Search code examples
javascripthrefgetelementbyid

How to redirect the url twice with document.getElementById("ID").href?


Good Evening, This question is an extension for document.getElementById to include href I currently have a next hyperlinks and the next hyperlinks is using a javascript to overwrite the url. The first time I click the next hyperlinks, it works but when the second times I clicked it, it goes to the url which in the a tag but not the javascript. How can I make the next hyperlinks goes to the url which is in the javascript everytime I click it?

<script> 

//..
   function nextHyperLinks() {

          document.getElementById("nextID").href = "www.google.com";
   }
</script>

<HTML>
   //..
   <a href="www.yahoo.com" id="nextID" onclick="nextHyperLinks();">next</a>
</HTML>

If any things not clear, please let me know. Need some hints and advised, thanks.^^


Solution

  • Try this:

    function nextHyperLinks(e) {
      e.preventDefault();
      document.getElementById("nextID").href = "www.google.com"; // you probably don't need this if you will anyway navigate away from the page.
      window.open('http://www.google.com/', '_self');
    }
    
    var el= document.getElementsById('nextID');
    el.addEventListener('click', nextHyperLinks);
    

    and remove the inline onclick="nextHyperLinks();"