QueSo
QueSo

Reputation: 339

Window.open opening blank new tab?

The weirdest thing is happening. This click event opens a blank new tab and then in the original tab, navigates to the proper page. What's going on and how do I fix it?

I checked the inspector for a target="_blank" attribute that maybe had been added later and nothing. I did a search for it in my code and nothing. So it doesn't make sense that the _blank attribute on window.open would open a blank new tab and navigate to the url in the same tab.

Thanks.

$(".homedepot, .amazon, .walmart").on('click', function() {
                url = $(this).attr('href');
                window.open(url , "_blank");
                trackOutboundLink(url);
            });

    //var path = window.location.path;
                        var trackOutboundLink = function(url) {
                            var loc = function getLocation(url) {
                                var match = href.match(/^(https?\:)\/\/(([^:\/?#]*)(?:\:([0-9]+))?)([\/]{0,1}[^?#]*)(\?[^#]*|)(#.*|)$/);
                                 return match && {
                                 href: href,
                                 protocol: match[1],
                                 host: match[2],
                                 hostname: match[3],
                                 port: match[4],
                                 pathname: match[5],
                                 search: match[6],
                                 hash: match[7]
                                }
                            }



                            newURL = loc.protocol + "//" + loc.host;
                            console.log(newURL)


                            ga('send', 'event', 'outbound click', 'click', newURL, {
                                'transport': 'beacon',
                                'hitCallback': function(){console.log("");}
                            });
                        }

Markup:

<a class="ilHide" href="<%= product.data["product.buy_amazon"].value[0].text %>"><img class="amazon" style="width:200px; position: relative; right: .5rem;" src="images/amazon2.jpeg" alt="Amazon" /></a>
<a class="ilHide" href="<%= product.data["product.buy_homedepot"].value[0].text %>"><img class="homedepot" style="display:inline;position:relative;" src="images/homedepot.png" alt="Home Depot" /></a>
<a class="ilHide" href="<%= product.data["product.buy_walmart"].value[0].text %>"><img class="walmart" style="width:200px;" src="images/walmart.jpeg" alt="Walmart" /></a>

Upvotes: 3

Views: 8170

Answers (1)

gaetanoM
gaetanoM

Reputation: 42054

I assume you want to navigate to the anchor href in a new tab while remaining in the current page. If it's correct you need:

The new click handler:

$(".homedepot, .amazon, .walmart").on('click', function(e) {
    e.preventDefault();
    url = $(this).parent().attr('href');
    window.open(url , "_blank");
    trackOutboundLink(url);
});

Upvotes: 1

Related Questions