Search code examples
javascripthtmlwindow.open

window.open() only works with input type but not on tags?


I'm trying to use window.open() to open a new window with tag but it doesn't seem to work. I'm new to programming so i get stuck a lot and this one especially doesn't let me find a solution. could anyone tell me what I am doing wrong?

javascript
var grid2Btn = document.getElementsByClassName('grid2__btn__container');
grid2Btn.addEventListener('click', function(){
    window.open('https://www.google.com/','google', 'top=100,left=100,width=300,height=400');
})

html
<button class="grid2__btn__container">
          <span><img class="magnifier" src="au-logos/search.png" alt="magnifier">click here<span class="new__window__logo"></span></span>
</button> 

Solution

  • document.getElementsByClassName() returns collection of elements.

    You can know it:

    • by checking the docs

    • by checking its real output

      const elements = document.getElementsByClassName('grid2__btn__container');
      console.log(elements);
      
    • reading the method name: getElementsByClassName().

    So, simply take the first array element of the result and then add an event listener to it.

    const elements = document.getElementsByClassName('grid2__btn__container');
    
    // Take the first element
    const grid2Btn = elements[0];
    
    grid2Btn.addEventListener('click', function() {
        alert('Button clicked');
        window.open('https://www.google.com/','google', 'top=100,left=100,width=300,height=400');
    });
    <button class="grid2__btn__container">
              <span><img class="magnifier" src="au-logos/search.png" alt="magnifier">click here<span class="new__window__logo"></span></span>
    </button>