Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alert On Button Click And Move User To Opened New Tab

I have Created a Button With Link Which opens in new tab. I have also used javascript to alert.

Currently this code is working perfectly. But After Clicking OK in Alert, user stays on same page. But I Want To Move User To New Opened 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 Needed

Here Is My JSFIDDLE

like image 474
darshan Avatar asked Jul 12 '14 16:07

darshan


People also ask

How do I get a button tag to open in a new tab?

How it works. Add an HTML element to your Page Block: Write your own HTML link / button. It is this attribute (target="_blank") that causes the link to open in a new tab.

What is Onclick alert?

A JavaScript can be executed when an event occurs, the user clicks on any HTML tag elements. The onclick and alert events are most frequently used event type in the JavaScript for web pages. If any anonymous function to the HTML elements the onclick attribute will attach event to this element.

How do I handle Alert OK button?

To click on the Ok button on alert, first of all we have to switch to alert with switchTo(). alert() method. Next, to click on the Ok button, we have to use accept() method. Please note we cannot identify elements on alert by inspecting on them.

How do I make a link open in a new tab in HTML?

You can make a HTML link open in a new tab by adding the target=”_blank” attribute. You should insert this after the link address.


2 Answers

This one is super simple.

You need to remove the onclick attribute from the input tag.

Then, put your code to open new tab using JS after your alert line.

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

In your JS code, do this:

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

like image 152
AdityaParab Avatar answered Sep 23 '22 02:09

AdityaParab


Style the anchor tag by changing the text color to black and changing text-decoration to none:

<button><a href="http://www.google.com" target="_blank">Click here</a></button>
like image 28
wahiddudin Avatar answered Sep 25 '22 02:09

wahiddudin