Reputation: 4642
The following jQuery is not working as expected. I'm simply trying to fire an event when an image is clicked.
$(document).ready(function () {
alert("document.ready has fired");
$("img").click(function () {
alert("image has been clicked");
});
});
I see the "document.ready has fired" alert when the page loads, so jQuery and my custom .js file are referenced correctly.
I suspect I'm missing something really obvious, but what?
Update:
The jQuery is correct (works in a new page but not on my existing page), as I workaround for now I have used the onclick
on the <img>
tag since this had to be a 'quick fix', I will look into what has happened though, thanks everyone for your input.
Upvotes: 1
Views: 2259
Reputation: 1557
I tend to use jQuery's bind function as then if anythings dynamically changed in the DOM it will still pick up the event as I've also had issues in the past using jQuery's .click function which resulted in this same problem.
$(document).ready(function () {
alert("document.ready has fired");
$("img").bind('click', function () {
alert("image has been clicked");
});
});
Upvotes: 0
Reputation: 1465
Just a guess:
Try this:
$("img").each(function(){
$(this).click(function () {
alert("image has been clicked");
});
});
Upvotes: 0
Reputation: 35223
In case all your images arent loaded direclty on page load you can try this
$(window).load(function () {
alert("window.load has fired");
$("img").click(function () {
alert("image has been clicked");
});
});
or
$("body").on("click", "img", function () {...
Upvotes: 1