Javascript: call function inside another function - javascript

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();
}
})
}

Related

onbeforeunload event exception?

i am wondering if there is a way to make onbeforeunload event alert be triggered with any other case except a specific function induced page reload.
most of the previously answered questions are at best 3 years old.
window.addEventListener('beforeunload', function (e) {
e.preventDefault();
e.returnValue = '';
});
document.getElementById("reload").addEventListener("click", myFunction);
function myFunction() {
location.reload();
} // I WANT TO EXCLUDE THIS FUNCTION FROM ONBEFOREUNLOAD EVENT ALERT
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
</head>
<body>
<button id="reload">RELOAD FROM HERE SHOULD NOT TRIGGER ONBEFOREUNLOAD ALERT</button>
</body>
</html>
A simple solution would be to set a flag, and check that flag in the beforeunload listener:
let beforeUnloadAlert = true;
window.addEventListener('beforeunload', function (e) {
if (!beforeUnloadAlert) return;
// etc
e.preventDefault();
e.returnValue = '';
});
function myFunction() {
beforeUnloadAlert = false;
location.reload();
}
Another approach would be to remove the listener just before calling .reload, by putting the listener in a named function:
window.addEventListener('beforeunload', unloadHandler);
function myFunction() {
window.removeEventListener('beforeunload', unloadHandler);
location.reload();
}

How to fix keypress event for enter key that is running a function twice while only being called once

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();

Jquery detect click OR keystroke?

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>

addEventListener on keyup javascript once

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

How to pass preventDefault call to other event?

When the event occurs, some other event is triggered by its name. In some cases the second handler can call preventDefault. How to pass this call to original event?
https://jsfiddle.net/edgv8qur/1/
$("button").click(function (event) {
$("body").trigger("some-custom-event");
// If the custom event was prevented, prevent original one too
if (true) { // How to check?
event.preventDefault();
}
})
$("body").on("some-custom-event", function (event) {
if (Math.random() > .5) {
console.log("prevent");
event.preventDefault();
} else {
console.log("allow");
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Test</button>
PS: Same question in Russian.
You can pass an array of arguments to trigger() which will be passed to the event handler set in on(). Here is how you do it:
$("button").click(function (event) {
function cb(prevent) {
// If the custom event was prevented, prevent original one too
if (prevent) {
event.preventDefault();
}
}
$("body").trigger("some-custom-event", [cb]);
})
$("body").on("some-custom-event", function (event, cb) {
if (Math.random() > .5) {
console.log("prevent");
event.preventDefault();
cb(true);
} else {
console.log("allow");
}
})
You can find out more about trigger() here.
UPDATE:
If you dont want to edit the handlers this is the way to go:
$("button").click(function (event) {
var event = jQuery.Event('some-custom-event');
$("body").trigger(event);
if (event.isDefaultPrevented()) {
event.preventDefault();
console.log("Prevented");
} else {
console.log("Allowed");
}
})
$("body").on("some-custom-event", function (event) {
if (Math.random() > .5) {
console.log("prevent");
event.preventDefault();
} else {
console.log("allow");
}
})
event.isDefaultPrevented() Returns whether event.preventDefault() was ever called on this event object.

Categories

Resources