jQuery – why isn’t this simple function working?

Mar 13, 2012   //   by phpfreelancer.biz   //   Blog, Jquery Tutorial  //  No Comments

I’m building a web application and I’ve decided to have a fiddle with jQuery and Javascript – something I’ve never really used before.

I have included jQuery in my header using Google Libraries:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>

And now I’m fiddling with the SIMPLEST of jQuery but it’s not working.

<p><a href="#" id="lovecounter"><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></a></p>

<script type="text/javascript">

$("#lovecounter").click(function() {
  alert("Click");
});         

</script>

I am clicking on the lovecounter link but there is no alert. If I add simple javascript to the actual anchor tag it works though.

<p><a href="#" id="lovecounter" onclick="alert('test')"><?php if ($post->love) { echo $post->love; } else { echo 0; } ?></a></p>

Any ideas? What am I doing wrong?

Wrap your code in ready handler:

$(document).ready(function(){
  $("#lovecounter").click(function() {
    alert("Click");
  });     
});

Leave a comment

Share This Post

RSS Wordpress News