How can I combine these two functions into one? Now I have two functions that do the same thing: close the search window on the site - by pressing escape and by pressing outside a certain .
searchOverlay.addEventListener('keydown', function(event){
if(event.key === "Escape"){
body.classList.remove('search-opened');
event.stopPropagation();
}
});
searchOverlay.addEventListener('click', function (e) {
if (e.target.closest('.search-inner') === null) {
body.classList.remove('search-opened');
e.stopPropagation();
}
});
}
You could even simply create an event listener that supports both cases
function removeSearchOpenedClass(event) {
if (event.key === "Escape" || !event.target.closest(".search-inner")) {
body.classList.remove('search-opened');
event.stopPropagation();
}
}
searchOverlay.addEventListener('keydown', removeSearchOpenedClass)
searchOverlay.addEventListener('click', removeSearchOpenedClass)
You can declare a function and call it in both callbacks.
function doStuff(e){
body.classList.remove('search-opened');
e.stopPropagation();
}
searchOverlay.addEventListener('keydown', function(event){
if(event.key === "Escape"){
doStuff(event)
}
});
searchOverlay.addEventListener('click', function (e) {
if (e.target.closest('.search-inner') === null) {
doStuff(e)
}
});
Related
I am trying to stop a keydown event from repeating for a game. I am unable to use libraries due to it being part of a school project. I have tried most of the answers I can access but they don't work for my code, I also can't use MDN because it's blocked. Here is the code
window.addEventListener("keydown", function (e){
if (e.keyCode == 32) {
accelerateBy = -0.5
accelerate()
}
});
You may have to use some variable to save the state of you key. Here's an example:
let isKeyDown = false;
document.addEventListener("keydown", (event) => {
if (event.keyCode == 32) {
if (isKeyDown) { return; } // If key was already down, don't do anything
isKeyDown = true;
// do your stuff here
}
});
document.addEventListener("keyup", (event) => {
if (event.keyCode == 32) {
isKeyDown = false;
}
});
Here is my code
document.onkeydown = function (a) {
if (a.which == 13) {
alert("Not Anymore");
}
}
document.onkeydown = function (b) {
if (b.which == 65) {
auto();
}
}
document.onkeydown = function (c) {
if (c.which == 83) {
auto2();
}
}
Only the last snippet works can someone explain why this is happening
check my website and you can see it isnt working when you press a but when you press b it is
Thanks, I appreciate the help and feedback
You're binding the same event on the document multiple times. So, the later event handlers override the previous event handlers just like the functions with same name does. You need to bind only one event handler and use if... else in it.
You can use this
document.onkeydown = function (e) {
if (e.which == 13) {
alert("Not Anymore");
} else if (e.which == 65) {
auto();
} else if (e.which == 83) {
auto2();
}
};
Also, use addEventListener instead of onkeydown.
document.addEventListener('keydown', function (a) {
if (a.which == 13) {}
...
}, false);
I have 2 events, a keydown and a click. I would like to put them into a single function and when the function is called, whichever event was fired would do what it's supposed to.
Example:
var close = function () {
$('.alert').remove();
};
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
//27 = ESC
close();
}
});
$('.alertBG').on('click', function () {
close();
});
I can't think of a way to get the document and .alertBG parts to play nicely. (Fiddle)
Don't. Your functions are too different. You have already factored the reusable parts of them out into a close function that you call from both. This is the best way to do it.
If you really wanted to, then you would have to bind a click/keydown handler to document and test the type of event and the element.
$(document).on("keydown click", function (event) {
if (
(event.type === "keydown" && event.keyCode === 27) || (event.type === "click" && (
$(event.target).is(".alertBG") || $(event.target).parents(".alertBG").length))) {
close();
}
});
As you can see, it's much cleaner just to bind your event handlers separately when there are so many differences between them.
Do you mean something like this?
function handler(event) {
if(event.type === "click") {
close();
} else if(event.type === "keydown") {
if (event.keyCode === 27) {
//27 = ESC
close();
}
}
}
$(document).on('keydown', handler);
$('.alertBG').on('click', handler);
Anything like this ?
function myFunc(method){
if(method == "one"){
// do anything
}
else if(method == "other"){
// do other thing
}
}
$(document).on('keydown', function (event) {
if (event.keyCode === 27) {
myFunc("one");
}
});
$('.alertBG').on('click', function () {
myFunc("other");
});
I'm trying to detect an Enter key press event when a button has been clicked.
I'm new in javascript and don't know the good way to go...
HTML:
<div id="div"> Only execute javascript on click, not enter key press </div>
JAVASCRIPT:
$("#div").click(function () {
/* IF ENTER KEY PRESSED, RETURN FALSE */
$("#div").keypress(
function(event){
if (event.which == '13') {
event.preventDefault();
alert('clicked');
}
});
/* Div has been clicked, continue code... */
});
This doesn't work...
Maybe there is a better way:
$("#div").MOUSE_CLICK_EVENT(function () {});
You need to stopPropagation like:
$('#div').keydown(function(event){
if (event.which == '13') {
event.preventDefault();
event.stopPropagation();
}
});
stopPropagation: Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
As others have noted, you need stopPropagation in addition to preventDefault, and you should be listening for the keydown event rather than keypress.
The pure JavaScript way to do this is:
document.getElementById('div').onkeydown = function (evt) {
if (evt.which === 13) {
evt.preventDefault();
evt.stopPropagation();
return false;
}
};
document.getElementById('div').onclick = function (evt) {
// do whatever you want here
};
try this if still needs anybody. Quick solution.
$("form").keypress(function(e) {
//Enter key
if (e.which == 13) {
return false;
}
});
Also you need to consider 3 key events: keydown, keypress and keyup.
$("#ID").keydown (function (e) {
if ( e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#ID").keyup (function (e) {
if (e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
$("#ID").keypress (function (e) {
if (e.key == 'Enter') {
e.preventDefault();
e.stopPropagation();
return false;
}
});
I'm trying to turn a button-click into a toggle that enables or disables a function, depending on its state. The function allows the enter key to be used for a form submission.
var enterToggle = true;
function enterToggleListener(elem) {
enterKeyPress();
elem.click(function() {
enterToggle = !enterToggle;
console.log('enter-toggle clicked')
if (enterToggle === false) {
console.log('enter toggle false')
// What do I need to add here to stop 'enterKeyPress()'?
} else {
console.log('enter toggle true')
enterKeyPress();
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(e.which == 13){
$('#noteButton').click();
}
});
}
enterToggleListener($('#toggle-button'));
What I don't understand is how to stop the enterKeyPress() function when enterToggle is false. Any suggestions?
EDIT: Cleaned-up code, with #James Montagne's answer added
var enterToggle = true;
function enterToggleListener(elem) {
elem.click(function() {
enterToggle = !enterToggle;
if (enterToggle === false) {
$('#enter-toggle').text('Enter key saves note (OFF)')
} else {
$('#enter-toggle').text('Enter key saves note (ON)')
}
});
}
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
enterKeyPress();
enterToggleListener($('#enter-toggle'));
function enterKeyPress() {
$('#noteText').keypress(function(e){
if(enterToggle && e.which == 13){
$('#noteButton').click();
}
});
}
You can simply check the value of the variable within your handler. This way you don't need to keep adding and removing the handler as seems to be your current approach.
However, if you must add and remove for some reason, you would use off.