Brown PO
Brown PO

Reputation: 487

button in iframe should trigger event

I have a button in an iframe. I want that button to trigger an event outside the iframe. How can I do that?

I have the following button

<button class="btn">Back</button>

inside an iframe

I want when people click on that button, that it triggers an event in the view outside of the iframe. How can I do that?

No need to worry about cross domain because the iframe url is on the same domain as the view.

The button only shows up when the user navigates to the second page of the iframe.

Upvotes: 1

Views: 135

Answers (1)

Quentin
Quentin

Reputation: 944425

It can't, at least not directly. Events stop bubbling when they hit the top of the document.

You could do something like:

button.addEventListener("click", passEventToParent);

function passEventToParent(event) {
    parent.querySelector("iframe").dispatchEvent(event);
}

See dispatchEvent on MDN for more information about it.

Upvotes: 1

Related Questions