Fresheyeball
Fresheyeball

Reputation: 30015

jQuery effect selector now and in the future WITHOUT an event

Here is an example usage, of what I am trying to do:

  $('img.switchToPng').each(function(){
       currentSRC = $(this).attr('src');
       $(this).attr('src', currentSRC.substr(0, currentSRC.length -3) + 'png');
  });

Later using ajax a new <img src="path/image.jpg" alt="blah" class="switchToPng" /> appears in the dom, I would like that to NOT require rerunning the selector and each function. With .on selectors in jQuery can live into the future, however I cannot find a way to use it without an event. I could use a 'load' event, but that would not be reliable as browser cache may prevent that from firing.

If this is possible, I can see many uses. Does anyone know a good answer to this?

Upvotes: 4

Views: 735

Answers (1)

Rob W
Rob W

Reputation: 349042

You have three options:

  1. Polling for the creation of new elements. [Example]
  2. Modifying the (jQuery) methods which insert the new element:

    var originalAppend = jQuery.fn.append;
    jQuery.fn.append = function() {
        // Function logic...
        return originalAppend.apply(this, Array.prototype.slice.call(arguments));
    };
    
  3. Using deprecated DOM mutation methods.

Upvotes: 2

Related Questions