Home > database >  jQuery .append() and .remove() skipping behavior with slider function
jQuery .append() and .remove() skipping behavior with slider function

Time:10-27

I'm having trouble with some dynamic HTML. I've got a slider that adds or removes DOM elements as the value changes. Each time it increases, an element is added, and each time it decreases, an element is removed.

Here's the HTML:

<input type="range" min="3" max="16"  value="3" tabindex="-1" oninput="slider(this.value)">

<div >
  <div >
    <div ><span></span></div>
    <div ><span></span></div>
    <div ><span></span></div>
  </div>
</div>

Here's the JS:

var colorCount = 3;
function slider(value) {
  if (colorCount < parseInt(value)) {
      $('.boxes').append('<div ><span></span></div>');
      colorCount = value;
  } else {
      $('.box:last-child').remove();
      colorCount = value;
  }
}

http://jsfiddle.net/meu9carx/

However, when I quickly move the slider, it seems to skip or trip up, and I end up with more or fewer than I started with. The slider has a range from 3-16, but sometimes the min value goes to more or less than 3. Sometimes, all the boxes vanish.

Is there a smarter way to code this? I'm trying to avoid hard-coding divs here.

CodePudding user response:

If the mouse moves fast, it's possible for the input value to change by more than one (in either direction) during a single input event. Use the value in the input to determine how many squares there should be exactly, rather than adding or removing only a single element each time.

const boxes = $('.boxes');
$('input').on('input', function() {
  const targetSquares = Number(this.value);
  while (boxes.children().length < targetSquares) {
    boxes.append('<div ><span></span></div>');
  }
  while (boxes.children().length > targetSquares) {
    $('.box:last-child').remove();
  }
});
body{
  background: #777;
  font-family: 'Arimo', sans-serif;
}

.container { padding: 20px 0; }
.boxes { display: flex; }
.box {
  padding: 10px;
  background: #ffffff;
  height: 100px;
  flex: 1;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="range" min="3" max="16"  value="3" tabindex="-1">

<div >
  <div >
    <div ><span></span></div>
    <div ><span></span></div>
    <div ><span></span></div>
  </div>
</div>  

  • Related