-1

I have the following code:

<!DOCTYPE HTML>
<html>
<head>
<script src="jquery-2.0.3.js"></script>
<script>
    $("div.a").click(function(){
        $(this).slideUp();
        });
</script>
</head>
<body>
<div class="a"> <p> aaa</p></div>
</body>
</html>

Why doesn't work? The function is the same like in jquery documentation.

Irina Farcau
  • 167
  • 10

1 Answers1

2

Code in script tags runs as soon as the browser parses the script tag, before the parser continues with the rest of the HTML (unles you use the defer or async attributes). So your code hooking up the event handler runs before the element exists, so nothing gets hooked up.

Move the script to the end of the HTML, just before the closing </body> tag:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<div class="a"> <p> aaa</p></div>
<!-- ...rest of page here... -->
<script src="jquery-2.0.3.js"></script>
<script>
    $("div.a").click(function(){
        $(this).slideUp();
    });
</script>
</body>
</html>

That way, the elements defined by the HTML exist as of when the script runs. More here: YUI Best Practices for Speeding Up your Website

If for some reason you don't control where scripts go, a second-best alternative is to use jQuery's ready callback.

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639