简体   繁体   中英

jQuery - After click has finished and a delay occurs, execute a function

I'm wondering how I may approach building a filtering system where a user can essentially use a jQuery slider to select values, then an Ajax request to a database will fetch some new objects that fit the entered parameters.

How might I go about developing a feature where after I finish dragging the slider, a function will be executed after a 1 second delay which will make an Ajax request?

I've tried looking at the mouse events, however only mouseup seems suitable - but I'm not sure how to go about writing this.

Here's my slider in HTML...

<div class='drag-slider-wrap max marg'>
     <div class='slider-wrap'>
         <div class='slider-cont' id='slider-cont'>
         </div>
     </div>
</div>
<div class='slider-meta-wrap max marg'>
     <div class='drag-slider-bound-wrap' id='drag-slider'>
         <h3 class='slider-val'>$<span id='slider-val-min'></span> to $<span id='slider-val-max'></span>
         </h3>
     </div>
</div>

and in jQuery....

$(function() {
    $('#slider-cont').slider({
      range:true,min:0,max:100,step:5,values:[0,100],
      slide:function(event,ui) {
        $('#slider-val-min').html(ui.values[0]);
        $('#slider-val-max').html(ui.values[1]);
      }
    });
    $('#slider-val-min').html($('#slider-cont').slider('values',0));
    $('#slider-val-max').html($('#slider-cont').slider('values',1));
  });

Thanks!

Edit: Currently using the jQuery User Interface library

As I understand, you don't want to fire too many ajax requests and only want to send it after user has finished sliding. In that case use change event instead of slide

$( ".selector" ).slider({
  change: function( event, ui ) {}
});

What you want is to "debounce" the event, meaning to prevent it from firing to many times in a short period of times.

I wrote a jquery plugin for this exact purpose: jquery.ajaxDebounce , where you can configure what is the minimum "quiet period" before executing your function...

The plugin was made to debounce events that trigger ajax calls, but it is open source, and you can take it and use the internal logic for your own needs as you wish :-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM