views:

28

answers:

2

Hello, I have a page with two buttons, one Button opens a popup window with the next function:

function MM_openBrWindow(theURL,winName,features) { //v2.0
  my_window=window.open(theURL,winName,features);
}

and I need to detect from that window(my_window) when the second button in the parent page is clicked and raise an alert.

How can I do that?

Thanks in advance.

Carlos

A: 

You would do my_window.alert("hey") in the click event for the second button in the parent window. If you want to access the parent window from the child window (to add an event, for example), use window.opener in the child window.

button2.onclick = function (e) {
   my_window.buttonTwoHasBeenClicked(); // this is defined in the child window.. once executed it means the button has been clicked.
}

If you want to define the event from within the child window:

// put this in your child window javascript source
// also change "button2" to whatever your second button's ID is.
window.opener.getElementById("button2").onclick = function () {
   alert("button has been clicked on parent window");
}
CD Sanchez
Hello, thanks but what I need is that the child window detects IF the parent button was clicked, the alert is just to see if it works.Thanks
notforever
@notforever: Yes, I know. You would need a click handler, no matter where it was defined in. In that click handle you would call a function in your `my_window` reference to let the other window "know" the button has been clicked.
CD Sanchez
I am sorry I am a a newbie, could you give me an example please, I don't know how to reference parent button from my window. Thanks
notforever
@notforever: Try out the second snippet I added to my answer
CD Sanchez
thank you very much it works!!
notforever
A: 

You need to put code on the child window using window.opener, like this:

function registerWithParent() {
    window.opener.registerCallback(myCallback);
}

you can call than on body onload event.

<body onload="registerWithParent()">

Then you have JS code on the parent window like this:

var theCallback;
function registerCallback(fn) {
    theCallback = fn;
}

Then your HTML on the parent is like:

<input type="button" onclick="theCallback()" value="The 2nd button">
Jerome