I'm making a game, and there's a leaderboard. I want the user to be able to toggle the leaderboard by hitting the TAB key. Here is my code:
keysPressed = {};
if(keysPressed[KEY_TAB]){
if(leaderboard.style.display == 'none'){
$(leaderboard).fadeIn(100);
} else {
$(leaderboard).fadeOut(100);
}
keysPressed[KEY_TAB] = false;
}
document.addEventListener('keydown', (event) => {
keysPressed[event.key.toLowerCase()] = true;
}, false);
document.addEventListener('keyup', (event) => {
keysPressed[event.key.toLowerCase()] = false;
}, false);
Note: leaderboard is just document.getElementById('leaderboard')
This all works fine, but whenever I hit the tab key, the webpage (I'm using Chrome) automatically selects/deselects the URL bar. Is there a way I can prevent the TAB key from doing this, or do I need to switch to a different key? Here is an screenshot demonstrating my problem:
JavaScript is prefered, since I am rather new to jQuery, but I am willing to go either.
Thanks in advance~
Use Event.preventDefault()
From MDN :
The preventDefault() method of the Event interface tells the user
agent that if the event does not get explicitly handled, its default
action should not be taken as it normally would be.
The event continues to propagate as usual, unless one of its event
listeners calls stopPropagation() or stopImmediatePropagation(),
either of which terminates propagation at once.
As noted below, calling preventDefault() for a non-cancelable event,
such as one dispatched via EventTarget.dispatchEvent(), without
specifying cancelable: true has no effect.
document.addEventListener('keydown', (event) => {
if (event.key == "Tab") {
event.preventDefault();
}
}, false);
Related
Is it possible with jquery to trigger a function when the user clicks the browsers back button.
I have a lightbox/widget that when open fills the window when it is open. There is a close button etc but this would be good if this closed if a user hit the back button by mistake.
I have this so far but the function doesnt seem to run at all
$(window).on("navigate", function (event, data) {
event.preventDefault();
console.log('BACK PRESSED');
var direction = data.state.direction;
if (direction === 'back') {
if(widgets.full_active){
$('.close', widgets.active_widget).click();
event.preventDefault();
console.log('CLOSE THIS');
}
}
if (direction === 'forward') {
// do something else
}
});
By not running this line at the start of the function event.preventDefault(); should mean the page never changes
Usually, I do this using the native JavaScript API from the browser, like described here: Manipulating the Broser History.
With jQuery, I see people usually using this plugin: History.js, although I have no idea what is it's status.
The event you're looking for is onpopstate.
A popstate event is dispatched to the window every time the active
history entry changes between two history entries for the same
document.
On some websites, you can right-click on a link and chose "open in a new tab" and it works fine, but not if one uses the middle mouse button to do so.
I encountered this a few times, it's it not too annoying but I'm still curious what causes this behaviour. (About the HOW)
Here is a site that behaves this way browsing with Chrome 46:
http://ebookfriendly.com/free-public-domain-books-sources/
the html link tags looks normal:
<a title="Feedbooks" href="http://www.feedbooks.com/">⇢ Feedbooks</a>
The cause must be something in the javascript. Any pointers?
One way to do this is using the auxclick event. (auxclick on MDN)
The following code will prevent the middle click behaviour on the entire page.
window.addEventListener("auxclick", (event) => {
if (event.button === 1) event.preventDefault();
});
Seems like this link has an event listener that uses preventDefault() and opens the page by other means.
Edit: hard to say why exactly they do this but when I look at the whole handler it seems that the link is being passed to google analytics:
function(e) {
var n = this.getAttribute("href"),
i = "string" == typeof this.getAttribute("target") ? this.getAttribute("target") : "";
ga("send", "event", "outbound", "click", n, {
hitCallback: t(n, i)
}, {
nonInteraction: 1
}), e.preventDefault()
}
You can ask which button caused the event and prevent the default behavior.
document.querySelector("a").addEventListener("click", function(e) {
if (e.which === 2) {
e.preventDefault();
}
}, false);
$(document).mousedown(function(e){
if(e.which == 2 ){
e.preventDefault();
alert("middle click");
return false;
}
});
works only if you keep the alert()
I have a soundboard with buttons that trigger AJAX posts on mousedown.
The ideal functionality is to play an audio on left-mousedown and cancel playback on right-mousedown.
The code I have so far disables the context menu and cancels the playback...however, if they are over a button when they right-click (that triggers other previously defined events), it will still honor the mousedown and play that audio.
$(document).ready(function(){
document.oncontextmenu = function() {return false;};
$(document).mousedown(function(e){
if( e.which == 3 ) {
e.preventDefault();
Cancel_Playback();
return false;
}
return true;
});
});
I am trying to disable the right-mousedown from triggering the previously defined events but honor the Cancel_Playback. Any ideas?
EDIT
Updated Title and Description to more accurately reflect what I am trying to accomplish. This should also help: http://jsfiddle.net/g9sh1dme/15/
stopImmediatePropagation is probably the function you're looking for.
It cancels all other events bound to the the same element and any other delegates higher in the DOM. Order also matters as events are called in the order in which they were bound. You can only cancel events that were bound after the event doing the canceling.
I'm not sure if these changes maintain the validity of your program, but it demonstrates the function's use. Otherwise, I'd just check for right-mousedown in Play_Sound and exit out instead of banking on another event to cancel its execution.
Live Demo
$(document).ready(function(){
document.oncontextmenu = function() {return false;};
//For this to work you must bind to the same object or you must bind to something lower in the DOM.
$(".sound").mousedown(function(e){
if( event.which == 3 ) {
Cancel_Playback();
e.stopImmediatePropagation();
return false;
}
return true;
}).mousedown(Play_Sound);
})
function Cancel_Playback() {
alert("This is all that should be displayed on right-mousedown")
}
function Play_Sound() {
alert("Display this on left-mousedown... but not on right-mousedown")
}
I want to prohibit the right mouse button. But I find that if I write this:
document.addEventListener('contextmenu', function(event) {
return false;
}, false);
It will not work, the event will still work.
But if I write it like this,
document.oncontextmenu = function() {
return false;
}
The right mouse button will not work.
I wish to know why I can't use addEventListener to stop the event contextmenu.
As stated in "Preventing the Browser's Default Action", the return of false value is not enough for preventing default action. You need to call preventDefault() method on Event object:
document.addEventListener('contextmenu', function(event) {
event.preventDefault();
}, true);
DEMO
I believe you need to useCapture, try passing true as the third parameter to
document.addEventListener() and see if that doesn't solve it for you.
I'm trying to prevent a mousewheel event captured by an element of the page to cause scrolling.
I expected false as last parameter to have the expected result, but using the mouse wheel over this "canvas" element still causes scrolling:
this.canvas.addEventListener('mousewheel', function(event) {
mouseController.wheel(event);
}, false);
Outside of this "canvas" element, the scroll needs to happen. Inside, it must only trigger the .wheel() method.
What am I doing wrong?
You can do so by returning false at the end of your handler (OG).
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
return false;
}, false);
Or using event.preventDefault()
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Updated to use the wheel event as mousewheel deprecated for modern browser as pointed out in comments.
The question was about preventing scrolling not providing the right event so please check your browser support requirements to select the right event for your needs.
Updated a second time with a more modern approach option.
Have you tried event.preventDefault() to prevent the event's default behaviour?
this.canvas.addEventListener('mousewheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Keep in mind that nowadays mouswheel is deprecated in favor of wheel, so you should use
this.canvas.addEventListener('wheel',function(event){
mouseController.wheel(event);
event.preventDefault();
}, false);
Just adding, I know that canvas is only HTML5 so this is not needed, but just in case someone wants crossbrowser/oldbrowser compatibility, use this:
/* To attach the event: */
addEvent(el, ev, func) {
if (el.addEventListener) {
el.addEventListener(ev, func, false);
} else if (el.attachEvent) {
el.attachEvent("on" + ev, func);
} else {
el["on"+ev] = func; // Note that this line does not stack events. You must write you own stacker if you don't want overwrite the last event added of the same type. Btw, if you are going to have only one function for each event this is perfectly fine.
}
}
/* To prevent the event: */
addEvent(this.canvas, "mousewheel", function(event) {
if (!event) event = window.event;
event.returnValue = false;
if (event.preventDefault)event.preventDefault();
return false;
});
This kind of cancellation seems to be ignored in newer Chrome >18 Browsers (and perhaps other WebKit based Browsers). To exclusively capture the event you must directly change the onmousewheel method of the element.
this.canvas.onmousewheel = function(ev){
//perform your own Event dispatching here
return false;
};
Finally, after trying everything else, this worked:
canvas.addEventListener('wheel', (event) => {
// event.preventDefault(); Not Working
// event.stopPropagation(); Not Working
event.stopImmediatePropagation(); // WORKED!!
console.log('Was default prevented? : ',event.defaultPrevented); // Says true
}, false)
To prevent the wheel event, this worked for me in chrome -
this.canvas.addEventListener('wheel', function(event) {
event.stopPropagation()
}, true);