Reputation: 1244
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.
Upvotes: 34
Views: 77740
Reputation: 1438
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.
Upvotes: 0
Reputation: 11619
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).
Upvotes: 0
Reputation: 5636
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
Upvotes: 3
Reputation: 4742
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;
});
Upvotes: 85
Reputation: 370
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
});
})
Upvotes: 7