Created
October 17, 2012 16:23
-
-
Save raiden-dev/3906509 to your computer and use it in GitHub Desktop.
jQuery Plugin: Conditional Custom Events
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Conditional Custom Events | |
* jQuery Plugin | |
* based on setInterval() | |
*/ | |
;(function ($, window, undefined) { | |
// Define conditional events | |
function defineCondEvents(element, events) { | |
var intervals = []; | |
var delay = 10; | |
$.each(events, function(index, eventObj) { | |
if (eventObj['condition'] && eventObj['condition']) { | |
intervals.push( | |
setInterval(function() { | |
if (eventObj['condition'].apply(element)) { | |
if (!eventObj.occured) { | |
eventObj.occured = true; | |
$(element).trigger(eventObj['name']); | |
} | |
} | |
else { | |
if (eventObj.occured) { | |
eventObj.occured = false; | |
} | |
} | |
}, delay) | |
); | |
} | |
}); | |
return intervals; | |
} | |
// Remove defined conditional events | |
function removeCondEvents(element, events) { | |
$.each(events, function(index, intervalId) { | |
clearInterval(intervalId); | |
}); | |
return null; | |
} | |
// jQuery plugin wrapper | |
$.fn['condEvents'] = function (events) { | |
return this.each(function () { | |
var defined = $.data(this, 'condevents'); | |
if (!defined && events) { | |
$.data(this, 'condevents', defineCondEvents(this, events)); | |
} | |
else if (defined && !events) { | |
$.data(this, 'condevents', removeCondEvents(this, defined)); | |
} | |
else { | |
return false; | |
} | |
}); | |
} | |
}(jQuery, window)); | |
// Example of usage: | |
// defining 'scrollbar shows' and 'scrollbar hides' events for window | |
$(window).condEvents([ | |
{ | |
// event name | |
name: 'hscrollshows', | |
// condition for event triggering | |
condition: function() { | |
return ($('body')[0].scrollWidth > $(window).width()); | |
} | |
}, | |
{ | |
name: 'hscrollhides', | |
condition: function() { | |
return ($('body')[0].scrollWidth <= $(window).width()); | |
} | |
} | |
]); | |
// Adding events handlers | |
$(window).on('hscrollshows', function() { console.log('hscrollshows'); }); | |
$(window).on('hscrollhides', function() { console.log('hscrollhides'); }); | |
// Evoking method without params will remove all defined | |
// conditional custom events of element | |
//$(window).condEvents(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment