sємsєм sємsєм - 1 year ago 138
jQuery Question

Bootstrap tooltip dynamic placement

I'm using Bootstrap tooltip through attribute selector. i.e any element has

attribute should be rendered as a tooltip:

$('[title]').tooltip({placement: 'bottom', trigger: 'hover'});

However, for some reasons and for some elements I would like to change the placement. Originally, I did not used
attribute for the elements, but for elements that I want its tooltip to have diifirent placement other than the default, I supplied them with
attribute and I modified the above code to be like the following:

$('[title]').tooltip({placement: (typeof $(this).attr('data-placement') === 'undefined')? 'bottom' : $(this).attr('data-placement'), trigger: 'hover'});

This code should set the placement to be
for elements that has no
attribute, while set it equals to its value for elements that has that attribute.

However, the code does not work as expected, it set placement = bottom for every element even,for example, those has

Answer Source

The placement's callback function receives 2 arguments - the first one is the tooltip argument and the second is the original element.
You can use this element to get the data you are looking for:

  placement: function(t_el, el) {
    return (typeof $(el).data('placement') === 'undefined') ? 'bottom' :  $(el).data('placement');
  }, trigger: 'hover'
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>

<div style="margin: 35px 55px;">

  <button type="button" class="btn btn-default" data-placement="left" title="Tooltip on left">Tooltip on left</button>

  <button type="button" class="btn btn-default" data-placement="top" title="Tooltip on top">Tooltip on top</button>

  <button type="button" class="btn btn-default" data-placement="bottom" title="Tooltip on bottom">Tooltip on bottom</button>

  <button type="button" class="btn btn-default" data-placement="right" title="Tooltip on right">Tooltip on right</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download