Kaizokupuffball
Kaizokupuffball

Reputation: 2843

Ajax call on textarea change, but not on every change

I'm making a kind of note system for my users in Laravel application. I want this textarea that the user writes their notes on to be saved after the user is done typing, instead of running the ajax call on every change done because that would be a lot of requests.

What is the best way to achieve this? Should I use some sort of timer here to determine if the user is done writing?

Currently I'm just using the following:

notesTextarea.on('change', function(e) {
   $.ajax({ ... });
});

Upvotes: 4

Views: 684

Answers (5)

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4005

Similar to @Mamun's answer.

Call Ajax on keypress event:

$("textarea").on('keypress', function() {
    //$.ajax({ ... });
    console.log('request sent!');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
<textarea id="textarea"></textarea>
</p>

Upvotes: 0

Mamun
Mamun

Reputation: 68923

One way, you can make the call on pressing the enter key on keydown event:

notesTextarea.on('keydown', function(e) {
  if(e.keyCode == 13){
    $.ajax({ ... });
  }
});

You can also think of blur which will occur when the element loses focus

notesTextarea.on('blur', function(e) {
  $.ajax({ ... }); 
});

Upvotes: 3

wawa
wawa

Reputation: 5074

While the other proposed solutions (on blur or on keydown if it's the enter key), would work, I think they're not what you're looking for.

What if the user neither clicks outside the textarea, nor uses enter? I would use a technique called debounce instead. You can read about it for example here: https://davidwalsh.name/javascript-debounce-function or see an example here: https://www.geeksforgeeks.org/debouncing-in-javascript/

The short version is, it only calls a function after an event has stopped firing for a given length of time.

Add the debounce function to your code by either using an NPM package (ex. https://www.npmjs.com/package/debounce) or directly adding the necessary code:

// Returns a function, that, as long as it continues to be invoked, will not
// be triggered. The function will be called after it stops being called for
// N milliseconds. If `immediate` is passed, trigger the function on the
// leading edge, instead of the trailing.
function debounce(func, wait, immediate) {
    var timeout;
    return function() {
        var context = this, args = arguments;
        var later = function() {
            timeout = null;
            if (!immediate) func.apply(context, args);
        };
        var callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
    };
};

Source: https://davidwalsh.name/javascript-debounce-function which has taken it from Underscore.js

Then have a function doing your ajax calls like:

var makeAjaxCall = function(e) {
    $.ajax({ ... });
};

Now you can simply add a listener like:

var minTimeoutBetweenCallsInMilliSeconds = 500;
notesTextarea.on('change', debounce(makeAjaxCall, minTimeoutBetweenCallsInMilliSeconds));

Now the makeAjaxCall function would be called only 500ms after the last change event occurred, a.k.a. the user stopped typing.

Upvotes: 3

Deepak
Deepak

Reputation: 125

If you want to automate this saving you can call to ajax, after N number of characters typed by user each time.

Otherwise, you can call to ajax function on CTRL+S key combination

document.addEventListener('keydown', function(event) {

if (event.ctrlKey && event.key == 's') {
event.preventDefault();  //prevent default file save box open by browser
  alert('ajax call goes here!');


}

});

Upvotes: 0

Ricardo Pontual
Ricardo Pontual

Reputation: 3757

You can use the onlbur event instead. It happens when the element lost the focus, that could means you are no longer changing its content:

$("#notesTextarea").on('blur', function(e) {
     // $.ajax({ ... });
     console.log("has finished, content to be saved:" + $(this).val());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>
Notes: <textarea id="notesTextarea"></textarea>
</p>
<p>
Other something: <input type="text">
</p>

Upvotes: 3

Related Questions