Call function with mouse click - javascript

I have a text area. Each time the enter key is entered the cursor travels to the next line of the text area and a function is called. This function posts/updates the entry in a database. I want it so that if I edit a line and then click on the mouse to resume typing at another line the function is again called on the mouse click
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
Is it possible to change my line to something like this and the method gets called on pressing the enter key or pressing the mouse(anywhere in the text area)?
if (e.keyCode == 13 || mouse.click) {
I know the above isn't correct but want to illustrate what I'm after

You could take use of jQuery's .on method like so:
$("#textarea").on('click keydown', (e) => {
if(e.keyCode && e.keyCode == 13 || e.type == "click" ){
// Do stuff
}
});
It takes a first parameter as string with different events, which mean you can listen to multiple events at once. The second is a callback function, where you can track the event that is triggered. Nb: Events are different between click and keydown. You can have a closer look by putting console.log(e); in your callback

You'll need to attach another event listener. The keydown event will not trigger when a mouse is clicked. You will need to add a $(...).click(function ...) as well. For example...
function myFunction (e) {
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
stream();
}
$("#textarea").keydown(function() {
if (e.keyCode == 13) {
myFunction()
e.preventDefault();
}
});
$('#textarea').click(myFunction)

Instead of putting a condition you can create 2 events and a common function to handle it.
Foe Example:
$("#textarea").keydown(function (e) {
if (e.keyCode == 13) {
logic1()
$("#textarea").click(function() { logic1();});
function logic1(){
document.addEventListener('keydown', newLine(this, "\n"));
console.log("code added");
e.preventDefault();
stream();
}

I don't know about jQuery but with vanilla JS you can do something like this:
const textarea = document.querySelector('textarea');
const foo = event => {
const output = document.querySelector('output');
output.textContent = event.type;
}
textarea.addEventListener('click', foo, false);
textarea.addEventListener('keypress', foo, false);
<textarea></textarea>
<output></output>

Related

Understanding how many times the jquery events are called and right handling of keyup event

I am trying to develop my webpage where I have a simple input field where I can type something. I want that when I type something and press "enter", a function gets called. The code I am using is:
$(document).ready(function(){
$("#searchBar").click(function(){
$("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$("#searchBar").bind("enterKey", function (e) {
searchFunction();
});
})
})
Something is not working well. I have 2 questions:
First of all by debugging on the browser I realize that the event "keyup" is called whenever I type any kind of character, but not when I press "enter" and I don't know why.
By always debugging and using a breakpoint on the keyup handler, it happens that when I press a key, in order to get out from the breakpoint I have to resume the script execution once.. then if I type another character and I go again at the breakpoint, I have to resume the script exectuion twice instead of once to continue debugging.. and so on incresing.. why do I have this kind of behavior?
Thanks in advance!
Two problems:
#searchBar only listens to keyUp and Enter if you have clicked on it at least once
#searchBar adds a new keyUp and Enter listener for each time it receives a click event
I'd just bind the events once like so:
$(document).ready(function(){
$("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$("#searchBar").bind("enterKey", function (e) {
searchFunction();
});
});
I can't come up with a valid reason to stop listening to the events, but if that's what you want, then I'd unbind just before or after the call to your searchFunction();
$(document).ready(function(){
$("#searchBar").click(function(e){
$(this).keyup(function (e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
$(this).bind("enterKey", function (e) {
searchFunction();
$(this).unbind("enterKey");
$(this).unbind("keyup");
});
});
// but you'd also need to unbind the events if the user clicks somewhere else in the document, otherwise, these events would still get attached every time the user clicks #searchBar
});
But it's unnecessary, as the events are only fired when #searchBar has focus. All these events also detach if you delete #searchBar
Also, why fire "enterKey" when you already are listening for keystrokes?
$(document).ready(function(){
$("#searchBar").keyup(function (event) {
var keycode = event.keyCode || event.which; //this for cross-browser compatibility
if (keycode == 13) {
searchFunction();
}
});
});
I have to resume the script exectuion twice instead of once to
continue debugging.. and so on incresing.. why do I have this kind of
behavior?
You are attaching a new keyup and enterKey event at each click on element.
Remove click event or use .one() to attach click event
$(document).ready(function() {
var search = $("#searchBar").keyup(function (e) {
if (e.keyCode == 13) {
search.trigger("enterKey");
}
})
.on("enterKey", function (e) {
searchFunction();
});
})
or, if one click is intended to begin process
$(document).ready(function(){
var search = $("#searchBar").one("click", function() {
search.keyup(function (e) {
if (e.keyCode == 13) {
search.trigger("enterKey");
}
})
.on("enterKey", function (e) {
searchFunction();
});
})
})

How to run function in function

I have this function, it should track ctrk+enter keys and send message. But function don't work. But if i call HotKeys(); in console, it works. So how to trigger it when script loaded? I new to javascript. Thanks and sry for my english.
function HotKeys() {
$('#msgbox').keydown(function (e) {
if (e.ctrlKey && e.keyCode == 13) {
document.getElementById("go").click();
}
});
}
HotKeys();
You can trigger the function on load by using:
window.onload = HotKeys();
If you want the function to be run anytime the hot keys are pressed, remove the function declaration around it so you just have the function body
Don't use a function, but attach a document ready handler like that:
$(document).ready(function() {
$("#msgbox").keydown(function (e) {
if (e.ctrlKey && e.keyCode == 13) {
$("#go").click();
}
});
});
This will register your handler when the document is ready. with your code, you indeed had to call HotKeys in order to register the handler.
try this
(function HotKeys() {
$('#msgbox').keydown(function (e) {
// when user presses ctrl + enter, click the "go" button
if (e.ctrlKey && e.keyCode == 13) {
document.getElementById("go").click();
}
});
})();

How to prevent a "keypress" event firing a "click" event when focus is on a button - javascript/html dom

I have a button that fires a "stopstart" function (animation). I also want to have a mouseless method to do this so I've bound the same function to the space bar. This works.
However if focus is on the button, and I press space - both events fire, can't work out how to stop this (the keypress event fires first - in chrome..)
Eventlistener code:
document.getElementById("stopstart").addEventListener("click",
function (event) {
stopstart();
}); //add event listener to "stopstart" button
document.addEventListener("keypress",
function (event) {
if (event.keyCode === 32) { //space key
stopstart();
}
}); //add spacekey event listener to document
I don't want to remove focus from the button, as I'd like to retain that functionality - the two events appear to be separately generated - so I haven't found how to detect that the click event was in fact generated by the space bar.
Is this solvable using without having to add temporary flags to catch it etc
The click location for key events is zero, zero so you can look for that.
document.getElementById("stopstart").addEventListener("click",
function (event) {
var x = event.x || event.clientX;
var y = event.y || event.clientY;
if (!x && !y) {
alert("key press");
return false;
}
stopstart();
});
http://jsfiddle.net/mScEC/
function (event) {
if (event.pointerType !== "mouse") return;
stopstart();
}); //add event listener to "stopstart" button
document.addEventListener("keypress",
function (event) {
if (event.keyCode === 32) { //space key
stopstart();
}
}); //add spacekey event listener to document```
You can simply use event.preventDefault() inside keypress event Listener to prevent the Button Click event from getting triggered on keypress
e.g
document.addEventListener('keydown', function (e) {
e.preventDefault();
if (e.key === 'Enter') {
try {
// if expression is not evaluated then catch block will be executed
screen.value = eval(screen.value);
}
catch (error) {
console.log(error.message);
screen.value = 'Invalid Operation';
}
}
})

bind click and keyup of different target to do same function

I have a submit button, I use $("#submit") to perform "myAction function", but in the same time I also want if the user pressed enter, it perform "myAction function"..
I can't do like this
$("#submit").on('click keyup', function(){
//myAction function
});
because I have to attach the keyup event to my input field instead of #submit..
Give a name to your function and bind both event on the selector. Then add a special condition:
function send(e){
if(e.type == 'click' || (e.type == 'keyup' && e.wich == 13))
}
$('[type=text]').on('keyup', send);
$('[type=submit]').on('click', send);
Write your my action as a separate function and use it as below
function myAction() {
console.log('act');
//do your stuff here
}
$("#submit").on('click', myAction);
$("input.enter").on('keypress', function (e) {
//enter key code is 13
if (e.which == 13) {
myAction()
}
});
Demo: Fiddle

press 'Enter' key to invoke a function

In my page there is a button and a text box.
Originally I invoke a function by click the button. Now I also want to implement it by press Enter key as well. But it is not working. Press Enter key doesn't reach myFunction.
<script type="text/javascript">
$(document).ready(function () {
$("#txt1").keyup(function (event) {
if (event.keyCode == 13) {
$("#btn1").click(myFunction);
}
});
$('#btn1').click(myFunction);
});
function myFunction() {
// do something, press enter key doesn't reach here.
})
}
</script>
You are almost right: Just invoke the handler with .click() or .trigger('click')
$(document).ready(function () {
$("#txt1").keyup(function (event) {
if (event.which== 13) {
$("#btn1").click(); // Just do a click.
}
});
$('#btn1').click(myFunction); //Your handler is already registered here.
});
function myFunction() {
// do something, press enter key doesn't reach here.
}
Also use event.which instead of event.keyCode when inside jquery event handler as it normalizes event.keyCode and event.charCode.
Instead of
$("#btn1").click(myFunction);
I reccommend to use:
$("#btn1").on("click", function () {
myFunction();
});
And then:
if (event.keyCode == 13) {
$("#btn1").click(); //click the button
}
JSFIDDLE

Categories