Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery $("img").click(function() selector not working

For some reason when I click on an image with this JQuery code the alert screen doesn't show up.

HTML:

<div id="example1">
 <div>
  <div>
   <div class="user">
    <img class="Image" src="images/image.jpg">
   </div>
  </div>
 </div>
</div>

Javascript:

$(document).ready(function(){
 $("img").click(function(){
  alert("it works!");
 });
});

I cant figure out why this isn't working I included the jquery library and the <script> tag is under the div

like image 298
Stefan Avatar asked Sep 29 '14 11:09

Stefan


People also ask

What is the difference between .on click function ()) and .click function?

on('click') event in jquery . on('click') is different from . click(), there it has the capacity to create delegated event handlers by passing a selector parameter, while . click() does not.

Why click is not working?

Update Mouse Drivers It's prudent to make sure your mouse drivers are always up-to-date. If the left click isn't working, you definitely need to check them. Right-click on the Start Menu and then choose Device Manager.

What is the difference between .click and .on (' click in jQuery?

So onclick creates an attribute within the binded HTML tag, using a string which is linked to a function. Whereas . click binds the function itself to the property element.

How do you click a button in JQ?

To trigger the onclick function in jQuery, click() method is used. For example, on clicking a paragraph on a document, a click event will be triggered by the $(“p”). click() method. The user can attach a function to a click method whenever an event of a click occurs to run the function.


2 Answers

the img isn't in the DOM when your event handler is registered. you can use $('body').on('click','img',function(){alert('it works');})

like image 197
electrophanteau Avatar answered Oct 22 '22 14:10

electrophanteau


Rather than run your code in document.ready(), you should use window.load() function instead.

$(window).load(function() {
    $("img").click(function(){
        alert("it works!");
     });
});
  • document.ready() is a jQuery event, it runs when the DOM is ready, e.g. all elements are there to be found/used, but not necessarily all content.
  • window.load() fires later (or at the same time in the worst/failing cases) when images and such are loaded, so if you're using image dimensions for example, you often want to use this instead.
like image 34
Biosopher Avatar answered Oct 22 '22 14:10

Biosopher