MrMangado
MrMangado

Reputation: 993

Issue with JQuery DOM and .click()

This is the code:

<html>
<head>
 <script type="text/javascript">
       $(document).ready(function(){
           $("#favorite").click(function(){
                     alert('click!')
           });
       });

 </script>
</head>
<body>

   <h4>Favourites <small><%= photo.fav %></small></h4>  
   <button id="favorite" class="btn btn-inverse">Favorite</button> 

</body>
</html>

When I click the button, I don't get the alert window, so I think is a problem with the DOM tree, How can I resolve this...?

Thank's advance!

Upvotes: 0

Views: 88

Answers (4)

SpaceBeers
SpaceBeers

Reputation: 13947

Or... You're not including jquery...

EDIT: Sarcasm aside, include the JQuery library before your code to be able to use it.

https://developers.google.com/speed/libraries/devguide

Here's an example of how it should looks... It works fine.

http://jsbin.com/osijok/1/edit

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
 <script type="text/javascript">
       $(document).ready(function(){
           $("#favorite").click(function(){
                     alert('click!')
           });
       });

 </script>
</head>
<body>

   <h4>Favourites <small><%= photo.fav %></small></h4>  
   <button id="favorite" class="btn btn-inverse">Favorite</button> 

</body>
</html>

Upvotes: 4

Ryan
Ryan

Reputation: 14649

How can I resolve this...?

Use plain JavaScript

(function(){
  document.getElementById("favorite").onclick = function() { alert('clicked'); }
}());

Upvotes: 0

Jamie
Jamie

Reputation: 1

You need to import the jQuery JS Library to be able to use functions such as

    $(document).ready(function(){ .. etc.

Upvotes: 0

AGDM
AGDM

Reputation: 104

Pretty simple. You don't have the JQuery library loaded on your page prior to executing methods from that library it looks like.

Upvotes: 0

Related Questions