zak leon
zak leon

Reputation: 43

How to open new tab just once using javascript

I am new to javascript .I want to have a javascript code that allow to open new tab for a link just once when you click on either buttons but when you click on same button or other button , the script wont work .For example : After clicking on the download or printing button I want to open new tab of my facebook page but I want to do it just once , so if that user clicked on download button that's it .So even if he clicks on same button multiple times or other print button multiple times the facebook function wont work at all

function facebook() {
  window.open("https://www.facebook.com");
}
<button onclick="facebook();printContent('exportContent')"  >Print</button>
<button onclick="facebook();Download();" >Download</button>

I tried to use this.onclick=null in the buttons but it cause two problems : 1/ It make other functions just work once while I want other functions to keep working each time the buttons are clicked and facebook function to work just once ; 2/ when click on one of the buttons new tab opens and when you click on other button it still open too .

Upvotes: 0

Views: 130

Answers (1)

Toxnyc
Toxnyc

Reputation: 1350

You can create a global variable to keep track of how many times you invoked facebook function

var counter = 0;

function facebook() {
  if(counter === 0) {
    window.open("https://www.facebook.com");
    counter += 1;
  }
}

function Download() {
  console.log('dl')
}

function printContent(msg) {
    console.log(msg)
}
<button onclick="facebook();printContent('exportContent')"  >Print</button>
<button onclick="facebook();Download();" >Download</button>

Upvotes: 1

Related Questions