Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

href="#" appends # on end of page url

Let's say I have the following link:

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

When clicked this link will alert a message as well as appending a pound sign on the end of the page url.
This doesn't look very pretty is there any way to avoid it besides using javascript in the url itself:

<a href="javascript:alert('You clicked a link.');">Click Me!</a>
like image 660
Web_Designer Avatar asked Dec 28 '22 22:12

Web_Designer


2 Answers

You have to prevent the default response from occurring.

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 nowadays is to call the proper method of the event property:

<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 best to replace that # with an URI to some proper page, for people not using JavaScript. In some jurisdictions, accessibility is in fact 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;
like image 62
Lightness Races in Orbit Avatar answered Jan 05 '23 11:01

Lightness Races in Orbit


The trick is return false on the event handler.

<a href="" onclick="alert('You clicked a link.'); return false">Click Me!</a>
like image 25
bradley.ayers Avatar answered Jan 05 '23 10:01

bradley.ayers