Detecting window onblur() event in Firefox, IE and Chrome? - javascript

I currently have the code below:
if (document.onfocusin !== undefined) {
var onfocusin = true;
}
else{
var onfocusin = false;
}
if (onfocusin === true)
{
document.onfocusout = ad_blur; //ad_blur is a function I defined
//when window.onblur() fires
} else{
window.onblur = ad_blur;
}
Code works fine in IE 8 and Chrome 17 but not in Firefox 8, I also found some other code but the compatibility doesn't meet my need. So the question is : is there a way to determine window.onblur() event in IE, Firefox and Chrome?
More specifically, I want to handle the event when a new window (or tab) is open.

as jmort253 mentioned, jQuery is really good at this, here is the code that works in almost every current browsers:
$(document).ready(function() {
$(window).blur(function() {
ad_blur(); //here is what you wanna do when blur fires
});
});

Related

attachEvent not working in chrome browser for focusout event

I have below code working fine in IE 9 but when I am going through Chrome I am getting the error 'element has no method"attachEvent"'. I tried using.on as well as addEventListener() still I am unable to get through. The element used here is a SharePoint people picker field. I am referring jquery 2.1.
Please advice if I am missing anything?
Code:
var element = getPeoplePickerRelControl("User", "div[Title='People Picker']");
if (element != null) {
$(element).focusin(function () {
_cardHolderInfo = getUserDetails(element.innerHTML);
});
// if(element.attachEvent)
element.attachEvent("onfocusout", manipulateLeaderProfile);
attachEvent is specific for IE only. If you want to attch any event in Chrome you should use addEventListener method. Attach events as shown below
if(navigator.userAgent.toLowerCase().indexOf('msie') != -1){
element.attachEvent("focusout", manipulateLeaderProfile);
}
else{
element.addEventListener("focusout", manipulateLeaderProfile, false);
}
Hope this will help you.

e.preventDefault() & return false not working in firefox

Chrome :
Following code is working in Chrome.
$('.links').click(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Firefox :
Since above code doesn't catch middle button / mouse wheel click event in firefox, I tried following which is able to catch mouse wheel click event.
$('.links').mousedown(function(e) {
if(e.which == 2) {
console.log(e.which); // prints 2
//e.preventDefault();
//e.stopPropagation();
return false;
}
});
Above code prints 2. But return false; is not working.
When I replaced console.log with alert then it works. But I can't & don't want to use alerts.
I tried mouseup, mousewheel events also. But it didn't work.
I tried attachEvent also but, I got an error(attchEvent is not a function).
I am using below mentioned js files :
jQuery-1.10.2.min.js
jquery.easyui.min.js
jquery-ui.js
jquery.ui.core.js
You can refer below links for more clarity.
jsfiddle.net/nilamnaik1989/vntLyvd2/3
jsfiddle.net/nilamnaik1989/2Lq6mLdp
http://jsfiddle.net/nilamnaik1989/powjm7qf/
http://jsfiddle.net/nilamnaik1989/q6kLvL1p/
Following are some good links. But anyhow it doesn't solve my problem.
event.preventDefault() vs. return false
event.preventDefault() vs. return false (no jQuery)
http://www.markupjavascript.com/2013/10/event-bubbling-how-to-prevent-it.html
I need your valuable inputs.
All click default actions should be cancelable. That's one of the points of this important event. However, certain browsers have exceptions:
IE 5-8 won't prevent the default on text inputs and textareas.
IE9/10 & Opera incorrectly un-check radio buttons when you click on another radio in the same group. It correctly doesn't check the new radio.
IE 5-8, Firefox, & Opera won't prevent the default on select boxes.
Firefox & Chrome feel that one radio button must be checked. If all are unchecked they’ll check the first one you click on, even if the default is being prevented.
See Events - click, mousedown, mouseup, dblclick for some more information.
I had the same issue with firefox, related with
preventDefault();
Everything was working well in Safari, Chrome, Opera and even in IE9 (not kidding)
But, after a lot of reading, I saw that the site was using and old jquery version (1.10), then updated to the latest one (2.1.4) the action was canceled even in Firefox.
Another thing to consider is that I used a variable named "keyPressed" like:
var keyPressed = event.keyCode || event.which || event.charCode
So it was easy for each browser to recognize the key event.
Hope this help!
I have faced the similar problem in FF on middle click.
The following script fixed me the issue and it works fine in FF as well.
$(document).on('click', $(".content"), function(e) {
if(e.button==1) {
e.preventDefault();
return false;
}
})

Page visibility API in Google Chrome

When using the page visibility API in Google Chrome the event is fired twice.
This is some thing that happen only in Chrome.
document.addEventListener('visibilitychange', function(e) {
if (!document.hidden) {
console.log(e);
}
});
By what I know of the API the event is suppose to fire once.
I am trying to fire it once regardless the browser.
You have to do two different methods to detect browser window and browser tab.
For a cross-browser solution check out this example:
Using HTML5 Visibility API to manage the focus of browser tabs and windows:
For detecting if the browser tab is active or not, use the HTML5 Visibility API:
/////////////////////////////////////////
// main visibility API function
// check if current tab is active or not
var vis = (function(){
var stateKey,
eventKey,
keys = {
hidden: "visibilitychange",
webkitHidden: "webkitvisibilitychange",
mozHidden: "mozvisibilitychange",
msHidden: "msvisibilitychange"
};
for (stateKey in keys) {
if (stateKey in document) {
eventKey = keys[stateKey];
break;
}
}
return function(c) {
if (c) document.addEventListener(eventKey, c);
return !document[stateKey];
}
})();
/////////////////////////////////////////
// check if current tab is active or not
vis(function(){
if(vis()){
// the setTimeout() is used due to a delay
// before the tab gains focus again, very important!
setTimeout(function(){
// browser tab gains focus
// code goes here
},300);
} else {
// browser tab gains focus
// code goes here
}
});
For detecting the browser window you just check the window blur, focus, focusin, and focusout depending on what browser it is:
/////////////////////////////////////////
// check if browser window has focus
var notIE = (document.documentMode === undefined),
isChromium = window.chrome;
if (notIE && !isChromium) {
// checks for Firefox and other NON IE Chrome versions
$(window).on("focusin", function () {
setTimeout(function(){
// browser window gains focus
// code goes here
},300);
}).on("focusout", function () {
// browser window loses focus
// code goes here
});
} else {
// checks for IE and Chromium versions
if (window.addEventListener) {
// bind focus event
window.addEventListener("focus", function (event) {
// the timeout is due to a slight delay when a browser tab regains focus
setTimeout(function(){
// browser window gains focus
// code goes here
},300);
}, false);
// bind blur event
window.addEventListener("blur", function (event) {
// browser window loses focus
// code goes
}, false);
} else {
// bind focus event
window.attachEvent("focus", function (event) {
// the timeout is due to a slight delay when a browser tab regains focus
setTimeout(function(){
// browser window gains focus
// code goes here
},300);
});
// bind focus event
window.attachEvent("blur", function (event) {
// browser window loses focus
// code goes here
});
}
}
Resources:
MDN - visibilitychange
MDN - Using_the_Page_Visibility_API
Working example of the above code: http://codepen.io/jonathan/pen/sxgJl
I also converted this into a jQuery plugin if needed. You can download it on the GreenSock GSAP Forum, at this link here.
Or download the TabWindowVisibilityManager jQuery Plugin directly.
I hope you find this helpful!
Looks like it is a bug in Chrome:
https://code.google.com/p/chromium/issues/detail?id=409467
The workaround seems to be to attach to the window:
Workaround: use window to attach the event to. This seems
non-standard.

onfocusin not working for firefox and chrome

I have a Javascript running in a page. The following is the code am using.
window.document.onkeydown = keydown;
function keydown()
{
alert("keydown");
}
window.document.onfocusin = focussedin ;
function focussedin ()
{
alert("focus in");
}
Here , If I run the code, I am not getting the focus in alert for firefox and chrome. Whether window.document.onfocusin will not work in other browsers except IE ?
onfocusin is only supported by IE http://help.dottoro.com/ljggspvo.php
You should use onfocus instead.
function onfocusFun ()
{
console.log("focus in");
}
window.onfocus = onfocusFun;
JSFIDDLE
Note: Behavior of firefox is correct as you loss focus from document once it open alertbox and on closing alertbox you agian firing onfocus. Use console.log instead.

Cross-browser: detect blur event on window

I just read, I think all the thread that deals with this subject, and I can't find a real solution to my problem.
I need to detect when the browser window loses its focus, i.e. a blur event.
I've tried all the scripts on stackoverflow, but there doesn't seem to be a proper cross-browser approach.
Firefox is the problematic browser here.
A common approach using jQuery is:
window.onblur = function() {
console.log('blur');
}
//Or the jQuery equivalent:
jQuery(window).blur(function(){
console.log('blur');
});
This works in Chrome, IE and Opera, but Firefox doesn't detect the event.
Is there a proper cross-browser way to detect a window blur event?
Or, asked differently, is there a way to detect a window blur event with the Firefox browser?
Related questions and research:
See Firefox 3 window focus and blur
According to the following github articles, jQuery has discontinued support for Firefox blur testing:
https://github.com/jquery/jquery/pull/1423
http://bugs.jquery.com/ticket/13363
I tried both:
document.addEventListener('blur', function(){console.log('blur')});
and
window.addEventListener('blur', function(){console.log('blur')});
and they both worked in my version of FF (33.1).
Here's the jsfiddle: http://jsfiddle.net/hzdd06eh/
Click inside the "run" window and then click outside it to trigger the effect.
The document.hasFocus (MDN) is an implementation that can resolve the problem with Firefox, but in Opera it isn't supported. So, a combined approach can reach out the problem you are facing.
The function below exemplifies how can you use this method:
function getDocumentFocus() {
return document.hasFocus();
}
Since your question isn't clear enough about the application (timed, pub/sub system, event driven, etc), you can use the function above in several ways.
For example, a timed verification can be like the one implemented on this fiddle (JSFiddle).
It appears that jQuery no longer supports these tests for FireFox:
jQuery bug ticket is here: http://bugs.jquery.com/ticket/13363
jQuery close/deprecation commit is here: https://github.com/jquery/jquery/pull/1423
I am searching for a better way to support Firefox blur eventing, but until I find a better approach, this is a more current status relative to the original accepted answer.
You can use jQuery's blur method on window, like so:
$(document).ready(function() {
$(window).blur(function() {
// Put your blur logic here
alert("blur!");
});
});
This works in Firefox, IE, Chrome and Opera.
I tried using the addEventListener DOM function
window.addEventListener('blur', function(){console.log('blur')});
window.addEventListener('click', function(event){console.log(event.clientX)});
I got it to work after the first blur. but it didnt work when I didnt have the click function attached to it.
There might be some kind of refresh that happens when a click function is interpreted
Here is an alternative solution to your question but it uses the Page Visibility API and Solution is Cross Browser compatible.
(function() {
var hidden = "hidden";
// Standards:
if (hidden in document)
document.addEventListener("visibilitychange", onchange);
else if ((hidden = "mozHidden") in document)
document.addEventListener("mozvisibilitychange", onchange);
else if ((hidden = "webkitHidden") in document)
document.addEventListener("webkitvisibilitychange", onchange);
else if ((hidden = "msHidden") in document)
document.addEventListener("msvisibilitychange", onchange);
// IE 9 and lower:
else if ("onfocusin" in document)
document.onfocusin = document.onfocusout = onchange;
// All others:
else
window.onpageshow = window.onpagehide = window.onfocus = window.onblur = onchange;
function onchange(evt) {
var v = "visible",
h = "hidden",
evtMap = {
focus: v,
focusin: v,
pageshow: v,
blur: h,
focusout: h,
pagehide: h
};
evt = evt || window.event;
if (evt.type in evtMap) {
console.log(evtMap[evt.type]);
} else {
console.log(this[hidden] ? "hidden" : "visible");
}
}
// set the initial state (but only if browser supports the Page Visibility API)
if (document[hidden] !== undefined)
onchange({
type: document[hidden] ? "blur" : "focus"
});
})();

Categories

Resources