Trend Snaps Trend Snaps - 7 months ago 12
Javascript Question

page opening in both window

i have one submit button in my page , where i wanted to open that link in different window .

check this code

<input class="btn add-to-cart-btn" onclick="one();two();" type="submit" value="More Info At {{ product.vendor }}"/>


java script code

<script>
function one(){
trackOutboundLink('{{ product.metafields.google.custom_label_0 }}');


}

function two(){
window.open('{{ product.metafields.google.custom_label_0 }}');

}


var trackOutboundLink = function(url) {
ga('send', 'event', 'outgoing', 'click', url, {
'transport': 'beacon',
'hitCallback': function(){document.location = url;}
});
}
</script>


the "product.metafields.google.custom_label_0" is a static url .

if i click that submit page then that link is opening in new window as well as same window .

But i wanted to open in different window only . how to control this ?

Answer

The actual problem lies here:-

'hitCallback': function(){document.location = url;}

What happen that on button click first one(); and then two(); function called. So after opening the new window again, the original URL reloaded by the above code of function trackOutboundLink() which is called in function one();

So simple remove it or comment it like below:-

<input class="btn add-to-cart-btn" onclick="one();two();" type="submit" value="More Info At {{ product.vendor }}"/>

<script>
  function one(){
   trackOutboundLink('{{ product.metafields.google.custom_label_0 }}');


}

function two(){
    window.open('{{ product.metafields.google.custom_label_0 }}');

}


  var trackOutboundLink = function(url) {
    ga('send', 'event', 'outgoing', 'click', url, {
    'transport': 'beacon',
    /* 'hitCallback': function(){document.location = url;} */
  });
    }
</script>