Search code examples
javascriptjquerytwitter-bootstraptooltiptwitter-bootstrap-tooltip

Enable/Disable dynamic bootstrap tooltip


I want to make tooltip work for dynamic content. But I also want to enable/disable depending on the screen size.

What I want to happen: If the screen is less than 768 I want to disable the tooltip. If the screen is greater than 768 I want it to be enabled.

So far I have this:

function tooltip(){
  if (window.innerWidth <= 768) {
    $('[data-toggle="tooltip"]').tooltip("disable");
  } else {
    $('body').tooltip({
      selector: '[data-toggle="tooltip"]'
    });
  }
}

Solution

  • Since you are using tooltip delegation and because we cannot change element attributes in media queries, you need to destroy / regenerate each tooltip when the viewport width changes.

    Tooltips that use delegation cannot be individually destroyed but must be removed by $('body').tooltip('destroy') / $('body').tooltip('dispose') in 4.x.

    Now setup your tooltip() function as a onresize handler that reset the selector when the viewport width is below the accepted range. Instead of an empty selector you could return trigger: 'manual' or even better not initialise the tooltips at all :

    window.onresize = tooltip = function() {
      $('body').tooltip('destroy')
      $('body').tooltip({
       selector: window.innerWidth > 768  ? '[data-toggle="tooltip"]' : ''
      })
    }
    tooltip()
    

    Demo in iframe here -> http://jsfiddle.net/gpmcxaeL/2/


    NB: The above should only be used in an environment where the user dynamically can change the size of the viewport. To have different rules for tooltips on mobile, desktop and so on, solve this in declarative markup / responsive design.