0

I have a simple page, which has a button on it, behind this button has code which will open a new page / tab in the web browser. I will use google.co.uk as an example.

window.open("www.google.co.uk");

This works fine!

But I want to find out whether it is possible, once it has been clicked and that new tab is open, is there a way so it can't keep being clicked? If that new tab then closes, then you can re-click it?

(Just to limit people to not keep clicking it and opening multiple tabs)

Thanks!

AshJam
  • 35
  • 4

1 Answers1

1

I have a solution, although if you want the counter to be persistent over refreshes (let me know and I will edit my answer) you will have to modify it. My solution is to add a variable that increases by one every time the button is click, and then check to see if it has exceeded a value:

let count = 0
const eventListener = () => ((count += 1) < 10/*your max # of clicks*/) ? alert('max # of clicks')/*whatever you want to do*/ : window.open('www.google.co.uk')

or, if you are using the HTML onclick property, and want it to all be on one line:

<button onclick="(((window.count || window.count = 0) += 1) < 10/*your max # of clicks*/) ? alert('max # of clicks')/*whatever you want to do*/ : window.open('www.google.co.uk')">Open google</button>

This javascript sets a count variable to 0 then, after each button click, it increases the counter and checks to see if it is greater than your max number of clicks at the same time. After that it does whatever you want it to do depending on if it (the counter) is larger than the max number or not.

MilesZew
  • 667
  • 1
  • 8
  • 21