Prashant Patil
Prashant Patil

Reputation:

Href and onclick issue in anchor link

I have anchor link with both href and onclick events specified. The onclick sets location.href to server URL and href to a other link.

When the link is clicked the href event gets called always but onclick event gets called only once (that is only for one anchor link). If I debug JavaScript it works properly that it calls both href and onclick. What can be the problem?

Upvotes: 4

Views: 37343

Answers (3)

miketosh
miketosh

Reputation: 11

For those who said "Why?", I have a reason. Middle clicks. Maybe you have AJAX that can get the details from the server and then prepare them in the same page, but if a middle-clicker wants to see that data in a new page, they are blocked.

So, Reports would provide the same functionality to users who want such a thing.

As a habitual middle-clicker, I hate tags with a passion. but I have found with GreaseMonkey, I can sometimes reassign the javascript href to the onclick, and try to parse a valid URL for the href. I really wish that opening Javascript in a new tab would just clone the page then run the code.

Upvotes: 1

Patrick McElhaney
Patrick McElhaney

Reputation: 59341

It sounds like you want the link to call a page that runs server-side code (such as PHP) and then direct the browser to another location. That's typically done by having the server-side script send a redirect response with the second URL.

Upvotes: 5

Jonathan Fingland
Jonathan Fingland

Reputation: 57187

Try

 <a href="whatever.html" onclick='window.location.href="http://whereverelse";return false;'>linky</a>

just to explain: returning false in this case prevents the default action.

Why would you want to do this though?

Upvotes: 12

Related Questions