Alert On Button Click and move the user to open a new tab.

I created a button with a link that opens in a new tab. I also used javascript for warning.

This code is currently working fine. But after clicking OK in the warning, the user remains on one page. But I want to move the user to a new open tab. Is it possible?

My code is

<form><input type="button" id="anchor1" style="cursor:pointer" value="Click Here" onClick="window.open(href='http://www.google.com')"></form> 

<script type="text/javascript">
  var anchor = document.getElementById('anchor1');
    // or anchor = getElementsByTagName('a') then do ('a')[0]

    anchor.addEventListener('click', doSomething, false);

    function doSomething() {
        alert('You Are About To Open New Tab');
    }
</script>

Help required

Here is my JSFIDDLE

+4
source share
3 answers

It is super easy.

You need to remove the attribute onclickfrom the tag input.

Then enter your code to open a new tab using JS after the line alert.

<form><input type="button" id="anchor1" style="padding:5px; cursor:pointer" value="Click Here"></form> 

JS- :

var anchor = document.getElementById('anchor1');

anchor.addEventListener('click', doSomething, false);

function doSomething() {
    alert('You Are About To Open New Tab');
    var win = window.open("http://google.com", '_blank');
    win.focus();
}

Fiddle

+2

, text-decoration none:

<button><a href="http://www.google.com" target="_blank">Click here</a></button>
+1

HTML

<form><input type="button" id="anchor1" style="padding:5px; cursor:pointer" value="Click Here" ></form> 

Js

var anchor = document.getElementById('anchor1');
// or anchor = getElementsByTagName('a') then do ('a')[0]

anchor.addEventListener('click', doSomething, false);

function doSomething() {
    alert('You Are About To Open New Tab');
    window.open(href='http://www.google.com')                
}
0
source

Source: https://habr.com/ru/post/1548189/


All Articles