Search code examples
javascripttwitter-bootstrap-3touch-eventbootstrap-popover

Different Behaviors for Touch and Click


I'm using Bootstrap Popovers to supply "help text" in my UI.

My existing JavaScript:

// add "tooltips" via popover
$('[data-toggle="popover"]').popover({
    container: 'body',
    trigger: 'hover',
    placement: 'auto bottom'
});

The Popover displays when I hover with a mouse or touch the element. My problem is with anchor tag elements. If the Popover is triggered by a touch event:

  1. Don't follow the link
  2. Add an anchor tag element to the Popover text to give access to the underlying link

Solution

  • I'd detect whether the user is on a touch device, then serve different content from data attributes. Use Popover methods to trigger your various actions.

    <a href="#" 
      data-href="http://jsfiddle.net" 
      data-toggle="popover" 
      title="A popover title" 
      data-hover-content="No link here." 
      data-touch-content="<a href='http://jsfiddle.net'>
        A link here</a>.">A popover link
    </a>
    
    var is_touch_device = 'ontouchstart' in document.documentElement;
    
    $('[data-toggle="popover"]').popover({
        container: 'body',
        trigger: 'manual',
        placement: 'auto bottom',
        html: true,
        content: function () {
            if (is_touch_device) {
                return $(this).attr('data-touch-content');
            } else {
                return $(this).attr('data-hover-content');
            }
        }
    })
    .on('mouseenter touch', function (e) {
        $(this).popover('show');
    })
    .on('mouseleave', function () {
        $(this).popover('hide');
    })
    .on('click', function () {
        if (!is_touch_device) {
            window.location.href = $(this).attr('data-href');
        }
    });
    

    Fiddle demo

    This can probably be simplified a bit. You could specify your content in the content function instead, of course.