Twak
Twak

Reputation: 128

How do you open a new window when you click on the <a> tag in html

I don't mean like this

<a href="youtube.com" target="_blank">Youtube Link</a> 

I mean that when you click the a tag it opens a new window just like when you're paying with Paypal on another site.

enter image description here

So my code is

<a href="youtube.com">Youtube Link</a> 

Upvotes: 0

Views: 1680

Answers (3)

ash
ash

Reputation: 524

that should be done by javascript.

<a href="#" id="openWindow">Youtube</a>

let link = document.getELementById('openWindow');

link.addEventListener('click', function(event) {
   window.open("https://youtube.com/", "youtube");
});

more info for window MDN

Upvotes: 2

andersryanc
andersryanc

Reputation: 969

If you want to open in a totally new window (ie. a "popup") none of the HTML anchor (<a />) "target" values will work for this. Instead, you would need to use javascript, in this case, window.open (more info).

In the example below, I'm using a class and .querySelectorAll() so that you can reuse the class on any links you want to have this feature. I'm also keeping the href and target attributes on the anchor, so in case javascript is disabled or the user clicks the link before the page finishes loading it will still at least open the link in a new tab.

Keep in mind also, that the 3rd argument to the window.open() call is required to make the popup work, otherwise it will just open in a new tab like target="_blank". Also, feel free to adjust the 3rd argument options to your use case, however, for the "popup" to still work, you need to make sure that menubar=no is used OR leave that option out entirely.

<a href="https://youtube.com/" target="_blank" class="js-new-window">Youtube</a>

<script>
    const links = document.querySelectorAll('.js-new-window');
    links.forEach((link) => {
      link.addEventListener('click', function(event) {
        event.preventDefault();
        window.open(event.currentTarget.href, 'new-window', 'height=600,width=800,left=100,top=100,resizable=yes,scrollbars=yes,toolbar=yes,menubar=no,location=yes,directories=yes,status=yes');
      })
    });
</script>

Upvotes: 0

AlliterativeAlice
AlliterativeAlice

Reputation: 12577

Can be done by using the onclick attribute:

<a href="#" onclick="window.open('https://youtube.com/', 'yt', 'height=600,width=800')">Link text</a>

Upvotes: 2

Related Questions