A few days ago I posted this question:
My last question about ajax link vs normal link
It was about making links work for JavaScript enable browser (AJAX) and normal link for non-JavaScript browsers or crawlers.
Now I found that this method work for me and is also recommended by Google. This is what I do:
<a href="/some/page.php" onClick="jsfunction():return false">My Link</a>
Now what I like about this is that it is working exactly how I need it to work. But if I was to use an event handler with jQuery. I would do something like this:
<a href="/some/page.php" id="mylink">My Link</a>
<script>
$("#mylink").live(\'click\', function(){
my_function();
})
</script>
I want to know how to prevent my page from reaching the target /some/page.php when JavaScript is enable and not using the onClick event with a return false like the previous case.
I was also wondering how to do the same with forms. When I click the submit button and JavaScript is enable I don't want the form to perform the action.
I'm trying to make a site that is working with and without JavaScript enabled browser. The only difference is that JavaScript enabled browser will use AJAX and the others not.
Use preventDefault(), like this:
<script>
$("#mylink").live('click', function(event) {
event.preventDefault();
my_function();
});
</script>
Note that you have to have event as a parameter to the function for this sample code to work. Also, I don't know why you had escaped your ' (maybe this code is generated by another script somehow?), but you don't need it unless you're doing something strange.
This part isn't technically your answer, but it's also important: live() is deprecated, as pointed out in the comments. The best way to do this is with event delegation and on(), like this:
<script>
$('body').on('click', '#mylink', function(event) {
event.preventDefault();
my_function();
});
</script>
Looks like you should use method event.preventDefault().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With