tags:

views:

58

answers:

5

Below doesn't work on any browser. It supposed to show alert box. What am I doing wrong?

 <html>
 <head>
 <script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"&gt;&lt;/script&gt;
 <script type="text/javascript">
$('#prevlink').click(function () { 
  alert("Test"); 
});  
</script>
</head>
<body>
<a id="prevlink" href="#">test</a>
</body>
</html>
+2  A: 

You are not wrapping the function in a ready() event. It runs before the DOM exists.

Pekka
thanks on jquery documenttation it wasn't in ready()
nLL
+4  A: 

Put it in document.ready!

Mike Robinson
+1 Although the question technically is if the OP is crazy. :P
Ashish
oh, and you may want to return false from the click() handler if you don't want the page to navigate back to itself.
Dave Markle
A: 

change to

$(function()
{
  $('#prevlink').click(function () { 
    alert("Test"); 
  });
});
dmitko
A: 

Because the javascript code executed before the html finished downloading Use this instead as your code

$(document).ready(function(){
$('#prevlink').click(function(){
  alert("Test");
});
})
vener
A: 

You're trying to access the element before it exists (JavaScript is run inline with HTML parsing/rendering). You can either use the ready event that jQuery provides as Pekka and Mike pointed out, or just make sure you're trying to access the element after it exists:

<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"&gt;&lt;/script&gt;
</head>
<body>
<a id="prevlink" href="#">test</a>
<script type="text/javascript">
// By this time we get here, it exists.
$('#prevlink').click(function () { 
    alert("Test"); 
});  
</script>
</body>
</html>

The former (using a ready event or similar) is more "unobtrusive" and that's very useful when you're dealing with large teams, where your HTML designers and JavaScript coders are usually different people. The latter happens sooner (no small gap in time after the link appears and before you hook the click event), and so is what the Google Closure team recommend for hooking up element handlers.

Even when using the second method, you can keep your JavaScript and HTML reasonably separated, by ensuring that the script tag is just a call to set up the element and has no actual logic of its own.

T.J. Crowder