Search code examples
javascripthtmldropdownwindow.open

How to open link in new tab from dropdown


I'm trying to have items in a dropdown list open in new tab using the javascript function below. As of now, a drop-down list is displayed from where each item will open only in the same window.

Any help would be much appreciated!

HTML

<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Button Name</button>
<div id="myDropdown" class="dropdown-content">
  <a href="">Choice A</a>
  <a href="">Choice B/a>
 </div>
</div>

JS

function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}

Solution

  • You don't need JavaScript at all. Just set the target attribute to _blank in your <a> tags like so:

    function myFunction() {
      document.getElementById("myDropdown").classList.toggle("show");
    }
    .show{
      display:block !important;
    }
    #myDropdown{
      display:none;
    }
    <div class="dropdown">
    <button onclick="myFunction()" class="dropbtn">Button Name</button>
    <div id="myDropdown" class="dropdown-content">
      <a href="https://choice.a" target="_blank">Choice A</a>
      <a href="https://choice.b" target="_blank">Choice B</a>
    </div>
    </div>