Skip to content

Instantly share code, notes, and snippets.

@alekseyg
Last active April 20, 2017 02:13
Show Gist options
  • Save alekseyg/d2261e42a9b5335a8ce0774b4d92f129 to your computer and use it in GitHub Desktop.
Save alekseyg/d2261e42a9b5335a8ce0774b4d92f129 to your computer and use it in GitHub Desktop.
Make tooltips work on iOS by using touch events and ignoring mouse events
;(function ($) {
var wasTapped = function wasTapped (element) {
var touchStart = element.data('lastTouchStart')
var touchEnd = element.data('lastTouchEnd')
return (
touchStart && touchEnd &&
touchEnd.timeStamp - touchStart.timeStamp <= 500 && // duration
Math.abs(touchEnd.pageX - touchStart.pageX) <= 10 && // deltaX
Math.abs(touchEnd.pageY - touchStart.pageY) <= 10 // deltaY
)
}
var initTooltip = function initTooltip () {
$('[data-toggle="tooltip"]').tooltip({trigger: 'manual'})
.on('show.bs.tooltip', function () {
$(this).data('tooltipShown', true)
})
.on('hide.bs.tooltip', function () {
$(this).data('tooltipShown', false)
})
.on('touchstart', function (e) {
var $this = $(this)
$this.data({
lastTouchStart: e.originalEvent,
wasTouchedRecently: true
})
setTimeout(function () {
$this.data('wasTouchedRecently', false)
}, 300)
})
.on('touchend', function (e) {
e.preventDefault()
var $this = $(this)
$this.data({
lastTouchEnd: e.originalEvent,
wasTouchedRecently: true
})
setTimeout(function () {
$this.data('wasTouchedRecently', false)
}, 300)
if (wasTapped($this))
$this.tooltip('toggle')
})
.on('mouseenter', function () {
var $this = $(this)
if (!$this.data('wasTouchedRecently'))
$this.tooltip('show')
})
.on('mouseleave', function () {
var $this = $(this)
if (!$this.data('wasTouchedRecently'))
$this.tooltip('hide')
})
$('body')
.on('touchstart', function (e) {
$(this).data('lastTouchStart', e.originalEvent)
})
.on('touchend', function (e) {
var $body = $(this)
$body.data('lastTouchEnd', e.originalEvent)
$('[data-toggle="tooltip"]').each(function () {
var $tooltip = $(this)
var target = $tooltip.closest('[data-toggle="tooltip"]').get(0)
if ($tooltip.data('tooltipShown')
&& e.target !== target && wasTapped($body)) {
e.preventDefault()
$tooltip.tooltip('hide')
}
})
})
}
$(initTooltip)
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment