Call function with mouse click

Viewed 1555

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

4 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

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