Reputation: 91
I have a puzzling conundrum:
I have this JS: EDIT updated JS
$(".img-thumb").on("click", function(){ // exhibiting the same behaviour as .click()
thumbID = $(this).attr("id");
console.log(thumbID);
$(".gal-act").removeClass("gal-act");
$(this).addClass("gal-act"); // as suggested below
});
Which is meant to act on a piece of html inserted into a page using the .load() jquery function. The puzzle is that it works on the html when it's displayed as its original file (as here: http://keithneilson.co.uk/experimental/products/Data/prod-data.html, and yes I know there are images missing, no-one is meant to see this page on its own though). As you can see from that link the code is just meant to change the left border of the thumbnail to indicate which is selected for the moment, I'm going to add in the other functionality once I've got this puzzle solved.
Here is the same html inserted as a popup in the final page (click the red box beneath the slideshow): http://keithneilson.co.uk/experimental/products/. As you can see the images now work, but if you click the thumbnails again you'll see that the script is not acting (There's no log output either).
Now, it's the same html, and the same javascript, but it isn't working. My question is why, and is there a known workaround?
Upvotes: 0
Views: 77
Reputation: 1887
Let me answer why.
When you are using click function to bind event, it's binding the click event only on the element that are currently present in the DOM so when the ciick event got registered your html was not present in the DOM as it loaded later. So the event not got binded to your elements.
Try suggestions provided by @hexblot.
Update:
$('body').on('click', '.img-thumb', function(){
thumbID = $(this).attr("id");
console.log(thumbID);
$(".gal-act").removeClass("gal-act");
$("#"+thumbID).addClass("gal-act");
});
Upvotes: 1
Reputation: 10643
use the .on()
or .live()
instead of .click()
depending on jQuery version.
Edit: more on this jquery .live('click') vs .click()
Upvotes: 1