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");
});
Related
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)
}
});
I have a bunch of places where I have to code the same functionality for a click and an ENTER key press (keyup). I'm ending up writing event handlers like this:
$('#SomeElement').on('click keyup', function (e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
// do what needs to be done
}
});
Is there an elegant way of handling this without the if statement? I hate the fact that it's an event handler specific to click and keyup, yet I have to check the event type inside the handler.
EDIT: I'm OK with abstracting out the if statement into a separate function. As long as I don't have to copy/paste the same line of code over and over again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
(function( $ ) {
$.fn.clickOrKeyPress = function( callback ) {
this.on('click keyup', function (e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
callback(e);
}
});
return this;
};
}( jQuery ));
You will need an if condition to confirm if the key pressed is enter. So you cannot completely get rid of if condition there.
But you can get rid of redundant conditions, like you don't need to check if the event type is keyup as we know if the event is not click, it will definitely be a keyup event.
So you can reduce your condition to
e.type === 'click' || e.keyCode === 13
My final solution - jQuery Event Extensions.
Create jQuery event extension specific for ENTER key.
$.event.special.enterkey = {
delegateType: 'keyup',
bindType: 'keyup',
handle: function (event) {
if (event.keyCode === 13)
return event.handleObj.handler.apply(this, arguments);
}
};
Now all I have to do is the following. Neat and elegant.
$('#SomeElement').on('click enterkey', function (e) {
// do what needs to be done
});
P.S. To all the incognito downvoters - you should be ashamed of yourselves.
I have not tested this yet, but maybe you can do named function and pass it with another callback to the event handler?...
Example (not tested!):
// Define the callback function somewhere
function clickKeyupCallback(e, callback) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
return callback;
}
}
$('#SomeElement').on('click keyup', clickKeyUpCallback(e, function() {
// your normal code here
}));
// EDIT
I realized the named function has to sit on a different place here if you want to do it this way and abstract the "if" part.
another example:
// Define the callback function somewhere
function clickKeyupCallback(e, callback) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
callback();
}
}
$('#SomeElement').on('click keyup', function(e) {
clickKeyupCallback(e, function() {
// do what ever needs to be done
});
});
I didn't understand clearly what you mean by "I have a bunch of places where I have to code the same functionality". But according to my understanding you want to attach some handlers to some elements that involve this check.
function doSomething(e) {
//do what needs to be done
}
function handleEvent(attachedHandler) {
return function(e) {
if (e.type === 'click' || e.type === 'keyup' && e.keyCode === 13) {
attachedHandler(e);
}
};
}
$('#SomeElement').on('click keyup', handleEvent(doSomething));
lemme know if it helps you...
How to combine these two into one to avoid duplicated the code twice:
document.querySelector('body').onkeydown = function(e){
if ((e.keyCode || e.which) == 77) {
e.preventDefault();
// code...
}
}
$("button").on('click', function(){
// code...
});
Basically I want to be able to either click on the element or press a key.
As #forgivenson suggested, you can avoid code duplication by putting your executable code into a function. It would look like this:
document.querySelector('body').onkeydown = function(e){
if ((e.keyCode || e.which) == 77) {
e.preventDefault();
doSomething(); // call your function on keydown
}
}
$("button").on('click', doSomething); // call your function on click
function doSomething() {
// code to execute on keydown or click
}
Below is an example. Typing m (or M) or clicking the button will call your code.
$("input").on('keydown', function(e){
if ((e.keyCode || e.which) == 77) {
e.preventDefault();
doSomething(); // call your function on keydown
}
});
$("button").on('click', doSomething); // call your function on click
function doSomething() {
// code to execute on keydown or click
console.log("You typed 'm' or clicked the button.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Type here">
<button>Click Me</button>
How about calling a function ???
function doStuff(){
}
document.querySelector('body').onkeydown = function(e){
if ((e.keyCode || e.which) == 77) {
e.preventDefault();
doStuff()
}
}
$("button").on('click', doStuff);
You can simply put all your code in a function, someFunc then you can call it
function someFunc() {
alert('Hi');
}
document.querySelector('body').onkeydown = function(e){
if ((e.keyCode || e.which) == 77) {
e.preventDefault();
someFunc();
}
}
$("button").on('click', function(){
someFunc();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Click me or `m` in your keyboard</button>
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'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;
}
});