I stopped short of giving my PC a bath when for some strange reason, the jQuery selectors I was using weren’t working. Thing is when doing basic testing for jQuery, you’ll write something to console.log (either that or you’ll put an alert and wait for it to annoyingly pop-up ). Things were so bad, I did both! Many, many hoops later, I realised that the selector worked for all content not loaded by AJAX. Lightbulb! Quick fix:

For content that’s being loaded dynamically, you need to use a technique known as event-delegation

Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.

e.g.

jQuery("#TheParentSelector").on('click',"#dynamicallyLoadedSelector",function(){
/*Go on, do your thing*/
console.log("Just doing ma thing");
});

Note:

#TheParentSelector is a selector that’s already on the page. It isn’t loaded dynamically

“on” is supported in Jquery 1.7+

But my content isn’t dynamic

Are you targeting them correctly? Sure?

Is your script wrapped in an ‘onLoad’?


$( document ).ready(function() {
// You, doing your thing
});

Do you have any special characters in your selector? You need to escape them with \\ {jQuery(“#Selector\\~”)}

Leave a Reply

Your email address will not be published. Required fields are marked *