Sampat
Sampat

Reputation: 1309

jquery click function not getting called

Why is the click function not called?

    <html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Untitled Page</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" type="text/javascript" />
    <script type="text/javascript">
        $('#test').click(function () {
            alert('clicked');            
        });    
    </script>

</head>
<body>
    <a id="test" href="#">Click here</a>
</body>
</html>

Upvotes: 3

Views: 5620

Answers (3)

Headshota
Headshota

Reputation: 21449

you must have a closing script tag at:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js" 
type="text/javascript" >
</script>

and you must call your click binding in:

$(document).ready(function(){
  $('#test').click(function () {
        alert('clicked');            
    }); 
});

Upvotes: 4

texai
texai

Reputation: 3736

Wrap it this way:

$(function(){
    $('#test').click(function () {
        alert('clicked');            
    });    
});

in order to wait until DOM is ready to execute click function.

Upvotes: 2

Mauvis Ledford
Mauvis Ledford

Reputation: 42344

You are adding an event to an element that doesn't exist yet. Wrap your event listener in a DOM-ready function or move your script tag below the element.

Upvotes: 6

Related Questions