Click Me! Clic...">

Href = "#" adds # to the page url

Let's say I have the following link:

<a href="#" onclick="alert('You clicked a link.');">Click Me!</a> 

Clicking this link will display a message and add a pound sign at the end of the page URL.
This doesn’t look very pretty - is there any way to avoid this other than using javascript in the url itself:

 <a href="javascript:alert('You clicked a link.');">Click Me!</a> 
+4
source share
2 answers

The return false trick in the event handler.

 <a href="" onclick="alert('You clicked a link.'); return false">Click Me!</a> 
+4
source

You must prevent the default response.

The old-fashioned approach is to return false from it:

 <a href="#" onclick="alert('You clicked a link.'); return false;">Click Me!</a> 

Or better:

 <a href="#" id="myLink">Click Me!</a> <script type="text/javascript"> window.onload = function() { document.getElementById('myLink').onclick = function(event) { alert('You clicked a link.'); return false; }; }; </script> 

The best approach right now is to call the correct event property method:

 <a href="#" id="myLink">Click Me!</a> <script type="text/javascript"> window.onload = function() { document.getElementById('myLink').onclick = function(event) { alert('You clicked a link.'); event.preventDefault(); // <--- }; }; </script> 

It’s also better to replace this # with a URI with the page you need, for people who don’t use JavaScript. In some jurisdictions, accessibility is actually a legal requirement.

Edit Fixed for bleedin 'IE:

 function f() { document.getElementById('myLink').onclick = function(e) { alert('You clicked a link.'); if (!e) { var e = window.event; } // e.cancelBubble is supported by IE - this will kill the bubbling process. e.cancelBubble = true; e.returnValue = false; // e.stopPropagation works only in Firefox. if (e.stopPropagation) { e.stopPropagation(); e.preventDefault(); } }; window.onload = f; 
+6
source

Source: https://habr.com/ru/post/1347459/


All Articles