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?
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?
- I think you need more information. Why are you trying to send two requests with one anchor tag? What do you mean "gets called only once" -- only for one anchor tag, not all or only the first time, but not after the page is replaced? – tvanfosson Commented Jun 8, 2009 at 12:11
- It's completely unclear what your goal is. When you say onclick sets one location, and href - another, which location do you actually want user to go to? You realize he can't go to both locations on one page. By checking comments to some of the answer I get a feeling you want to take user to 1 location and then redirect to another. If yes, then redirect should be issued from server-side. I.e. if you have href="/target.html" and onclick="window.location='/action.call'" you have to put "/action.call" to href, and on server-side send HTTP status 302 redirect. Also, look up "redirect after post"! – mvmn Commented May 3, 2012 at 17:15
3 Answers
Reset to default 12Try
<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?
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.
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.