34

I'm building a web application that is extendable by dropping scripts into a preset directory. The script needs to read file headers before going to a page, so I need to use .preventDefault() when links are clicked and run some JScript first. Unfortunately I can't get past the .preventDefault()

Here's my link format:

<a href="path/to/file.php" class="filelink">Some Text</a>

here's the jquery I'm trying to use to stop the default action:

    $( '.filelink' ).click( function( e ) {
        e.preventDefault();
        //do some other stuff here
    });

EDIT:

More Info:

The <script>...</script> is in my footer. This function is INSIDE $(document).ready AFTER a $.ajax call that builds the list of links this function is trying to listen for clicks of.

8
  • 1
    you're missing a closing ) in your jquery statement. the click event is never fired because of a syntax error. Commented Jan 9, 2015 at 23:14
  • lol, was actually in there editing it when you commented. I just mistyped it on entering it here. it now looks exactly as it does in myscript, but is not firing. Commented Jan 9, 2015 at 23:16
  • I rolled back the edit because it wasn't clear yet that the typo was just in question or in actual code at the time of edit. As written, with the fixed typo, i see no reason for the problem you describe. Commented Jan 9, 2015 at 23:17
  • Where is the <script>...</script> located? Commented Jan 9, 2015 at 23:21
  • 3
    Duplicate of Event binding on dynamically created elements? (can't vote to close anymore, someone else please do it (@KevinB)). Commented Jan 9, 2015 at 23:33

5 Answers 5

85

Since your links are appended dynamically to the page, you need to use document.on() to capture the click events.

the syntax for appending event listeners to dynamic content is as follows

$(document).on( event, selector, callback );

so your click handler would become:

$(document).on('click','.filelink',function(e){

 e.preventDefault();

 //code here

 return false;

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

8 Comments

because the element doesn't exist when you create the clickhandler, ie at the time dom loaded. jQuery doesn't listen for new elements in the selector list, it would be horribly innefficient and would crash on pages with dynamic content.
the return false is not actually necessary. preventDefault() should be sufficient.
@RichardN: I recommend to read the documentation: "Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()."
@r3wt: You are right. return false; is equivalent to calling event.preventDefault(); event.stopPropagation();.
@amenthes to add to r3wt's remark, actually the return false prevents the #hashtag hyperlink to be displayed on the address bar which sometimes is strictly unwanted. probably for this case it's unnecessary, but just adding two cents here :)
|
7

I think you missed $(document).ready()

Please update your code as following:

$(document).ready(function(){
     $( '.filelink' ).click( function( e ) {
        e.preventDefault();
        //do some other stuff here
    });

})

Comments

3

is your code surrounded by:

$(function(){

//your code here

});

? or

$(document).ready(function(){

//your code here

});

? , because you should wait until the <a></a> element is ready before adding your click listener to it. try the code above or place your code at the bottom of the html right before the </body> tag or just right after the <a></a> element. that should work

EDIT: since your links are added dynamically call your $( '.filelink' ).click() function right after they are added

2 Comments

you don't have to wait until the dom is ready before adding event listeners, you just need to ensure that the code executes after the element exists.
@SpencerWieczorek Kevin was saying the script has to be AFTER the <a>, which is correct, and doesn't have to be in document.ready
0

I had the same problem, because I changed the window.location.search in my event handler:

 $( '.filelink' ).click( function( e ) {
        e.preventDefault();
       window.location.search = "something";
 });

To fix my problem I used window.location.hash (which is more what I wanted anyway).

Comments

0

For me, the issue was a syntax error in the Javascript code.

I substituted a php variable to one of the JS variable like below,

var myvar = "<?php echo $myvar; ?>";

which produced the below result,

var myvar = "value in "myvar" which is not escaped";

It worked when I escaped the variable.

Please check if there is any syntax error in your code.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.