简体   繁体   中英

HTML button click opening 2 links in new tab

I have these buttons on frontend and only one is visible at a time. .btn-active hides the button.

<a href="https://example.com/shop/" target="_blank" id="starter-monthly" class = "package1">Buy Now</a>
<a href="https://example.com/shop/" target="_blank" id="starter-yearly" class = "package2 btn-active">Buy Now</a>

on button click, I wanted to open the package link by concatenating package id in href in jquery.

jQuery('#starter-monthly').on('click', function(e) {
        var href = jQuery(this).attr('href');
         window.open(href + '?package='+24);
});
    jQuery('#starter-yearly').on('click', function(e) {
        var href = jQuery(this).attr('href');
         window.open(href + '?package='+27);
});

but when I click the button, it opens 2 links in 2 separate tabs which are https://example.com/shop?packag=24 and https://example.com/shop/

I wanted to open only one link which is https://example.com/shop?packag=24

What I am doing wrong? Any solution?

Clicking on an anchor element ( a tag) instructs the browser to open the link. Having target attribute further tells the browser to open it in a new window/tab. Now your code captures the click event and explicitly opens a new window (with proper url). However, that doesn't prevent the browser from carrying out the original action intended for all 'anchor' tags.

Basically you see two tabs opening, because one is opened by your code, and the other one by browser because of the click on anchor tag. You can suppress the default browser behaviour by calling preventDefault on the event object passed to your handler. Your code should be something like this:

jQuery('#starter-monthly').on('click', function(e) {
        e.preventDefault();
        var href = jQuery(this).attr('href');
        window.open(href + '?package='+24);
});

jQuery('#starter-yearly').on('click', function(e) {
        e.preventDefault();
        var href = jQuery(this).attr('href');
        window.open(href + '?package='+27);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM