vimeo/YouTube iframe video wheel event - javascript

I'm doing a Firefox addon to intercept wheel mouse events over an embedded iframe video of Youtube or Vimeo.
I got it working over normal YT/vimeo pages (attaching the listener to the window and then looking at event.target to identify the video), the problem is with the < iframe> tag: it doesn't intercept the "wheel" event (while for example "mouseover" works).
i.e. there is a similar HTML code in a page:
<iframe src="//player.vimeo.com/video/89055435/fallback?noscript" frameborder="0"></iframe>
This works:
iframes[i].addEventListener("mouseover", func, false);
For "wheel" I do the similar:
iframes[i].addEventListener("wheel", myFunc, false);
or
iframes[i].contentWindow.addEventListener("wheel", myFunc, false);
No result. I tried also capturing instead of bubbling: nothing.
I tried also this:
window.addEventListener("wheel", myFunc, false);
This works over every obj of the page, but nothing over the iframe itself.
I made also a setTimeout with the listener, to see if the iframe was not fully loaded: nothing changes.
http://jsfiddle.net/chtNP/121/
So, what should I do to have my wheel event when I'm over an iframe with a video inside it or how to get all wheels from the window including those over the iframe?

I had the same problem, here is my solution:
var iframe = document.querySelector('iframe');
iframe.contentDocument.addEventListener('wheel', event =>
iframe.dispatchEvent(new WheelEvent('wheel', event))
);
this will forward every wheel-event on the iframes document to the iframe element in the parent document.
Notes:
it is not possible to 'recicle' the event, it needs to be cloned
the WheelEvent constructor copies many, but not all of the original events properties
the cloned event is not isTrusted
the event forwarding is attached to the iframes document. It will only work as long as the document doesn't change. So you should run the above code once the final document is loaded
accessing the iframes document may get you in cross-domain-trouble

Related

Is it possible to monitor the event listeners in an HTML element to know when one of them is removed?

I have a problem in a page with an event not being fired under certain circumstances. It's not my code and I'm trying to debug minified and obscured JavaScript code and I'm going crazy.
When replying to a comment in our website, if the text of the reply is empty this event (an analytics event to register that the user clicked the reply button) is fired. If there's text, the event isn't fired.
The element is a <span> tag, but the event listener is actually attached to the <body> tag. My current theory is that some code that's being executed when there's actually text in the reply is removing that event listener and therefore it's not being fired.
So, is there a way to monitor the event listeners in <body> to know when (and where in the code) is this event listener being removed?
Update
We found the problem. The third-party library we use for the comments is removing the parent element of the button and that's making impossible for the event to propagate to body.
If you can run script code before the event handler is removed, you can replace removeEventListener on document.body with your own function:
const original = document.body.removeEventListener;
document.body.removeEventListener = function(...args) {
console.log("Removed");
return original.apply(this, args);
};
function handler() {
console.log("Clicked");
}
document.body.addEventListener("click", handler);
document.body.removeEventListener("click", handler);
(To cover your bases you might also convert onclick (or whatever is being used) to an accessor so you can capture it if code does document.body.onclick = null;)
There are other ways a handler can be added and removed, but hopefully whatever library you're using uses the standard.
Side note: To confirm your theory about the handler being removed, you can inspect the handlers on an element in Chrome's devtools: Right-click on the page and choose "Inspect element", navigate up to body, and look on the Event Listeners tab.
I think you can use also the google developers tools that you can open with a button on the top right corner on the window. In the source section you can see al the event listener

Add on load event for img elements now and in future?

