Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing tooltip title using jQuery

Help me out, as I am new to jQuery & web development. My requirement was to ellipsize(...) the long text in text boxes and then if mouse is hovered over them display the full text in tooltip.

For this I used Bootstrap's tooltip . What I did was the following :

Downloaded bootstrap js and included in my file like this :

 <script type="text/javascript" src="scripts/bootstrap.min.js"></script>        

Changed my elemnt like this

<input type="text" name="tooltip" id="samplebox" data-toggle="tooltip" title="Ankit" >

For Dynamically updating the title, I made use of jQuery

<script>
    $(document).ready(function(){
        $(" #samplebox ").mouseenter(function(){
            var word = document.getElementById("samplebox").value;
            $(" #samplebox ").attr('title', word);
        });     
    });
</script>

This works fine for that one element.

now I have to do the same thing for more text-boxes, whose number can keep on increasing. Now, I want to create a generic function where I can pass the id of that element and get it done for any textbox over which mouse is hovered.

like image 633
Ankit Avatar asked Jun 18 '15 09:06

Ankit


People also ask

How do I add a title to a tooltip?

Tooltips can be attached to any element. When you hover the element with your mouse, the title attribute is displayed in a little box next to the element, just like a native tooltip. But as it's not a native tooltip, it can be styled.

What is tooltip () method in jQuery?

The tooltip () method allows us the implementation of jQuery tooltip. It replaces the native tooltip which is set using the title attribute. There is also an option called content which can be used to specify the content.

How do I style tooltips?

Tooltips can be attached to any element. When you hover the element with your mouse, the title attribute is displayed in a little box next to the element, just like a native tooltip. But as it's not a native tooltip, it can be styled. Any themes built with ThemeRoller will also style tooltips accordingly.

How to modify the title value of a jQuery page?

Try to modify the title value by calling jQuery's data ("title") method. Show activity on this post. I also struggled with this. And this code worked for me: Please note the upper case T. Lower case T will not work.


1 Answers

If there are no style classes, use the attribute-selector. For a tooltip, there's also the attribute value of data-toggle="tooltip":

$(document).ready(function(){
    $("[data-toggle=tooltip]").mouseenter(function () {
        var $this = $(this);
        $this.attr('title', $this.val());
    });   
});

Demo

Note: For the use with Bootstrap's tooltip you may have to change the attribute data-original-title instead if title to update the content of your tooltip. Have a look at this question

like image 56
empiric Avatar answered Nov 04 '22 21:11

empiric