2

Possible Duplicate:
check window open

I'm using JQuery to change the URL of a window.open event depending on certain selections:

$(".class").click(function() {
    window.open("http://www.url.com/" + variable);
});

The problem is that every time it changes, I have to call this click function again and the old window.open event is still remembered and two windows are opened, then 3, then 4, etc.

I have tried a lot of work-arounds and nothing is working. I tried calling the click function just once and then changing the variable but the window.open will only remember the original variable.

Is there a way to remove old click event handlers before adding a new one?

Community
  • 1
  • 1
Chris
  • 579
  • 1
  • 6
  • 14

3 Answers3

1

The reason changing the variable doesn't work is because of variable scope: the anonymous function inherits the scope of its original context, regardless of what has happened since then. You have two potential answers:

Bad: use a global variable (window.variable) instead.

Good: Set the window.open function to a variable itself:

WindowOpener = $(".class").click(function() {
    window.open("http://www.url.com/" + variable);
});

and then

WindowOpener.unbind();

to clear the prior event whenever you need. Jamey Sharp's answer is also correct, and will likely work in your scenario unless you're doing something unusual with the bound element.

Winfield Trail
  • 5,535
  • 2
  • 27
  • 43
0

look at $.unbind -- http://api.jquery.com/unbind/ .You can use that to remove your old event

dchhetri
  • 6,926
  • 4
  • 43
  • 56
0

Before adding the new click handler, you can remove the old one(s):

$(".class").unbind('click');
Jamey Sharp
  • 8,363
  • 2
  • 29
  • 42
  • Wow, I thought I had tried unbind click but I guess not because it works. Thank you for the quick and to-the-point answer! – Chris Nov 14 '12 at 00:29