1

I am writing some code with jQuery and trying to add an onclick event listener. When I run my code, the event listener runs once, but does not repeat itself. Why is this happening?

If I replace this with addEventListener('click'...) it works fine.

$(function(){
  var url = "https://www.bensound.com/bensound-img/jazzcomedy.jpg";
  var doSomething = {
  clickedNow: function(){
  alert("Clicked ok now");
  }
  };
  
  $('#click-me').attr('src',url);
  $('#click-me').onclick = doSomething.clickedNow();
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure>
<img id="click-me" alt="An image went missing here">
<figcaption><figcaption>
</figure>
Dhia
  • 10,119
  • 11
  • 58
  • 69
CoderBC
  • 1,262
  • 2
  • 13
  • 30
  • add event listener on click using jquery style, $('#click-me').on('click',doSomething.clickedNow); – A.T. Dec 15 '17 at 08:11

3 Answers3

2
  $('#click-me').onclick = doSomething.clickedNow();

Here you are setting the onclick event to equal the result of the function doSomething.clickedNow, which is not what you want.

What you want to do is add an event listener for the click event and execute your function in there.

try this:

$('#click-me').click(function(){
      doSomething.clickedNow();
  });

Even better would be to use "on" like so

$( "#click-me'" ).on("click", function() {
  doSomething.clickedNow();
});
MKougiouris
  • 2,821
  • 1
  • 16
  • 19
1

onClick is a JavaScript function that you're trying to add to a jQuery selector. If you really want to do it this way then you can do it by changing it to:

$('#click-me')[0].onclick = doSomething.clickedNow;

It might be better to use a jQuery click function like Code Lover suggested in their answer.

$(function(){

  var url = "https://www.bensound.com/bensound-img/jazzcomedy.jpg";
  var doSomething = {
    clickedNow: function(){
      alert("Clicked ok now");
    }
  };
  
  $('#click-me').attr('src',url);
  $('#click-me')[0].onclick = doSomething.clickedNow;
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure>
<img id="click-me" alt="An image went missing here">
<figcaption><figcaption>
</figure>
0

$(function(){
  var url = "https://www.bensound.com/bensound-img/jazzcomedy.jpg";
  var doSomething = {
  clickedNow: function(){
  alert("Clicked ok now");
  }
  };
  
  $('#click-me').attr('src',url);
  $('#click-me').click(function(){
      doSomething.clickedNow();
  });
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<figure>
<img id="click-me" alt="An image went missing here">
<figcaption><figcaption>
</figure>

You are using the jquery and in jquery there is .onclick thing. the right syntax is in the above code. Check that. It's working.

Code Lღver
  • 15,573
  • 16
  • 56
  • 75