How to restore focus to iframe's parent after user interaction? - javascript

I am using the LightGallery lightbox lib to play a video (using video.js) in an iframe. The esc key is used to close the LightGallery instance. This works fine until the user interacts with the video controls since those are given focus.
How can I restore focus to the LightGallery instance after these interactions?
I've been poking around video.js and am able to trap these user clicks but so far I haven't been able to figure out what I need to do to return focus so the esc key works. I've tried using postMessage, blur and everything else I could think of and I'm a little lost. Am I asking the wrong question/looking at the wrong thing?
Various attempts:
player.on('click', function (evt) {
console.log('iframe window', window.frameElement);
evt.currentTarget.blur();
window.postMessage("hello", "*")
// var lg = document.getElementById('vidContainer');
// var lg = document.getElementsByClassName('lightGallery');
// console.log('lg', lg);
// console.log('document', document);
// lg.focus()
});

So I resolved the "focus" issue in what may be a really hacky way but it seems to work to insure that the lightbox close button can always be triggered by the escape key,
When the iframe loads, store a reference to the close button in the parent window.
let closeBtn
window.onload = function () {
closeBtn = parent.document.getElementsByClassName("lg-close lg-icon")[0]
}
Add a click event handler to the Videojs instance and use it to reassert focus on the close button after the user has interacted with the video controls. Not great, not accessibility friendly but this is what the client is expecting.
player.on('click', function (evt) {
closeBtn.focus();
});

Related

How to completely remove mobile browser long-press vibration?

