Ram Ram - 15 days ago 6
Javascript Question

How to Change div text to tooltip in bootstrap?

this is my div

<div class="classdiv">11</div>
<div class="classdiv">22</div>
<div class="classdiv">33</div>
<div class="classdiv">44</div>
<div class="classdiv">55</div>
<div class="classdiv">66</div>


i need to change this div text to tooltip using Jquery , because i can not change it manually , there are so many (http://getbootstrap.com/javascript/#tooltips). So that user cannot see the div's text first .When he hover this , text appear in tool tip .
I know how to make tool tip ,

<div class="classdiv" data-toggle="tooltip" data-placement="left" title="11">11</div>
$(function () {
$('[data-toggle="tooltip"]').tooltip()
})



But here the problem is that i cannot add manually
data-toggle="tooltip" and title to every classdiv, becuase there are
more than 500 div . so i need a solution in jquery , that cab add
data-toggle="tooltip" to every classdiv, and convert value to title.


Also how i can change this text to any attribute and assign this value for example
<div class="classdiv">11</div>
to
<div class="classdiv" val="11" ></div>

Please help.

Answer

You will have to loop all divs and set their respective tooltip text from the div text

TRY THIS DEMO

  // loop each classdiv and add data-toggle and title attributes
$('.classdiv').each(function(ndx, elem){
    var text = $(elem).text().trim();
    $(elem).attr('title', text);
    $(elem).text(''); // empty the text 
    $(elem).data('toggle', 'tooltip');
    $(elem).tooltip(); // activate bootstrap tooltip
})
.classdiv {
    width: initial;
    display: inline-block;
    margin: 45px 20px;
    padding: 10px;
    background: grey;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div class="classdiv">11</div>
<div class="classdiv">22</div>
<div class="classdiv">33</div>
<div class="classdiv">44</div>
<div class="classdiv">55</div>
<div class="classdiv">66</div>

Comments