0

I have a div that I've inserted a YouTube video into and this plays fine. But I'd like to be able to click somewhere on the video and remove the embed code from the DOM, so the div goes back to whatever it was before the embed code was inserted and the YouTube video and player completely disappear.

I know there's a YouTube JavaScript API, but this seems to just let you send commands, like stop, pause, play, to the player. I want to completely eliminate the player, and remove the iframe from the DOM seems like the best way.

The problem is that anything I click on the YouTube player is intercepted by the player so I never receive the click in my JavaScript or jQuery. Is there any way I can sense a click on the YouTube player in my JavaScript or jQuery?

Thanks

Steve
  • 4,534
  • 9
  • 52
  • 110
  • Strangely enough I could not find a duplicate for this. My guess would be to cover the player if possible with a div and forward the click over controls to the player and handle any other click yourself. That said. I would HATE that as a user. Instead add an [X] in the top just outside the container- if you want to overlay, then the [duplicate is here](http://stackoverflow.com/questions/3820325/overlay-opaque-div-over-youtube-iframe) – mplungjan May 26 '14 at 04:31

2 Answers2

0

When loading the player using an iframe then you cannot catch the events that happen inside of the iframe on your page because of the Same-Origin-Policy (the iframe links to a different domain).

If you really want to stop and remove the player on every click on it (no matte if the click is on the video or on the controls) then you could place an empty div element with the same size as the player over it and use this to catch the events. Check question mentioned by mplungjan how to do this correctly overlay opaque div over youtube iframe

One important note: as this would also block the link to youtube and also the context menu, I would guess that this is not allowed by the terms of use.

Community
  • 1
  • 1
t.niese
  • 39,256
  • 9
  • 74
  • 101
  • My thoughts too, but I am not sure all browsers will respect the z-index of the div and OP would have to catch all interaction over the controls. Here is how to overlay the div http://stackoverflow.com/questions/3820325/overlay-opaque-div-over-youtube-iframe – mplungjan May 26 '14 at 04:33
0

If you want to capture the clicks so you can operate on them, put a canvas over the player.

make a division inside it put a canvas and the player division

  canvas.style.zIndex = 2
  box=document.getElementById (div where the player is)
  box.zindex=1

you may need to set the position absolute to get them to overlap each other

now you can put a mouse listener on the canvas and capture the events. in Javascript you can pass clicks to the player if you want. Div.click() or use the API.

You may also need to use event.stopPropagation() if your click get picked up by the player.

bobbdelsol
  • 996
  • 6
  • 21