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
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'm using a script (impress.js) that bins some particular action to keyup and keydown events for left, right, up and down arrows.
In some particular moments (for example while typing in a textarea) I want back the default behaviour for the arrows.
I tried without success with
$("a#show-ta").click( function() {
document.addEventListener("keydown", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
document.addEventListener("keyup", function ( event ) {
if (event.keyCode >= 37 && event.keyCode <= 40) {
return;
}
});
});
where a#show-ta is the button that shows my textarea.
You want to prevent the keypress from bubbling up to the document where (I assume) Impress binds its handlers:
$("textarea").on('keyup keydown keypress', function(e) {
e.stopPropagation();
});
If you need the event in a specific zone, such as a texarea, you should stop the propagation of the event like this :
$('textarea').keydown( function(ev) {
ev.stopPropagation();
});
If the events are necessary for the whole page but you want to exclude while you are in a textarea, for example, you could raise a flag which you would validate in the event.
var keydownActivated = true;
$('textarea').keydown( function(ev) {
if (keydownActivated) {
ev.preventDefault();
// dostuff
}
});
This will more or less get you where you are going. Create a flag that tracks whether or not the textarea has focus, and check that flag in your current key press event handlers. I can't see all of your code, so this is just a simple example:
var textareaHasFocus = false;
var textarea = document.querySelector('#yourTextarea');
textarea.addEventListener('focus', function(event) {
textareaHasFocus = true;
}, false);
textarea.addEventListener('blur', function(event) {
textareaHasFocus = false;
}, false);
document.addEventListener("keydown", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});
document.addEventListener("keyup", function ( event ) {
if (textareaHasFocus) return true;
// your current keyboard handler
});
I have a jQuery button function that works properly and executes the code inside, what I want is when I press the Enter on the search box, it will execute the same function inside the onclick one. I don't want to copy paste the entire code of my function to the on Enter press event because that will be the wrong way to do it. This is the click event:
$("#checkScout").click(function(e){
...
}
And this is the one I tried with the on enter press
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
if (e.keyCode === 13) {
$("#checkScout").click(function (e);
}
});
it should be just
$("#checkScout").click();
so
$('#addChannelsToScout').keydown(function (e) {
if (e.which == 13) {
$("#checkScout").click();
//$("#checkScout").trigger('click');
}
})
Demo: Fiddle
Try:
$("#checkScout").trigger('click');
Trigger Performance
Change:
$("#checkScout").click(function(e);
To:
$("#checkScout").click();
Your code:
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
if (e.keyCode === 13)
{
$("#checkScout").click();//modified here
}
});
just this will work $("#checkScout").click();
var enterKey = document.getElementById("addChannelsToScout");
enterKey.addEventListener("keydown", function (e) {
if (e.keyCode === 13)
{
$("#checkScout").click();
}
});
actually you need to trigger the event. since it is already been handled it will perform the task that you have written in the event
Check Triggers here http://api.jquery.com/trigger/
$("#checkScout").trigger("click");
I have a textarea, and on each enter i want it to get blank if something has written. but my problem is; on the first enter it line breaks, and you continue to write from the second line. it only happens at the first enter. there is no problem with emptying the textarea, you just continue to write from the second line, which is the problem.
onkeydown= if(event.keyCode == 13){
sendMessage();
}
function sendMessage(user){
var message = $('#textarea').val();
$('#textarea').val('');
}
if(event.keyCode == 13) {
sendMessage();
if (event.preventDefault) event.preventDefault();
return false;
}
keydown happens before the character is entered in the textarea, so you just have to call preventDefault on the event so it doesn't enter a line break after you've called your function that clears the text-area. return false alone should be enough too if the code above is inline in the HTML, which isn't really recommended. See updated solution below:
For unobtrusiveness and back-compat, I'd recommend doing it all with jQuery:
$('#textarea_ID').keydown(function(e) {
if (e.which == 13) {
e.preventDefault();
var message = $(this).val();
$(this).val('');
//rest of your function using `message` here
}
});
Fiddle
In jQuery use the which property for the code. Then return false with e.preventDefault();
var field = $('.classname');
field.keydown(function(e){
if(e.which==13){
sendMessage();
e.preventDefault();
}
});
Simply add return false; to your keydown function. This prevents the default action of the key (a newline in this case) from being executed.
You may also want to include code to handle Internet Explorer's way of getting keycodes. Your new function would be:
onkeydown = function (e) {
// Gets keycode cross browser
e = window.event ? window.event : e;
var keycode = e.keyCode !== null ? e.keyCode : e.charCode;
// Checks if it was the enter key that was pressed (enter = keycode 13)
if (keycode === 13) {
// Calls function to do stuff
sendMessage();
// Cancels the default action of the (enter) key
return false;
}
}
I have a input on page in some div:
<input style='border:1px solid black;' type='text' id='inputFindBy_Name' />
and o jquery javascript function monitored it:
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
var searchField = "Name";
var searchValue = $(this)[0].value;
var pageIndex = "1";
var sortField = "Name";
Application.Services.ProductTypeService.LoadMainGridProductType(pageIndex, sort, sortField, searchField, searchValue, ResultLoadMainGridProductType, ErrorLoadMainGridProductType);
}
});
when user typed something and pressed ENTER (event.keyCode == 13) I need do some thing but without reloading the page. How do that?
Try this one
$("div[id=mainGridPage] input").bind("keyup", function (event) {
if (event.keyCode == 13) {
// needed do something here without reloading the page
return false;
}
});
just like a link.
Just return false from within the function:
var code = event.keyCode || event.which;
if (code == 13) {
// do what you have to do.....
return false;
}
Edit: the keyup event is triggered "too late" after the form submission event was already dispatched - you can't cancel or stop it in that stage. So, handle the keypress event instead. Change the line to:
$("div[id=mainGridPage] input").bind("keypress", function (event) {
And the return false; will indeed stop the form from submitting.
Live test case.
You need to do a event.stopPropagation() and maybe the return false;. Please use event.which because event.keyCode is not compatible with all browsers, also you are using div[id=mainGridPage] input which searches for an ID, a better way to put this down is: div#mainGridPage input, and probably faster.
$("div#mainGridPage input").bind("keyup", function (event) {
if (event.which == 13) {
event.stopPropagation();
// needed do something here without reloading the page
return false.
}
});
try this. this will work i think:
$("div[id=mainGridPage] input").keypress(function(event) {
if (event.keyCode == 13) {
// do your code
console.log('hello');
return false;
}
});