I am working with some others on a web based javascript game, and there is a small issue where occasionally keyboard shortcuts can get in the way. sometimes for example, one might accidentally press Alt+W and that can be annoying (and sometimes a little scary depending on what your doing).
So i would like to know, is there any way to use javascript to disable shortcuts on a webpage? i have looked around quite a lot and have not found anything about how to do this
you need to use key codes. try with something like this:
window.onload = function() {
window.document.body.onkeydown = function() {
if (event.ctrlKey) {
event.stopPropagation();
event.preventDefault();
try {
event.keyCode = 0;
}
catch (event) {
}
return false;
}
return true;
}
}
Related
On a site where some calculated answers must be given, I have implemented an invisible-until-button-clicked <div> with a simple calculator. I want to be able to operate this calculator using the physical keyboard.
I can use document.onkeypress= function(key){ reactKey(key); }, and I can catch the keys pressed. However, the div-buttons I use in my form no longer work, which also means I cannot even summon the hidden div with the calculator.
I have tried to associate the onkeypress with the calculator div, but then the key presses go undetected.
Ideally, I want the key press to be detected and used in a conditional function:
document.onkeyup= function(key){ reactKey(key); }
function reactKey(evt) {
isVisible = document.getElementById("calcRow").style.display;
if (isVisible=="table-row") {
// use key for calculator function
}
} else {
//go about business as usual
}
}
Neither return true; not return false seem to do this.
Anybody any ideas?
Please note I am trying to avoid using JQuery, as it seems silly to link in an entire library for only this functionality.
I am trying to make two checkboxes, out of which only one can be selected at any point of time. I searched the forums a lot and found a few suggestions.
if (document.attachEvent){
// For IE Browsers.
document.attachEvent("DOMContentLoaded", function (event) {
var saSelector = document.querySelector('input[name=saWrite]');
var cgSelector = document.querySelector('input[name=cgWrite]');
if (cgSelector !== null) {
cgSelector.attachEvent('change', function (event) {
if (cgSelector.checked) {
document.querySelector('input[name=saWrite]').checked = false;
}
});
}
if (saSelector !== null) {
saSelector.attachEvent('change', function (event) {
if (saSelector.checked) {
document.querySelector('input[name=cgWrite]').checked = false;
}
});
}
});
}
I wrote a similar function with addEventListener in place of attachEvent for non-IE browsers. That works on Firefox. But this method somehow doesn't work for IE. Am I doing something wrong here? Any suggestions would be helpful. I wish i could use JQuery for this. But i cant.
https://jsfiddle.net/20g7ym8q/
You say you want to use JQuery but you can't. I realize starting out that may seem like a real limitation, but it isn't. Anything you can do with JQuery you can do with JavaScript.
Your code won't work on IE11 because attachEvent has been deprecated and removed in favor of accepting addEventListener as the standard way to attach an event in all modern browsers. If you're looking for generational support without JQuery and without code duplication, setting up your own Object to use as an intermediate layer between your code and the browser is probably the best way to go about this.
function $(ele) {
return {
ele: document.querySelector(ele),
on: function(ev, fn) {
(document.attachEvent) ?
this.ele.attachEvent(ev, fn) :
this.ele.addEventListener(ev, fn);
},
checked: function(change) {
if(typeof change !== undefined) this.ele.checked = change;
return this.ele.checked;
}
}
}
The above is a function that returns an Object with two methods and a property. It works similarly to JQuery for familiarity and consistency, but it is without the overhead of including the entire JQuery library.
The methods allow you to add an event using .on with an event type and function as parameters. The methods also allow you to set or get the checked property of the specified element. .checked() will simply return a boolean as to whether the box is checked, .checked(boolean) will set the elements property to the desired state.
In practice, to solve your dilemma of only one allowable check box, you could do this:
var sa = $('input[name="saWrite"]');
var cg = $('input[name="cgWrite"]');
cg.on('click', function(ev) {
sa.checked(false)
});
sa.on('click', function(ev) {
cg.checked(false);
});
I am writing a Greasemonkey script. I want to trigger a certain code to run when the user presses the "Q" key. I did a little bit of research, and most of the sources I saw suggested using window.onkeypress.
To test this method, I created a userscript set to run when the users presses Q. Here is my code:
window.onkeypress = function(event) {
if (event.keyCode == 81) {
alert("This is a test.")
}
}
However, upon pressing the Q key, nothing happened. I am wondering if anyone knows why this may be and what I can do to correct it.
In addition, if anyone knows of any other methods I can use to achieve the same effect, it would be greatly appreciated.
keypress events don’t receive a keyCode; try handling keydown instead.
window.onkeydown = function(event) {
if (event.keyCode === 81) {
alert("This is a test.");
}
};
Is there something I can do like this (perhap via a plugin)
if ( ! $('form#contact input]').hasFocus()) {
$('form#contact input:first]').focus();
}
Basically, set focus to the first input, but only if the user has not already clicked into anything?
I know this will work too, but is there anything more elegant?
$(function() {
var focused = false;
$('form#contact input]').focus(function() {
focused = true;
});
setTimeout(function() {
if ( ! focused) {
$('form#contact input:first]').focus();
}
}, 500);
});
There is no native solution but yes there is a more elegant way you can do it:
jQuery.extend(jQuery.expr[':'], {
focus: "a == document.activeElement"
});
You're defining a new selector. See Plugins/Authoring. Then you can do:
if ($("...").is(":focus")) {
...
}
or:
$("input:focus").doStuff();
$('input:focus')
It's CSS. You don't need to create a "custom selector." It already exists! http://www.w3schools.com/CSS/pr_pseudo_focus.asp
Just attach whatever process you want to do to that selector, and it will weed it out if the element in question is not focused. I did this recently to keep a keyup from instantiating an email input error check when the e-mail input wasn't being used.
If all you're trying to do is check if the user has focused on anything themselves, just do this:
if($('input:focus').size() == 0){
/* Perform your function! */
}
jQuery 1.6 now has a dedicated :focus selector.
I had trouble with cletus approach, using jQuery 1.3.2 and Firefox 3.6.8, because the string "a == document.activeElement" was not a valid function.
I fixed it defining a function for the focus key. In fact, all other keys defined in jQuery.expr[':'] are defined as functions. Here's the code:
jQuery.extend(jQuery.expr[':'], {
focus: function(e){ return e == document.activeElement; }
});
So, now it works as expected.
However, I was experiencing some strange behaviour in Firefox 3.6.8 (maybe a bug in FF?). If I clicked on an input text while the page was rendering, and if I called is(":focus") on page load, I would get an error from the browser, reported by FireBug, and the script would break.
To solve this, I surrounded the code with a try...catch block, returning false on error. Use it if you want to prevent your users from experiencing the same error:
jQuery.extend(jQuery.expr[':'], {
focus: function(e){
try{ return e == document.activeElement; }
catch(err){ return false; }
}
});
Frustratingly difficult to find a solution to this problem considering the solution is actually very simple:
if (document.activeElement == this) {
// has focus
}
if (document.activeElement != this) {
// does not have focus
}
No, there isn't.
However, you can simulate it like this:
$(':input')
.data('focused', false)
.focus(function() { $.data(this, 'focused', true); })
.blur(function() { $.data(this, 'focused', false); });
There is a plugin http://plugins.jquery.com/project/focused
Also you can check Using jQuery to test if an input has focus
Here is a succinct way to do it.
$(document.activeElement)
or to plug it into your example..
if ($('form#contact input]')[0]!=$(document.activeElement)) { ... }
I know this is an old question, but may be my solution will help someone :)
since this didnt worked for me:
if ($(this)!=$(document.activeElement)) { ... }
..were "this" is returned from blur function. So i did this:
if ($(document.activeElement).attr("class") != "input_textbox"){ ... }
$('*:focus')
(Necro ftw, but still valid and useful)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Is there a way to detect if a browser window is not currently active?
I have a function that is called every second that I only want to run if the current page is in the foreground, i.e. the user hasn't minimized the browser or switched to another tab. It serves no purpose if the user isn't looking at it and is potentially CPU-intensive, so I don't want to just waste cycles in the background.
Does anyone know how to tell this in JavaScript?
Note: I use jQuery, so if your answer uses that, that's fine :).
In addition to Richard Simões answer you can also use the Page Visibility API.
if (!document.hidden) {
// do what you need
}
This specification defines a means for site developers to
programmatically determine the current visibility state of the page in
order to develop power and CPU efficient web applications.
Learn more (2019 update)
All modern browsers are supporting document.hidden
http://davidwalsh.name/page-visibility
https://developers.google.com/chrome/whitepapers/pagevisibility
Example pausing a video when window/tab is hidden https://web.archive.org/web/20170609212707/http://www.samdutton.com/pageVisibility/
You would use the focus and blur events of the window:
var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});
$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});
To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:
$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}
$(this).data("prevType", e.type);
})
Click to view Example Code Showing it working (JSFiddle)
I would try to set a flag on the window.onfocus and window.onblur events.
The following snippet has been tested on Firefox, Safari and Chrome, open the console and move between tabs back and forth:
var isTabActive;
window.onfocus = function () {
isTabActive = true;
};
window.onblur = function () {
isTabActive = false;
};
// test
setInterval(function () {
console.log(window.isTabActive ? 'active' : 'inactive');
}, 1000);
Try it out here.
Using jQuery:
$(function() {
window.isActive = true;
$(window).focus(function() { this.isActive = true; });
$(window).blur(function() { this.isActive = false; });
showIsActive();
});
function showIsActive()
{
console.log(window.isActive)
window.setTimeout("showIsActive()", 2000);
}
function doWork()
{
if (window.isActive) { /* do CPU-intensive stuff */}
}
All of the examples here (with the exception of rockacola's) require that the user physically click on the window to define focus. This isn't ideal, so .hover() is the better choice:
$(window).hover(function(event) {
if (event.fromElement) {
console.log("inactive");
} else {
console.log("active");
}
});
This'll tell you when the user has their mouse on the screen, though it still won't tell you if it's in the foreground with the user's mouse elsewhere.
If you are trying to do something similar to the Google search page when open in Chrome, (where certain events are triggered when you 'focus' on the page), then the hover() event may help.
$(window).hover(function() {
// code here...
});