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>
Related
I am creating a tip calculator. I have a button on the page that calculates the tip if you press it or if you press enter on the keyboard. When I press the enter key, the function that calculates the tip runs but then it runs again even though I did not call it again anywhere in my code. The odd thing is, is that the second time it runs, it goes into the variable where the function is stored and runs the function. I don't know why it goes into a variable that wasn't called.
I tried debugging to see if I missed a step and if I called the function twice somewhere, but I didn't.
Here is the keypress event:
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
Then right after that code is the calculateTip variable:
var calculateTip = function() {
some code that does calculations
}
After the key is pressed, calculateTip is executed, then it goes straight into the above variable to run calculateTip again.
I have my code inside an IIFE. I already tested to see if the code outside of this IIFE affected anything, it doesn't. The 'click' event listener works perfectly and only executes the calculateTip function once.
In this version of my code, calculateTip will print 'test' to the console twice if enter is clicked.
The IIFE:
var controller = (function(calcCtrl, UICtrl) {
var setupEventListeners = function() {
var DOM = UICtrl.getDOMstrings();
document.querySelector(DOM.button).addEventListener('click', calculateTip);
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
});
};
var calculateTip = function() {
console.log('test')
};
return {
init: function() {
setupEventListeners();
}
}
})(calculateController, UIController);
controller.init();
with jquery you can solve it
$(document).unbind('keypress').bind('keypress', function (e) {
if (e.keycode === 13 || e.which === 13) {
calculateTip();
}
});
Just add event.preventDefault(); inside the callback, it helped me.
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
event.preventDefault();
calculateTip();
}
}
It's give one time would you please check this out.
<script type="text/javascript">
document.addEventListener('keypress', function(event) {
if (event.keycode === 13 || event.which === 13) {
calculateTip();
}
});
var calculateTip = function() {
console.log("enter clicked");
}
</script>
Try to put the following to your event listener function:
event.stopImmediatePropagation();
I want to run countup(); and random(); function after I hit enter on my keyboard. But I wanna make that it's only work for the first time.I mean when first time i hit enter, it will run that function. But if those function already run and I hit enter again, it'll never effect anything.
Here's my code :
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
countup();
random();
}
});
Anyone can help me? Thanks.
Do something like this
// Create a named function as your event handler
var myFunction = function (e) {
if (e.keyCode === 13) {
// Do your stuff here
countup();
random();
// Remove event listener so that next time it is not triggered
removeEventListener("keydown", myFunction);
}
};
// Bind "keydown" event
addEventListener("keydown", myFunction);
Idea is user a global variable, set it after firing event.
var is_fired = false;
addEventListener("keydown", function(e){
if (e.keyCode === 13 && is_fired == false) {
countup();
random();
is_fired = true
}
});
You can make click event listener work only once after trigger it.you just need to add another argument to addEventListener() which is {once:true}and it will work as expected:
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
countup();
random();
}
},{once: true});
Check my question it's similar to your case.
Also you can just use removeEventListener()method but you should defined your Anonymous function before as external function like myKeyPressed() and then inside if condition remove event Listener from your element:
element.removeEventListener("keydown", myKeyPressed);
var is_clicked = false;
addEventListener("keydown", function(e){
if (e.keyCode === 13 && !is_clicked) {
countup();
random();
is_clicked = true;
}
});
There is a removeEventListener function in javascript but it's tricky to implement that inside the function you are calling on addEventListener.
Try this, it worked in jsfiddle.
addEventListener("keydown", function(e){
if (e.keyCode === 13) {
alert("i did it");
this.removeEventListener('keydown',arguments.callee,false);
}
});
You can add a variable to check the status of your keydown.
The first time you use it, set it up to true. So you will only have this function triggered once.
var n = document.getElementById("txtInput"),
r = document.getElementById("result"),
loadFlag = true;
n.addEventListener("keyup", function(e) {
if (e.keyCode === 13 && loadFlag ) {
countup(r);
random(r);
loadFlag = false;
}
}, false);
To add keydown to an element in your HTML code.
element.addEventListener("keydown", event => {
//check if event is cancelable because not all event can be cancelled
if(event.cancelable)
{
//this prevent element from executing the default event when user click
event.preventDefault()
if(event.keycode === 13){ //write your statement here }
}
}
for more https://www.w3schools.com/jsref/event_preventdefault.asp
I have a simple code which calls a function func1() when the user presses "A". Inside func1() I would like that, if a certain condition is satisfied, another function func2() is called and func1() is stopped.(A short example of what I am doing is shown below). How can I do this? Thank you!
<html>
<head>
</head>
<body>
<script>
$(document).ready(function() {
document.addEventListener("keydown", function (e) {
else if (e.keyCode === 83) { // If "S" is pressed the game starts
func1();
}
});
})
function func1(){
$(document).ready(function() {
document.addEventListener("click", function(e) {
var myVar = Math.floor( Math.random() *6);
if (myVar>3){
func2();
}
}, false);
});
}
function func2(){
/////
}
</script>
You need to refactor your code and remove the unnecessary call to $(document).ready(). I'm assuming it's the click event you want to disable...
Let me know if it's the keypress you want to disable.
EDIT:
I edited the code to remove the func2 event listener when 's' key is pressed, and add click event listener to document when func2 is called.
$(document).ready(function() {
document.addEventListener("keydown", function(e) {
var keyCode = e.which || e.keyCode;
$('.keypressed').html(String.fromCharCode(keyCode));
if (keyCode === 83) { // If "S" is pressed the game starts
document.removeEventListener('click', helper2);
func1();
}
});
});
//refactored the handler function to stand on its own
function helper(e) {
var myVar = Math.floor(Math.random() * 6);
console.log('myVar in func1() = ', myVar);
if (myVar > 3) {
func2(e);
return;
}
}
function helper2(e) {
console.log('func2() click event called!')
}
function func1() {
document.addEventListener("click", helper, false);
}
function func2(e) {
//disable the click event listener
document.removeEventListener('click', helper);
document.addEventListener('click', helper2)
console.log('called func2()');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<div class="keypressed"></div>
<body>
</body>
</html>
You can use .off() to remove event listener attached to jQuery object. .ready() call within func1 is not necessary.
else..if should be if, unless there is if statement not included at javascript at Question.
$(document).on("keydown", function() {
if (/* condition */) {
$(this).off("keydown");
func1();
}
});
function func1() {
$(document).on("click", function() {
if (/* condition */) {
$(this).off("click");
func2();
}
})
}
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;
}
});