3

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>

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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');            
    }); 
});

1 Comment

+1 for catching the closing script tag. Although technically it could work the way he's doing it (with self-closing <script />), as long as he's serving the page as application/xhtml+xml
2

Wrap it this way:

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

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.