I want to add a load event on an image that would affect that image even when that image is added to the document after the page's initial load. For a click event I would do someting like this:
$(document).on('click', '.elem', function(e) {
// do stuff
});
When I try something similar with the load event, however, it does not to work. This is what I have tried:
$(document).on('load', '.image', function() {
// do stuff
});
This event is simply never triggered. Does anyone know what I may be doing wrong, or how to achieve this?
This answer is incorrect. It's possible to do this using the capture phase, see Dhia Louhichi's answer. I'll delete this answer when I can (i.e.., once it's no longer the accepted answer).
By their nature, delegated handlers only work for events that bubble. Not all do, and load is one of the ones that doesn't. The jQuery documentation even highlights this:
In all browsers, the load, scroll, and error events (e.g., on an element) do not bubble.
You'll have to add the load handlers to the images when you add them.
What I mean by "delegated handlers only work for events that bubble":
Events that bubble work like this (in the "bubbling" phase, which is the phase you normally work with): The event is fired on the element where it originates, and then on that element's parent, then that element's parent, etc. until it gets to the document element (html). This diagram from the DOM3 events spec may help make this clearer:
Using a delegated handler (the kind you're using in your question) relies on bubbling. Consider this HTML:
<div id="container">
<div class="content">xxxx</div>
<div class="content">xxxx</div>
<div class="content">xxxx</div>
</div>
If you do $("#container").on("click", ".content", ...) you're not hooking the event on the "content" divs, even though jQuery will make it seem a bit like you are. You're hooking the event on the "container" div. When the event bubbles down to the container div, jQuery looks at where it started and sees whether it passed through any "content" divs during its bubbling. If it did, jQuery calls your handler as though (mostly) you'd hooked the event on the "content" div. That's why delegated handlers work when you add elements later; the event isn't hooked on the element, but on the container.
So that's why it won't work for load: load doesn't bubble, so even though it fires on the img elements you add, it doesn't bubble to the parent and so on, and so you never see it. To see it, you have to hook it on the specific element, not an ancestor of it.
This code shows handling the load event for img elements created in the future, without explicitly adding a listener/handler to them, by using the capture phase of the event process on document.body (also works when attached to document, but not window because of backward compatibility issues):
document.body.addEventListener(
"load",
function (event) {
var elm = event.target;
if (elm.nodeName.toLowerCase() === 'img') {
console.log("Loaded: " + event.target.src);
}
},
true // Capture phase
);
Live Example:
document.body.addEventListener(
"load",
function (event) {
var elm = event.target;
if (elm.nodeName.toLowerCase() === 'img') {
console.log("Loaded: " + event.target.src);
}
},
true // Capture phase
);
// Brief wait, then add an image
setTimeout(function() {
document.body.insertAdjacentHTML(
"beforeend",
"<img src='https://via.placeholder.com/150/202080?text=Some+Image'>"
);
}, 400);
This is tested and works in at least the following:
IE9+
Chrome and other Chromium-based browsers (Opera, Edge, Vivaldi, ...)
Firefox
iOS Safari
The behavior is also documented. In fact, coincidentally the specification gives this example mentioning load by name (scroll down slightly from that link):
EXAMPLE 5
The following is one way to interpret the above tables: the load event will trigger event listeners attached on Element nodes for that event and on the capture and target phases. This event is not cancelable. If an event listener for the load event is attached to a node other than Window, Document, or Element nodes, or if it is attached to the bubbling phase only, this event listener would not be triggered.
That's saying load will be fired in the capture and target phases, but not the bubbling phase (since the event doesn't bubble).
By default, when you use addEventListener, the handler is attached for the target phase of the element you call addEventListener on and the bubbling phase for any element within that element. If you add the third argument with the value true, though, it attaches the handler for the target phase of the element you call addEventListener on (as before) and the capture phase for any element within that element. So the code above will handle load for document.body during the target phase (except document.body doesn't fire load) and also handle load for the capture phase of any element within document.body.
More about event flows in the specification, including this handy diagram:

webkitfullscreenchange event not firing, when the element contains Flash

I have an element that contains a video player: that video player can either be Flash or HTML5 based. I want to be able to make that element fullscreen (I know, only works in webkit at the moment) and run some resizing scripts when it happens.
Here is how I do it:
this.getEl('.fullscreen').bind('click', $.proxy(function() {
this.getEl('#tpPlayer')[0].webkitRequestFullScreen();
}, this));
And the event listener:
this.getEl('#tpPlayer').bind('webkitfullscreenchange', function() {
console.log('fullscreen change');
$(this).toggleClass('tpPlayer tpPlayerFullScreen');
});
When #tpPlayer contains a <video> element, everything works fine: the element goes fullscreen, the event fires, the message is logged and the classes are toggled. However, when #tpPlayer contains a Flash <object>, the element goes fullscreen fine, but no event is fired (so the callback does not run either).
Why is this happening and how to avoid this?

Capture click on div surrounding an iframe

How can I capture a click or mousedown event on a div surrounding an iframe. I've tried attaching the function to click event on the div but since the iframe never bubbles the event up to the surrounding div the function is never called. Is there a way I can capture the event on the div and then propagate it to the iframe for default action?
If the click is in the iframe area, the iframe context handles the click event, it does not bubble up to the iframe parent. So the div will never register the click event at all if it happened in the iframe area.
Furthermore, if the iframe contains a page that does not belong to the same domain as the iframe parent, any interaction is prohibited (re. same origin policy).
When the same origin policy is met, there are a few things you can do, you could call a method in the iframe parent context:
top.parentFunction();
So in the iframe you add an event listener that delegates to the iframe parent (accessible with the top reference.
Propagating events is a lot more complicated, so I'm simply going to refer to Diego Perini's NWEvents library. I believe his event system to be one of the better ones out there and he's particular on iframe interaction.
I certainly would not start writing your own code to achieve this, this can easily be a year long project if you want to do it properly and even then will be inferior to Diego's work.
There's no "good" way to do it, but if you really need to detect a click on an Iframe, you can kind-of do it in the latest browsers.
<iframe src="http://mtw-ed.com/" id="iframe" style=""></iframe>
<script type="text/javascript">
var inIframe = false;
function checkClick() {
if (document.activeElement
&& document.activeElement === document.getElementById("iframe")) {
if (inIframe == false) {
alert("iframe click");
inIframe = true;
}
} else
inIframe = false;
}
setInterval(checkClick, 200);
</script>
This script will check every 200ms whether the user is in the Iframe. Of course, they may not have clicked on the Iframe to get there, but I'm afraid this is the best you can do without #BGerrissen's solution.
It will detect the first 'click' only, unless you click out again. It only works in really modern browsers.
You can use a library like porthole to pass messages between parent and iframe, even across domains. Using this wouldn't exactly propagate the event (you won't be able to get the event object), but you can create your own event in the form of a simple message, and then handle it in the parent as a click.
Here's their example
However, I've used Brendon's answer as it's simpler works for my current need.
If you land here because you need to track a click on a PayPal button (like me), and you have access to the JavaScript SDK, you can listen to the click by adding the onClick callback in the initialization.
Example:
paypal.Buttons({
onClick() {
// here you can track the click
}
}).render('#paypal-container');
Link to the docs: https://developer.paypal.com/sdk/js/reference/#link-oninitonclick.

Mobile Safari Event Issue

I have designed a website with a menu that is initially invisible. When the user clicks on a button, the menu becomes visible. There are two ways for the user to hide the now visible menu:
Click the button that caused the menu to become visible
Click anywhere on the web page that isn't the menu
The way I have coded the second option is to tie an onclick event to the window element, and have it compare where the user clicked to the menu's position to determine if the menu should be hidden. This works great in Firefox and Safari, but it fails in Mobile Safari.
I noticed that the window onclick event only fires when I click on another element with an onclick event already assigned. If I click on an element with no event(s) assigned, the window's onclick event never fires. If I click on the button which displays the menu, it fires along with the event tied to the button.
Is it possible to assign events to the window element in Mobile Safari?
I'v been encountering this same problem. Here is what worked for me. (Note: I am working within a Modernizr and jQuery context)
First, I add a custom Modernizr class using Modernizr's addTest Plugin API to test for iOS, which will add the class appleios or no-appleios accordingly.
Because in my research the body seems to fire events on it's own agenda, I am taking a little precaution by wrapping all the document's content with an element in an iOS context. Then I add an event handler to this element.
$(".appleios body").wrapInner('<div id="appleios-helper" />');
$("#appleios-helper").bind("mouseup", function(){return;});
What was suggested earlier in this thread is using void(0). I did some quick testing, and found that void(0) as the event just wasn't causing touches on the body to be recognized. When I plugged in my own "empty" function in the form of function(){return;} things started working.
This all hinges on the fact that no events are fired in Mobile Safari unless the element explicitly has events to fire (Safari Web Content Guide.) By inserting this empty event on the wrapper, things will bubble up to the body.
If you're doing strait JavaScript with none of these libraries, the same effect could be achieved in the HTML markup
<html>
...
<body>
<div id="appleios-helper" onmouseup="function(){return;}">
...
</div>
</body>
</html>
This worked for me to hide tooltips when touching anywhere on the document's body. Your mileage may vary.
Simply adding the dummy onclick handler to the html body works for me:
<body onclick="void(0)">
Note that I am using usual live event handlers as shown below:
function liveHandler( event ) {
var target = event.target; ...}
window.addEventListener(evtype, liveHandler, true);
// evtype such as 'mousedown' or 'click'
// we use the capturing mode here (third parameter true)
This is an old question, but I struggled with the same thing today.
I found that using touchstart event works.
I solved it like this:
var isTouchDevice = 'ontouchstart' in document.documentElement;
if (isTouchDevice) {
// Do touch related stuff
$(document).on('touchstart', function (event) {
// Do stuff
});
} else {
// Do non-touch related stuff
$(document).on('click', function () {
// Do stuff
});
}
You could just add onclick="void(0);" to some <div> that covers the whole page so that no matter what, you are always clicking on an element that has an onclick event. Not a great solution, though.
I'd prefer not having the onclick event be tied to the window. Why don't you create a container <div> that has that event on it. Then handle it just like you currently are.
You can also:
$('body').css('cursor', 'pointer');
No idea what those "engineers" at Apple are doing. LOL.
This has problems though. You wouldn't want to do this on every touch device. Only touch devices that don't also have a pointing device (Laptops with Touch Screens, for example).
Source: http://www.quirksmode.org/blog/archives/2014/02/mouse_event_bub.html
The conclusion of the article is this:
So I don’t understand why all this is the case, but it most certainly is the case. If you’re having bubbling problems, just add an empty-function event handler anywhere between the body and the element, and you’re set to go. But it shouldn’t be necessary.

Categories

Resources