Search code examples
javascriptjqueryrangeslider

DIV Element Show/Hide via RangeSlider


I want to show and hide some DIV elements with range. Each DIV element has a specific percentage value.

If the range is set to 70, the values of the DIV elements are checked and those with levels 70 and above are displayed. Those who are 70 and below are hidden.

But this code structure does not serve it and I am not able to resolve the error.

HTML:

<div class="similarQuestionFrame" data-similar-question-percentage-value="50">...</div>
<div class="similarQuestionFrame" data-similar-question-percentage-value="100">...</div>
<div class="similarQuestionFrame" data-similar-question-percentage-value="76">...</div>
<div class="similarQuestionFrame" data-similar-question-percentage-value="81">...</div>

JAVASCRIPT:

let range = document.getElementById("similarQuestionFilterInput");

let similarQuestionsPercentageFilter = () => {
  range.onchange = similarQuestionsPercentageFilter;
  
  $(".similarQuestionFrame").each(function() {
    if ($(this).attr('data-similar-question-percentage-value') >= range.value) {
      $(this).show();
    } else {
      $(this).hide();
    }
  });
  
  console.log(range.value);
}

Solution

  • You are applying the onchange handler in the handler itself and therefore it never gets called. Move it down a few lines and it should work:

    let range = document.getElementById("similarQuestionFilterInput");
    let similarQuestionsPercentageFilter = () => {
        $(".similarQuestionFrame").each(function () {
            if ($(this).attr('data-similar-question-percentage-value') >= range.value) {
                $(this).show();
            } else {
                $(this).hide();
            }
        });
    }
    //Apply onchange here
    range.onchange = similarQuestionsPercentageFilter;