0

Anyone can help how to open new windows when clicked anywhere but only once pervisit. Example, you visit google.com and click anywhere there, and new window will open but only once, second click will not open windows.
Site example : http://afowles.blogspot.com
My script is

Function popup() {
   window.open ("http://www.stackoverflow.com","popup","menubar=1,resizable=1,width=450,height=550");

And then put

onclick="popup()"
In body.
Code above show new windows every single click on the site. What should i do to make it only show once?

2 Answers2

1

Set a global variable a=1; then in function check for variable's value. After windows.open is executed, change the global variable's value, so that windows.open will not be executed again.

Code:

<script>
var a=0;
function popup() {
if(a==0){
window.open ("http://www.stackoverflow.com","popup","menubar=1,resizable=1,width=450,height=550");
a++;
}
}
</script>
0

Firstly you will need to define to yourself what a visit consists of, i.e. once per day, week, or each time a users lands on your site, every page loaded, etc.

Assuming you want some persistence for your users while they browse, what you need to do on your site is set a condition to be evaluated prior to the first click and if the result indicates a users' first visit then open the page. At the same time, set a value to be checked next time (and most likely all subsequent clicks based on your current implementation). LocalStorage or cookies would be your best options for this.

I would set up something along the lines of:

//check page is loaded
if (cookie.firstVisit) {
  //add click event listener
} else {
  //set cookie.firstVisit to false
  //remove click event listener
}

Instead of spelling out how to do this with cookies here, have a look at this article which explains it all: How to set/unset cookie with jQuery?

Lastly, opening a new window when someone clicks anywhere on your page without them explicitly wanting that action perform is considered bad practice in most scenarios. However, I do not know your situation so this may be the best course of action but thought it was worth mentioning.

Community
  • 1
  • 1
Ash
  • 11,292
  • 4
  • 27
  • 34