Search code examples
jquerytwitter-bootstrapbootstrap-slider

jQuery: Add class based on value of a slider / bootstra-slider.js


I'm using bootstrap-slider.js and I would appreciate if someone could help me add a function to add a class (.active) if the slider has a specific value (ex.1100) with jQuery

The class active should be added to an image or a div (i'm using font-awesome icons as an example in the demo)

my current js

$("#slider").slider({
    tooltip: 'always'
});

$("#slider").on("slide", function(slideEvt) {
    $("#slider-val").val(slideEvt.value);   /* Changes the value of the input field with the slider value */

});

Codepen: http://codepen.io/anon/pen/ojdEBM


Solution

  • Add an if statement to the slide handler to check if the slider value equals the specified value, and then use addClass() to add the active class to the elements.

    I've assumed you want the active class removed if the slider is NOT at the specified value, which is what the else block does. If you don't want it to be removed, then remove the else block.

    $("#slider").on("slide", function(slideEvt) {
        $("#slider-val").val(slideEvt.value);
        if (slideEvt.value == 1531){
          $('.fa-user').addClass('active');
        } else {
          $('.fa-user').removeClass('active');
        }
    });