Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cancel navigation when user clicks a link (<a> element)?

Tags:

jquery

I'm trying to load some stuff using AJAX when a user clicks a link, but I want the link to actually go somewhere so that the app still works when javascript is disabled. Is there any way to just do something with javascript and cancel navigation when a link is clicked?

What's the best practice? Can that be done, or do I need to replace the link using javascript or what?

like image 665
Max Schmeling Avatar asked May 15 '09 00:05

Max Schmeling


People also ask

How would you stop a link from causing navigation when clicked?

One way you can prevent navigation is to implement an click / onclick JavaScript event handler and return false from it. Alternately you can use event. preventDefault() inside the click event's event object passed into the handler too.

What is JavaScript void 0?

What Does JavaScript Void 0 Mean? JavaScript void 0 means returning undefined (void) as a primitive value. You might come across the term “JavaScript:void(0)” while going through HTML documents. It is used to prevent any side effects caused while inserting an expression in a web page.

How do I stay in the same page after clicking links?

usually href's ar used to transfer the request to another page.. If you want to redirect another page still the existing page remain open use target attribute.. If you dont want to redirect anywhere and still want send a signal while clicking the text, use onclick on the text and not the href.

Can we give id to anchor tag?

The id and name attributes share the same name space. This means that they cannot both define an anchor with the same name in the same document. It is permissible to use both attributes to specify an element's unique identifier for the following elements: A , APPLET , FORM , FRAME , IFRAME , IMG , and MAP .


1 Answers

If you have HTML like this:

<a href="no_javascript.html" id="mylink">Do Something</a> 

You would do something like this with jQuery:

$(document).ready(function() {     $('#mylink').click(function() {         doSomethingCool();         return false; // cancel the event     }); }); 

All you have to do is cancel the click event with Javascript to prevent the default action from happening. So when someone clicks the link with Javascript enabled, doSomethingCool(); is called and the click event is cancelled (thus the return false;) and prevents the browser from going to the page specified. If they have Javascript disabled, however, it would take them to no_javascript.html directly.

like image 174
Paolo Bergantino Avatar answered Sep 29 '22 21:09

Paolo Bergantino