Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function with mouse click

Tags:

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

like image 486
martinDa Avatar asked Jan 27 '23 05:01

martinDa


1 Answers

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

like image 65
Ole Haugset Avatar answered Jan 30 '23 09:01

Ole Haugset