JS - How to disable spacebar scrolling ONLY, but allow other spacebar functionality? - javascript

I have a website which has regular spacebar functionality, not just inside an input box, so I can't make it return false if the target is the body. I just want to stop it from scrolling down the page, but allow the other functionality. Is it possible to do this using vanilla JS? Here is my code:
//Many other functions here
function spacebar() {
window.onkeydown = function(e) {
if ((watch.isOn) && (!done)) {//u can stop it with any key
watch.freeze();//stop the stopwatch
}
else if (e.keyCode == 32) {
if (done) {
watch.start();//start the stopwatch
stage = 1;
}
if (stage === 0) {
stage = 1;
}
}
}
<html>
<body>
<h1 id="timer">0:00.000</h1>
<script src="js/timer.js"></script>
<!--The JS starts and stops this timer.-->
</body>
</html>
So it starts the timer when the spacebar is pressed, and stops it when any key is pressed.

A default behaviour of pressing the spacebar is to scroll. We have the ability to prevent default behaviors using
event.preventDefault();
You are using window.onkeydown, passing the event argument as var e. You know how to recognize keys by keycode, as you have demonstrated. Now then, if the key that is pressed is the spacebar, then prevent the default behaviors (in this case that includes scrolling). You have the option to define your own behavior instead.

What you can do is that You can add e.preventDefault(); with your functionality like as i can play and pause the song but restrict the Scrolling.
$(window).keypress(function(e) {
if (e.which == 32) {
const isMusicPaused = wrapper.classList.contains("paused");
isMusicPaused ? pausedMusic() : playMusic();
e.preventDefault();
}});

Related

Detecting Alt key in Chrome

In my app I need to handle Alt key press/release to toggle additional information on tooltips. However, the first time Alt is pressed, document loses keyboard focus, because it goes to Chrome's menu. If I click any part of the document, it works again (once).
I can avoid this by calling preventDefault, but that also disables keyboard shortcuts such as Alt+Left/Right, which is undesirable.
I can also handle mousemove and check altKey flag, but it looks very awkward when things only update when mouse is moved.
Is there any way to reliably detect current Alt key state in my situation? I would really rather not switch to a different key.
Update: I suppose the best solution would be to call preventDefault only when a tooltip is active.
document.addEventListener("keydown", (e) => {
if (this.curComponent) e.preventDefault();
if (e.which === 18) {
this.outer.classList.add("AltKey");
}
});
document.addEventListener("keyup", (e) => {
if (this.curComponent) e.preventDefault();
if (e.which === 18) {
this.outer.classList.remove("AltKey");
}
});
I had the same issue and I solved thanks to this answer:
document.addEventListener("keyup", (e) => {
if (e.key === "Alt") {
return true; // Instead of e.preventDefault();
});
return true restores normal behavior of Alt+Left/Right chrome keyboard shortcuts.
Keyboard value both left/ right side ALT = 18
jQuery:
$(document).keyup(function(e){
if(e.which == 18){
alert("Alt key press");
}
});
JavaScript
document.keyup = function(e){
if(e.which == 18){
alert("Alt key press");
}
}

After preventing the default behavior the enter key seems to be refreshing the global variables in java script

I am writing a search function much like the [cmd+f] function in a browser. I have everything working but I want the enter key on press to cycle through the results through the page. I also have arrow buttons that call the function I wrote and they work. I prevented the default behavior of enter using:
$('form').keydown(function (event) {
if (event.keyCode == 13) {
event.preventDefault();
return false;
}
});
I am using this code to call the function on enter:
$('form').keyup(function (event) {
if (event.keyCode == 13) {
nextSearch();
}
});
It works for the first result but I think it resets the global variable I use to mark the place. The only logical answer I can think of is that pressing enter now refreshes the JavaScript. Is there a way to prevent this?
I use these global variables to keep track:
window.luCurrentNumber = 0;
window.luLastActive = 0;
If I understand you corrected, you the arrow keys and the enter keys to tab instead of performing their default. Here is an example of a function that I use to treat the Enter key as a tab, which I wrote because users kept hitting the enter key and accidentally submitting the page.
//Make enter key is pressed, tab instead of submitting.
$('body').on('keydown', 'input, select', function (e) {
var self = $(this)
, form = self.parents('form:eq(0)')
, focusable
, next
;
if (e.keyCode == 13) {
focusable = form.find('input,a,select,button').filter(':visible');
next = focusable.eq(focusable.index(this) + 1);
if (next.length) {
next.focus();
} else {
form.submit();
}
return false;
}
});
Though it's not exactly what you are trying to do, I think it should set you on the right path.

how to add dbclick() on right click in jquery

Hi I want to have a dblclick() on the right click as the google maps have to zoom in and zoom out. Is there any way to do that. I have written the dblclick but now its working with only left click. Any pointers on how to do this. Here is my code
$("div#demo1").dblclick(function(e) {
//alert(e.getElementById());
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
alert("Left Mouse Button was clicked on demo1 div!");
$("div.window").animate({
'height':'+=20', 'width':'+=20'
},0,function(){
jsPlumb.repaintEverything();
jsPlumb.repaintEverything();
});
// Left mouse button was clicked (all browsers)
}
else if( (!$.browser.msie && e.button == 2) || ($.browser.msie && e.button == 3) ) {
alert("right click double");
}
});
There is another way you could detect a double right-click that does not involve fiddling with timers or keeping track of click counts manually. Using the .detail property of the event object in a mouseup or mousedown event. .detail holds the click count which will tell you how many clicks have happened recently. If .detail === 2 it was a double-click.
// suppress the right-click menu
$('#target').on('contextmenu', function (evt) {
evt.preventDefault();
});
$('#target').mouseup(function (evt) {
if (evt.which === 3) { // right-click
/* if you wanted to be less strict about what
counts as a double click you could use
evt.originalEvent.detail > 1 instead */
if (evt.originalEvent.detail === 2) {
$(this).text('Double right-click');
} else if (evt.originalEvent.detail === 1) {
$(this).text('Single right-click');
}
}
});
You might notice that I am using evt.originalEvent.detail to access the property instead of just .detail. This is because jQuery provides it's own version of the event object which does not include .detail, but you can access the original event object that the browser returned via .originalEvent. If you were using pure JavaScript instead of jQuery you would just use evt.detail.
Here's a working example.
There is no real way to do it, you can emulate it by taking the default timer for double clicks which IIRC is 300ms:
function makeDoubleRightClickHandler( handler ) {
var timeout = 0, clicked = false;
return function(e) {
e.preventDefault();
if( clicked ) {
clearTimeout(timeout);
clicked = false;
return handler.apply( this, arguments );
}
else {
clicked = true;
timeout = setTimeout( function() {
clicked = false;
}, 300 );
}
};
}
$(document).contextmenu( makeDoubleRightClickHandler( function(e) {
console.log("double right click" );
}));
http://jsfiddle.net/5kvFG/2/
Because the right-click has meaning to the user agent that is outside the purview of javascript (the context menu), you're going to have to do some dancing around.
First, you should disable the context menu on the target element:
document.getElementById('demo1').oncontextmenu = function() {
return false;
};
Now, when we right click, there won't be the context menu messing up the second click.
Next, understand that "double-click right" does not, generally speaking, exist. Even though you can bind the dblclick event, that isn't a generic event. "Double-click" is, by definition, double-clicking with the left mouse button.
So, we'll have to use the mousedown event, check to see how many times the right has been clicked, and react after two. I created a small helper function that keeps track of the click count and resets the state after a short time-frame.
var RightClick = {
'sensitivity':350,
'count':0,
'timer':false,
'active':function () {
this.count++;
this.timer = setTimeout(
this.endCountdown.bind(this),
this.sensitivity
);
},
'endCountdown': function () {
this.count = 0;
this.timer = false;
}
};
$("div#demo1").mousedown(function(e) {
if(e.which == 3) {
RightClick.active();
if (RightClick.count == 2)
alert("right click double");
}
});
Try it here: http://jsfiddle.net/94L7z/
You can adjust the sensitivity rate, allowing for shorter or longer double-clicks, depending on your preference.
Documentation
element.onContextMenu on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.oncontextmenu
element.onMouseDown on MDN - https://developer.mozilla.org/en-US/docs/DOM/element.onmousedown
window.setTimeout on MDN - https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout
jQuery event.which - http://api.jquery.com/event.which/
"Javascript Madness: Mouse Events" on UnixPapa.com, an article showing some tests related to mouse events and the left/right buttons - http://unixpapa.com/js/mouse.html
The problem is the concept of double clicking is only relevant to the left mouse button as far as JS is concerned. So no matter how many time, and how fast you click the right mouse button, it just registers as a bunch of single clicks. So what to do?
Create a global variable to track click count
detect a single right-click, you already know how to do this it seems
set the global variable that the right-click was fired once
set a timeout, so if another right click doesn't come through in a
reasonable time to be considered a dblclick the global variable
resets to 0. I recommend 300 ms, it seems to be the most natural
each time a right-click registers check that variable, if it's more
than one, fire your double-right-click handler.
you may want to make that global variable an object so you can track which element
registered the right click and expire specific element right clicks
accordingly. This will allow you to ignore if they double click
while moving the mouse over various objects. I consider this
optional as the chain of events are unlikely for a user to follow,
but depending on your app may result in unexpected functionality.
It might be better to define a jQuery function with this (try it):
var precision = 400;
var lastClickTime = 0;
$(document).ready(function()
{
var div = $('#div');
$(div).bind("contextmenu", function(e)
{
return false;
});
$(div).mousedown(function(event)
{
if (event.which == 3)
{
var time = new Date().getTime();
if(time - lastClickTime <= precision)
{
// DOUBLE RIGHT CLICK
alert('double click');
}
lastClickTime = time;
}
});
});

Disabling enter key for form

I have been trying to disable the Enter key on my form. The code that I have is shown below. For some reason the enter key is still triggering the submit. The code is in my head section and seems to be correct from other sources.
disableEnterKey: function disableEnterKey(e){
var key;
if(window.event)
key = window.event.keyCode; //IE
else
key = e.which; //firefox
return (key != 13);
},
if you use jQuery, its quite simple. Here you go
$(document).keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
}
});
Most of the answers are in jquery. You can do this perfectly in pure Javascript, simple and no library required. Here it is:
<script type="text/javascript">
window.addEventListener('keydown',function(e){if(e.keyIdentifier=='U+000A'||e.keyIdentifier=='Enter'||e.keyCode==13){if(e.target.nodeName=='INPUT'&&e.target.type=='text'){e.preventDefault();return false;}}},true);
</script>
This code works great because, it only disables the "Enter" keypress action for input type='text'. This means visitors are still able to use "Enter" key in textarea and across all of the web page. They will still be able to submit the form by going to the "Submit" button with "Tab" keys and hitting "Enter".
Here are some highlights:
It is in pure javascript (no library required).
Not only it checks the key pressed, it confirms if the "Enter" is hit on the input type='text' form element. (Which causes the most faulty form submits
Together with the above, user can use "Enter" key anywhere else.
It is short, clean, fast and straight to the point.
If you want to disable "Enter" for other actions as well, you can add console.log(e); for your your test purposes, and hit F12 in chrome, go to "console" tab and hit "backspace" on the page and look inside it to see what values are returned, then you can target all of those parameters to further enhance the code above to suit your needs for "e.target.nodeName", "e.target.type" and many more...
In your form tag just paste this:
onkeypress="return event.keyCode != 13;"
Example
<input type="text" class="search" placeholder="search" onkeypress="return event.keyCode != 13;">
This can be useful if you want to do search when typing and ignoring ENTER.
/// Grab the search term
const searchInput = document.querySelector('.search')
/// Update search term when typing
searchInput.addEventListener('keyup', displayMatches)
try this ^^
$(document).ready(function() {
$("form").bind("keypress", function(e) {
if (e.keyCode == 13) {
return false;
}
});
});
Hope this helps
For a non-javascript solution, try putting a <button disabled>Submit</button> into your form, positioned before any other submit buttons/inputs. I suggest immediately after the <form> opening tag (and using CSS to hide it, accesskey='-1' to get it out of the tab sequence, etc)
AFAICT, user agents look for the first submit button when ENTER is hit in an input, and if that button is disabled will then stop looking for another.
A form element's default button is the first submit button in tree order whose form owner is that form element.
If the user agent supports letting the user submit a form implicitly (for example, on some platforms hitting the "enter" key while a text field is focused implicitly submits the form), then doing so for a form whose default button has a defined activation behavior must cause the user agent to run synthetic click activation steps on that default button.
Consequently, if the default button is disabled, the form is not submitted when such an implicit submission mechanism is used. (A button has no activation behavior when disabled.)
https://www.w3.org/TR/html5/forms.html#implicit-submission
However, I do know that Safari 10 MacOS misbehaves here, submitting the form even if the default button is disabled.
So, if you can assume javascript, insert <button onclick="return false;">Submit</button> instead. On ENTER, the onclick handler will get called, and since it returns false the submission process stops. Browsers I've tested this with won't even do the browser-validation thing (focussing the first invalid form control, displaying an error message, etc).
The solution is so simple:
Replace type "Submit" with button
<input type="button" value="Submit" onclick="this.form.submit()" />
this is in pure javascript
document.addEventListener('keypress', function (e) {
if (e.keyCode === 13 || e.which === 13) {
e.preventDefault();
return false;
}
});
Here's a simple way to accomplish this with jQuery that limits it to the appropriate input elements:
//prevent submission of forms when pressing Enter key in a text input
$(document).on('keypress', ':input:not(textarea):not([type=submit])', function (e) {
if (e.which == 13) e.preventDefault();
});
Thanks to this answer: https://stackoverflow.com/a/1977126/560114.
Just add following code in <Head> Tag in your HTML Code. It will Form submission on Enter Key For all fields on form.
<script type="text/javascript">
function stopEnterKey(evt) {
var evt = (evt) ? evt : ((event) ? event : null);
var node = (evt.target) ? evt.target : ((evt.srcElement) ? evt.srcElement : null);
if ((evt.keyCode == 13) && (node.type == "text")) { return false; }
}
document.onkeypress = stopEnterKey;
</script>
You can try something like this, if you use jQuery.
$("form").bind("keydown", function(e) {
if (e.keyCode === 13) return false;
});
That will wait for a keydown, if it is Enter, it will do nothing.
I checked all the above solutions, they don't work. The only possible solution is to catch 'onkeydown' event for each input of the form.
You need to attach disableAllInputs to onload of the page or via jquery ready()
/*
* Prevents default behavior of pushing enter button. This method doesn't work,
* if bind it to the 'onkeydown' of the document|form, or to the 'onkeypress' of
* the input. So method should be attached directly to the input 'onkeydown'
*/
function preventEnterKey(e) {
// W3C (Chrome|FF) || IE
e = e || window.event;
var keycode = e.which || e.keyCode;
if (keycode == 13) { // Key code of enter button
// Cancel default action
if (e.preventDefault) { // W3C
e.preventDefault();
} else { // IE
e.returnValue = false;
}
// Cancel visible action
if (e.stopPropagation) { // W3C
e.stopPropagation();
} else { // IE
e.cancelBubble = true;
}
// We don't need anything else
return false;
}
}
/* Disable enter key for all inputs of the document */
function disableAllInputs() {
try {
var els = document.getElementsByTagName('input');
if (els) {
for ( var i = 0; i < els.length; i++) {
els[i].onkeydown = preventEnterKey;
}
}
} catch (e) {
}
}
I think setting a class to a form is much better. so I coded that:
HTML
<form class="submit-disabled">
JS
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('submit', function (e) {
e.preventDefault()
});
/**
* </End>
* Submit Disabled Form
*/
And also if you want to disable submitting only when Enter Key press:
/**
* <Start>
* Submit Disabled Form
*/
document
.querySelector('.submit-disabled')
.addEventListener('keypress', function (e) {
if (e.keyCode === 13) {
e.preventDefault()
}
});
/**
* </End>
* Submit Disabled Form
*/
in HTML file:
#keypress="disableEnterKey($event)"
in js file:
disableEnterKey(e) {
if (e.keyCode === 13) {
e.preventDefault();
}
}
First you need to disable the form on submit, but re-enable it when clicked on the button. which or keycode is not used in this case, avoiding some problems with compatibility.
let formExample = document.getElementbyId("formExample");//selects the form
formExample.addEventListener("submit", function(event){ //must be used "submit"
event.preventDefault();// prevents "form" from being sent
})
To reactivate and submit the form by clicking the button:
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateButton); //calls the function "activateButton()" on click
function activateButton(){
formExample.submit(); //submits the form
}
a variation of this would be
let exampleButton = document.getElementById("exampleButton");
exampleButton.addEventListener("click", activateBtnConditions); //calls the function "activateBtnConditions()" on click
function activateBtnConditions(){
if(condition){
instruction
}
else{
formExample.submit()
}
}
Here is a modern, simple and reactive solution which works in:
React, Solidjs, JSX etc.
is written in Typescript
supports server-side rendering (SSR)
all modern browsers
does NOT require jQuery
blocks ALL Enter keys outside of <textarea> where you want to allow Enter
// avoids accidential form submission, add via event listener
function blockEnterKey(e: KeyboardEvent) {
if (e.key == "Enter" && !(e.target instanceof HTMLTextAreaElement)) {
e.preventDefault()
}
}
// add the event listener before the rendering return in React, etc.
if (typeof window !== undefined) {
window.addEventListener("keydown", blockEnterKey)
// the following line is for Solidjs. React has similar cleanup functionality
// onCleanup(() => document.body.removeEventListener("keydown", blockEnterKey))
}
return(
<form>
...
</form>
)
The better way I found here:
Dream.In.Code
action="javascript: void(0)" or action="return false;" (doesn't work on me)

Check if the spacebar is being pressed and the mouse is moving at the same time with jQuery?

Is there a way to check if the space bar and at the same time track what direction the mouse is moving and how far etc.
Point of this is that I want to replicate how Photoshop scrolls when you hold the space bar, left mouse button and you move the mouse, but without having to hold down the left mouse button.
You can use keydown() and keyup() to track if the space bar is pressed or not and look at that state in your mousemove() event handler. For example:
var space = false;
$(function() {
$(document).keyup(function(evt) {
if (evt.keyCode == 32) {
space = false;
}
}).keydown(function(evt) {
if (evt.keyCode == 32) {
space = true;
console.log('space')
}
});
});
And then your mousemove() handler can see if it's pressed or not.
you will probably have to be watching for the keydown event, check to see that it's the spacebar, set a variable saying it's down, unset it when the keyup event is seen.
so, then you would look for mouse movements when that variable was set indicating the spacebar was pressed.
This is my solution:
var allowed = true;
$(document).ready(
function () {
$(document).bind('keydown', 'space', function () {
if (!allowed) return;
allowed = false;
$('#viewport').
dragscrollable();
});
$(document).bind('keyup', 'space', function () {
allowed = true;
$('#base').off('mousedown');
return false;
});
});
Works with jQuery and the Dragscrollable Plugin.

Categories