snippet Archives - Justin Silver https://www.justinsilver.com/tag/snippet/ Technology, Travel, and Pictures Wed, 20 Apr 2016 00:04:54 +0000 en-US hourly 1 https://wordpress.org/?v=6.0.1 https://www.justinsilver.com/wp-content/uploads/2013/06/cropped-apple-touch-icon-160x160.png snippet Archives - Justin Silver https://www.justinsilver.com/tag/snippet/ 32 32 Inserting & Triggering Custom Events In jQuery Functions https://www.justinsilver.com/technology/inserting-triggering-custom-events-in-jquery-functions/?utm_source=rss&utm_medium=rss&utm_campaign=inserting-triggering-custom-events-in-jquery-functions https://www.justinsilver.com/technology/inserting-triggering-custom-events-in-jquery-functions/#respond Fri, 02 Oct 2015 20:13:45 +0000 http://justinsilver.com/?p=3937 I recently had the need to detect when new elements were appended to the DOM, however by default in jQuery there is no “append” event. This meant that the code I wanted to write,...

The post Inserting & Triggering Custom Events In jQuery Functions appeared first on Justin Silver.

]]>
AmpedSense.OptimizeAdSpot('AP'); AmpedSense.OptimizeAdSpot('IL'); AmpedSense.OptimizeAdSpot('IR');

I recently had the need to detect when new elements were appended to the DOM, however by default in jQuery there is no “append” event. This meant that the code I wanted to write, was invalid.

(function($) {
	$(document).on('append', function(){
		// handle the "append" event using the elements from the arguments
	});
})(jQuery);

The solution I ended up using involved caching the existing jQuery.append() to jQuery._append() and then overriding jQuery.append() to call the cached function internally, followed by the triggering of my new “append” event.

(function($) {
	// store a copy of the append() function as _append()
	$.fn._append = $.fn.append;

	// overwrite the existing append()
	$.fn.append = function () {
		return $.fn
			// apply the cached (function)ality using _append()
			._append.apply(this, arguments)
			// trigger our custom "append" event to fire handlers.
			.trigger("append", [arguments]);
	};
})(jQuery);

The post Inserting & Triggering Custom Events In jQuery Functions appeared first on Justin Silver.

]]>
https://www.justinsilver.com/technology/inserting-triggering-custom-events-in-jquery-functions/feed/ 0