views:

55

answers:

3
<script type="text/javascript">
$("a.filef").click(function(e){
    alert('hi, it works');
    return false;
});

</script>


<a class="filef" href="" rel="1">A</a>
<a class="filef" href="" rel="2">V</a>
+3  A: 

You need to make sure the elements exist first. Try this instead:

$(function(){
  $("a.filef").click(function(e){
    e.preventDefault();
    alert("Hi, it works.");
  });
});

Placing your code within:

$(function(){
  /* here */
});

Causes it to wait until the DOM is finished loading before it runs. In your case, it waits until the links exist before it attempts to bind logic to them.

In some scenarios you will need to run the code before the object exists. This is the case with many ajax-enabled websites. In those cases, jQuery has the $.live() method, which is of a similar look:

$(function(){
  $("a.filef").live("click", function(e){
    e.preventDefault();
    alert("Hi, it works.");
  });
});

Using this, it doesn't matter if the elements already exist, or will show up sometime in the future. Unless you're working with ajax or late-created elements, I would suggest sticking with the first solution.

Jonathan Sampson
I am sorry, I havent worked on jquery. Will putting the OP's function below the `<a id="filef">...` work as well?
shahkalpesh
Lol... can't bring yourself to type it out `$(document).ready` :) +1 for catching the problem and for using `e.preventDefault()` instead of `return false`.
Doug Neiner
@shahkalpesh Yes, it will.
Doug Neiner
@Doug: Those cursed chars shall never find a place in my code :)
Jonathan Sampson
A: 

Your same code is working for me, check out:

http://jsbin.com/axivo3

Put your js code at the bottom of the page or use jquery's ready event which is fired after DOM is available.

Sarfraz
Thats because JSBin adds the JS at the end of the HTML. The DOM is finished by that point. Try this revision to see it fail: http://jsbin.com/axivo3/2
Doug Neiner
that's because you have put the script element after the anchor elements.
ardsrk
It's working because jsbin places the Javascript *after* the elements.
Jonathan Sampson
Holy triple-play, Batman!
Jonathan Sampson
agreed guys, i noticed it afterwards, thanks
Sarfraz
A: 

Wrap your script in a function and pass it as an argument to $(document).ready(function) or you could write the same as an anonymous function inline.

<script type="text/javascript">
$(document).ready(function(){
 $("a.filef").click(function(e){
    alert('hi, it works');
    return false;
 });
});
</script>
ardsrk