Question

I have seen many questions on many forms regarding passing hyperlinks to JavaScript and only one or the other executing. There were no complete solutions that were both reusable and compact. My Answer below contains the solution.

Was it helpful?

Solution

Yes i am returning false both times to ensure that if JavaScript is enabled and the function is called, that the html href does not fire. The goal is to keep the current page from changing and call the requested link in a new tab. The way it is designed is to be reusable with any call passing a href. This way there is no looping through id's or tag names. This also keeps the code small and compact.

Here is the solution:

 <a onclick="return init(this.href)" href="http://..." >Something</a>

    <script>
   function init(href){
    if(window.open(href))
          {return false;}
    else {return false;}    
     }
    </script>

onclick will pass the href to init(), the return in the html if true will call the function and the href will both fire. This will result in the new tab and the current tab displaying the same thing. That's not what were looking for. The function will open the link into a new tab. It will return false no matter what forcing the html href not to execute. Thus the current tab will stay unchanged and the new tab will display the called link. If the user script is disabled only the html will fire displaying the link in the current tab.

This is browser compatible and completely reusable with any pass of a link.

I could not find any documentation that would achieve this so i have decided to post a solution that does not need an id or tagName.

Hope this helps those who are looking for an answer to a solution similar to this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top