Skip to content

Instantly share code, notes, and snippets.

@jonathanread
Created August 13, 2015 18:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonathanread/6fe5288afff136bb9204 to your computer and use it in GitHub Desktop.
Save jonathanread/6fe5288afff136bb9204 to your computer and use it in GitHub Desktop.
jQuery.fn.delayedAction = function (options) {
var settings = $.extend(
{},
{
delayedAction: function () { },
canceledAction: function () { },
hoverTime: 1000
},
options);
return this.each(function () {
var $this = $(this);
// Track hover state to ensure clicks are ignored until flyout is complete.
var canClick = false;
$this.click(function (e) {
if(!canClick)
e.preventDefault();
});
// Stop the eventual click on hover, and trigger the hover event.
$this.on("touchstart", function (e) {
$this.trigger('hover');
e.stopPropagation();
});
// Hover in actions
function hoverIn(e) {
if($(e.target).parent().children().length == 1){
canClick = true;
}
e.stopPropagation();
$this.data('timerId',
setTimeout(function () {
$this.data('hover', true);
settings.delayedAction($this);
canClick = true;
}, settings.hoverTime));
$this.data('hover', true);
}
// Hover out actions
function hoverOut() {
if ($this.data('hover')) {
clearTimeout($this.data('timerId'));
settings.canceledAction($this);
}
$this.data('hover', false);
canClick = false;
}
// Wire up hover events
$this.hover(hoverIn, hoverOut);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment