jangxx
jangxx

Reputation: 1019

html - How to prevent the browser from opening the link specified in href?

I currently making a filebrowser. If the user clicks on a link to a file a little window open and asks for options (like download and view). I've done this using the onclick attribute. If I click on the link the javascript is executed, but after this the url specified in href opens. What I'm trying to do is: If you click the link javascript get executed and forwards you eventually. But if the link gets rightclicked the "copy link location" should still be available. I'm thinking of solving this by blocking the forwarding scriptside. So if the link gets rightclicked no javascript is executed and you can copy the link location. But if you left click the link the javascript is executed and the link is not opened. Is that possible with javascript, or is there any other way of achieving this behavior?

Upvotes: 16

Views: 54895

Answers (4)

lexa-b
lexa-b

Reputation: 1939

you can replace href attribute by text "javascript:void(0)", for example:

<a href="http://..." id="somebutton">...</a>
<script>
document.getElementById('somebutton').href="javascript:void(0)"
</script>

Upvotes: 1

bobek
bobek

Reputation: 8020

You have to prevent default from your click function:

function stopDefAction(evt) {  
  evt.preventDefault();  
} 

Upvotes: 14

Bergi
Bergi

Reputation: 665316

Yes, you will need to prevent the default action of the event. You can do so by returning false in your onclick attribute.

Upvotes: 1

Armatus
Armatus

Reputation: 2191

In order to prevent the link executing, one way is to let the "onclick" method return false.

For example:

<a href="http://..." onclick="return clickfunc()">...</a>

If clickfunc() returns false, a click on the link will not direct to "http://..."

Although you are probably handling it more like

<a href="http://..." id="somebutton">...</a>
<script>
document.getElementById('somebutton').onclick = function() { 
      ... 
      else { return false; }
};
</script>

Upvotes: 20

Related Questions