I'm trying to completely remove the vibration that occurs on a long press of an element in a mobile browser.
Specifically, I have an image that I'm adding my own long-press functionality to, but the subtle short-vibrate that happens by default is interfering and I need to disable it.
I've successfully stopped the usual context menu from appearing by overriding it as follows:
window.oncontextmenu = function (event) {
event.preventDefault();
event.stopPropagation();
return false;
};
I've also added CSS to stop highlights and text selection etc - but I haven't been able to figure out what's causing the default vibrate after a few hundred ms.
Is there another lifecycle event that's popped on a long-press in a mobile browser, in or around oncontextmenu?
Full plunker Example here, long-press on the image from a mobile browser (I'm using chrome on Android) to see what I mean: https://plnkr.co/edit/y1KVPltTzEhQeMWGMa1F?p=preview
Disable the text selection when its clicked on.
document.querySelector("#your_target").addEventListener("touchstart", (e) =>
{
e.preventDefault();
e.stopPropagation();
this.style.userSelect = "none";
});
document.querySelector("#your_target").addEventListener("touchend", (e) =>
{
e.preventDefault();
e.stopPropagation();
this.style.userSelect = "default";
});
You could use touch-action: none; in CSS. Then you might be able to handle an interaction event to do what you want.
https://developer.mozilla.org/en-US/docs/Web/CSS/touch-action

Disable taphold default event, cross device

I'm struggling to disable default taphold browser event. Nothing that I have found on Google provided any help. I have only Android 4.4.4 mobile and Chrome dev tools for testing. I tried CSS fixes, such as webkit-touch-callout and others, but apparently they don't work for Android, also they don't work in Chrome dev tools.
I also tried detecting right click, (e.button==2), it doesn't work.
I came up with a solution, but it solves one problem and creates another. I just want to have a custom action for 'long press' event for selected anchors and I don't want the default pop up to appear (open in a new tab, copy link address, etc.)
This is what I did:
var timer;
var tap;
$("body").on("touchstart", my_selector, function(e) {
e.preventDefault();
timer = setTimeout(function() {
alert('taphold!');
tap=false;
},500);
});
$("body").on("touchend", my_selector, function() {
if(tap) alert('tap');
else tap=true;
clearTimeout(timer);
});
It successfully disables the default taphold event and context menu doesn't appear. However it also disables useful events, such as swipe. The links are in a vertical menu and the menu is higher than the screen, so a user has to scroll it. If he tries to scroll, starting on an anchor, it won't scroll, it will alert 'tap!'
Any ideas how could I disable taphold default or how could I fix this code so it disables only tap events and leave default swipe events enabled?
Edit: Now I thought about setting a timeout, if the pointer is in the same place for lets say 100ms, then prevent default action. However e.preventDefault(); doesn't work inside setTimeout callback.
So now I'm just asking about the simplest example. Can I prevent default actions after certain amount of time has passed (while the touch is still there).
And this is my whole problem in a fiddle. http://jsfiddle.net/56Szw/593/
This is not my code, I got this from http://www.gianlucaguarini.com/blog/detecting-the-tap-event-on-a-mobile-touch-device-using-javascript/
Notice that while swiping the box up and down, scrolling doesn't work.
I got the solution. It was so simple! I had no idea there's an oncontextmenu event. This solves everything:
$("body").on("contextmenu", my_selector, function() { return false; });
For an <img> I had to use event.preventDefault() instead of return false.
document.querySelector('img').addEventListener('contextmenu', (event) => {
event.preventDefault();
}

Detect tab/window activation in JavaScript

It seems that Google+ checks for notification updates when I activate the tab in Firefox
It'd show "0" every time I activate it, but change to a number of new notifications in a couple of seconds after that.
What's the mechanism allowing to tap into that event? Is there a specific DOM event for that? Or are they using something like onmouseover handler and just consider any kind of activity to be a sufficient indicator of tab activation?
Just a guess because I haven't all relevant browsers available for testing.
What about using the focus event on the window. Whenever a user clicks somewhere this is invoked but also on switching of tabs. To distinguish between a user's actions on the page and a user switching to the page you could check if the event's explicitOriginalTarget points to the window.
window.onfocus=function(event){
if(event.explicitOriginalTarget===window){
console.log('switched from tab');
}
}
There is Page visibility document, which describes document.onvisibilitychange event handler.
The usage
document.onvisibilitychange = function() {
console.log("Visibility of page has changed!");
};
Unfortunately there's no 100% accurate solution
onvisibilitychange correctly triggers on tab changes, but does not trigger on window changes (ALT+TAB) visibilitychange event is not triggered when switching program/window with ALT+TAB or clicking in taskbar
window.onfocus triggers when the document becomes focused. This works as expected if the tab's focus is already inside the web page, then it correctly triggers when window or tab becomes focused.
But if you have the focus on the URL bar, or in the console, you are already "out of focus", and when you get out of the window or tab and return, you will remain "out of focus", so this event won't trigger until you click inside the page, or navigate into it through TAB key
You can test below how each event triggers (click inside the white iframe to test onfocus/onblur events)
window.onfocus = () => console.log("focus");
window.onblur = () => console.log("out of focus");
document.onvisibilitychange = () => console.log("visibilityState: ", document.visibilityState);

How to determine if a user is actually looking at a web page?

Is it possible to determine whether a user is active on the current web page or, say, focused on a different tab or window?
It seems that if you switch tabs, any JavaScript set on a timeout/interval continues running. It would be nice to be able to 'pause' the events when the user is not on the page.
Would something like attaching a mouseover event to the body work, or would that be too resource-intensive?
You can place onfocus/onblur events on the window.
There's wide support for those events on the window.
Example: http://jsfiddle.net/xaTt4/
window.onfocus = function() {
// do something when this window object gets focus.
};
window.onblur = function() {
// do something when this window object loses focus.
};
Open Web Analytics (and perhaps some other tracking tools) has action tracking
You could keep an alive variable going using mousemove events (assuming the user does not leave the mouse still on the page). When this variable (a timestamp likely) has not been updated in x seconds, you could say the page is not active and pause any script.
As long as you do not do a lot of processing in the body event handler you should be okay. It should just update the variable, and then have a script poll it at a certain interval to do the processing/checks (say every 1000ms).
Attach listeners to mousemove, keyup and scroll to the document.
I use this throttle/debounce function (which works without jQuery, even though it's a jQuery plugin if jQuery is present) to only run code in response to them once in ~250ms, so that you're not firing some code on every pixel of the mouse moving.
You can also use the visibilityState of the document:
document.addEventListener("visibilitychange", function() {
if( document.visibilityState === 'visible' ) {
// Do your thing
}
});
There is a wide acceptance of this API.

How to detect if the user clicked the "back" button

When the user goes history-back-1...how do I detect that? And then, alert "the user clicked back!"
Using binds (and jQuery preferably)
You generally can't (browser security restriction). You can tell if the user navigates away from the page (onbeforeunload, onunload fire) but you can't tell where they went unless you've set up your page to allow it.
HTML5 introduces the HTML5 History API; in conforming browsers, the onpopstate event will fire if the user navigates back to an earlier "page" on your site.
try:
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
window.onpopstate=function()
{
alert("Back/Forward clicked!");
}
Following are the steps to detect back button click:
Register a mouse down event on body $('body').on('mousedown', 'on all li');
Now set a variable when mousedown event occur.
Check this variable when your location changes.
IF variable changes to true it means list clicked otherwise back button.
This work in my use case. This solution may help others because it depends on app design.
On the page you are looking at, you can add this piece of code to the onLoad event to move them back the page they were on.
if(history.length>0)history.go(+1)
If you want the alert then make it
if(history.length>0)alert("the user clicked back!")

Categories