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"
});
})();
Related
So, I've already tried the selected answer on this:
How to disable ondblclick in JavaScript?
but it doesn't work, on my end. As per usual, I'm suspecting it has something to do with IE8 (since a lot of my previous problems were related to IE8 issues).
This is how my button looks like, keyBtnEvent is a function that changes the class of the div:
function keyBtnEvent(key, id, event) {
//change class of object with id = 'id'
console.log(event + 'event of keyBtnEvent called');
}
<div id="2Key" class="key"
onmouseup="keyBtnEvent('2','2Key','up')"
onmousedown="keyBtnEvent('2','2Key','down')">
<button>2</button>
</div>
So, how do i disable ondblclick in IE8, without using jquery?
This is the proper IE 8 way to do it:
var key = document.getElementById('2Key')
// Feature detection for DOM Event Standard and IE 8 and less
if(window.addEventListener){
// W3C DOM Event Standard
key.addEventListener("dblclick", function(evt) {
evt.preventDefault(); // stop the event
evt.stopPropagation(); // don't bubble the event
});
} else if(window.attachEvent){
// IE 8 or less
key.attachEvent("ondblclick", function(evt) {
evt = evt || window.event;
evt.returnValue = false; // stop the event
evt.cancelBubble = true; // don't bubble the event
});
}
Also, you should not be using inline HTML event attributes (onmouseover, onmouseout, etc.). Here's why. Instead, you should be doing all your JavaScript work in a dedicated script and use .addEventListener() (or the above attachEvent() method for IE 8 or less).
I am making an HTML 5 game which requires the use of right click to control the player.
I have been able to disable the right click context menu by doing:
<body oncontextmenu="return(false);">
Then it came to my attention that if you hold shift and right click, a context menu still opens in Firefox!
So I disabled that by adding this JS as well:
document.onclick = function(e) { if(e.button == 2 || e.button == 3) { e.preventDefault(); e.stopPropagation(); return(false); } };
However, if you hold shift, and then double right click in Firefox it still opens!
Please tell me how to disable this bloody thing once and for all (I'm even willing to revert to some obscure, hacky, and unpractical solution, as long as it works).
You will never be able to entirely disable the context menu in all cases, as firefox has a setting that allows the user to tell the browser to ignore such hijinx as you are trying to pull.
Note: I'm on a mac, but this setting is in pretty uch the same place over all platforms.
That being said, try event.preventDefault() (see Vikash Madhow's comment on this other SO question:
How to disable right-click context-menu in javascript)
There is actually example in official documentation that blocks directly context menu event:
document.oncontextmenu = function () { // Use document as opposed to window for IE8 compatibility
return false;
};
window.addEventListener('contextmenu', function (e) { // Not compatible with IE < 9
e.preventDefault();
}, false);
document.ondblclick = function(e) {
if(e.button == 2 || e.button == 3) {
e.preventDefault();
e.stopPropagation();
return(false);
}
};
I've got a page setup where a map is displayed (ArcGIS Online) and a input box is presented.
In Opera, for some reason, you're unable to type some characters in the input box. Instead, Opera navigates through the map on that keypress. For example, when typing the letter 'a', Opera moves the map to the left corner.
The page with map is here
After a lot of searching the only thing I could came up with, is cathing the keypress event and return false, like this:
var cancelKeypress = true;
document.onkeydown = function(evt) {
evt = evt || window.event;
cancelKeypress = /^(112|113|65|97)$/.test("" + evt.keyCode);
if (cancelKeypress) {
return false;
} };
/* For Opera */ document.onkeypress = function(evt) {
if (cancelKeypress) {
return false;
} };
But for some reason, that doesn't do the trick. Secondly, I'm wondering if there isn't a nicer solution which hooks on to Opera and blocks all the map navigation at once, in stead of blocking every keypress by it's own.
I would be more then happy if someone could explain what Opera is doing different compared to other browsers, which makes the input box unusable. Hopefully that knowledge would lead to a sollution to the answer.
Thanks a million!
This might only elaborate your description of the problem. Have you tried things like:
preventDefault() / isDefaultPrevented()
stopPropagation() / isPropagationStopped()
stopImmediatePropagation() / isImmediatePropagationStopped()
I want to capture if any changes happened to <textarea>. Like typing any characters (deleting,backspace) or mouse click and paste or cut. Is there a jQuery event that can trigger for all those events?
I tried change event, but it triggers the callback only after tabbing out from the component.
Use: I want to enable a button if a <textarea> contains any text.
Try this actually:
$('#textareaID').bind('input propertychange', function() {
$("#yourBtnID").hide();
if(this.value.length){
$("#yourBtnID").show();
}
});
DEMO
That works for any changes you make, typing, cutting, pasting.
bind is deprecated. Use on:
$("#textarea").on('change keyup paste', function() {
// your code here
});
Note: The code above will fire multiple times, once for each matching trigger-type. To handle that, do something like this:
var oldVal = "";
$("#textarea").on("change keyup paste", function() {
var currentVal = $(this).val();
if(currentVal == oldVal) {
return; //check to prevent multiple simultaneous triggers
}
oldVal = currentVal;
//action to be performed on textarea changed
alert("changed!");
});
jsFiddle Demo
Use an input event.
var button = $("#buttonId");
$("#textareaID").on('input',function(e){
if(e.target.value === ''){
// Textarea has no value
button.hide();
} else {
// Textarea has a value
button.show();
}
});
This question needed a more up-to-date answer, with sources. This is what actually works (though you don't have to take my word for it):
// Storing this jQuery object outside of the event callback
// prevents jQuery from having to search the DOM for it again
// every time an event is fired.
var $myButton = $("#buttonID")
// input :: for all modern browsers [1]
// selectionchange :: for IE9 [2]
// propertychange :: for <IE9 [3]
$('#textareaID').on('input selectionchange propertychange', function() {
// This is the correct way to enable/disabled a button in jQuery [4]
$myButton.prop('disabled', this.value.length === 0)
}
1: https://developer.mozilla.org/en-US/docs/Web/Events/input#Browser_compatibility
2: oninput in IE9 doesn't fire when we hit BACKSPACE / DEL / do CUT
3: https://msdn.microsoft.com/en-us/library/ms536956(v=vs.85).aspx
4: http://api.jquery.com/prop/#prop-propertyName-function
BUT, for a more global solution that you can use throughout your project, I recommend using the textchange jQuery plugin to gain a new, cross-browser compatible textchange event. It was developed by the same person who implemented the equivalent onChange event for Facebook's ReactJS, which they use for nearly their entire website. And I think it's safe to say, if it's a robust enough solution for Facebook, it's probably robust enough for you. :-)
UPDATE: If you happen to need features like drag and drop support in Internet Explorer, you may instead want to check out pandell's more recently updated fork of jquery-splendid-textchange.
2018, without JQUERY
The question is with JQuery, it's just FYI.
JS
let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
yourBtnID.style.display = 'none';
if (textareaID.value.length) {
yourBtnID.style.display = 'inline-block';
}
});
HTML
<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>
Here's another (modern) but slightly different version than the ones mentioned before. Tested with IE9:
$('#textareaID').on('input change keyup', function () {
if (this.value.length) {
// textarea has content
} else {
// textarea is empty
}
});
For outdated browsers you might also add selectionchange and propertychange (as mentioned in other answers). But selectionchange didn't work for me in IE9. That's why I added keyup.
try this ...
$("#txtAreaID").bind("keyup", function(event, ui) {
// Write your code here
});
Try to do it with focusout
$("textarea").focusout(function() {
alert('textarea focusout');
});
.delegate is the only one that is working to me with jQuery JavaScript Library v2.1.1
$(document).delegate('#textareaID','change', function() {
console.log("change!");
});
After some experimentation I came up with this implementation:
$('.detect-change')
.on('change cut paste', function(e) {
console.log("Change detected.");
contentModified = true;
})
.keypress(function(e) {
if (e.which !== 0 && e.altKey == false && e.ctrlKey == false && e.metaKey == false) {
console.log("Change detected.");
contentModified = true;
}
});
Handles changes to any kind of input and select as well as textareas ignoring arrow keys and things like ctrl, cmd, function keys, etc.
Note: I've only tried this in FF since it's for a FF add-on.
Try this
$('textarea').trigger('change');
$("textarea").bind('cut paste', function(e) { });
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
});
});