Aleksei Akireikin
Aleksei Akireikin

Reputation: 1997

How on/live event in JQuery actually works?

I am trying to write a plugin, that will bind some loading animation to pictures before they are loaded from the server. It works fine, except some cases. I mean changing of the DOM structure. The logic of my plugin is:

(function( window ){

'use strict';

var $ = window.jQuery;
var console = window.console;
var hasConsole = typeof console !== 'undefined';

var methods = {
    // plugin initialization
    init : function( options ) {
        return this.each(function(){
            methods._applyImagepreloader.apply( this, options);
        });
    },
    // working with each object
    _applyImagepreloader: function() {
        // if has class imagepreloader, do nothing
        if ($(this).hasClass('imagepreloader'))
            return;
        // if the image has determined size
        var width = $(this).width();
        var height = $(this).height();
        $(this)
            .clone()
            .attr('src', 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7')
            .attr('width', width)
            .attr('height', height)
            .addClass('imagepreloader')
            .insertAfter(this);
        $(this).hide();
        $(this).load(function(){
            $(this).next('.imagepreloader').remove();
            $(this).fadeIn();
        });
    }
};

$.fn.imagepreloader = function( options ) {
    return methods.init.apply( this, options );
};

})( window );

Now, when the page is being updated by AJAX and new image tags appear, my plugin does not work. I made an investigation and learned, that the DOM mutation events can help me, but, as I understood, they are not supported by all browsers. Moreover, I can catch changin of DOM structure, using setinterval, but I guess It is not the best practice. So, maybe the issue has been already solved in JQuery on/live events. I wonder, how they work. How they can catch an appearance of new DOM elements?

Upvotes: 0

Views: 65

Answers (1)

Adil Shaikh
Adil Shaikh

Reputation: 44740

When you use event delegation with on, event is always attached to a static element which is not going to be loaded dynamically

$("#Container").on('click','#dynamicallyAddedChildOfContainer',function(){...});

For example #Container in above example is the container which is present in DOM and you are adding #dynamicallyAddedChildOfContainer dynamically, Now when you click on dynamically added element, the event bubble's up to the container and that is where the event is triggered.

More on event delegation -

Upvotes: 1

Related Questions