Justin Liwag Justin Liwag - 5 months ago 13
jQuery Question

Pre-highlight a set of divs

I have this code which has a set of

divs
that are highlight-able by clicking and dragging the mouse over these boxes. Each boxes represent a value with an increment of five. E.g 1st box is 0.5, 2nd is 1, and so on. When you highlight the divs it will return an array that contains the highlighted value.

If I have preset values. E.g
var x = [0.5, 1, 1.5, 2, 5, 5.5];
. How will I be able to highlight the
divs
matching the values in
array x


Here's a fiddle https://jsfiddle.net/guugmyn2/

var x = [0.5, 1, 1.5, 2, 5, 5.5];
Image of what I'm trying to achieve

Here's the code:

function calculateArray() {
var x = [];
$("div.range-bar").each(function(index, value) {
if ($(this).hasClass("highlight"))
x.push(0.5 + index / 2);
});
return x;
}
var x = [];
$(document).ready(function() {
var $range = $('.range-bar').mousedown(function() {
$(this).toggleClass('highlight');
var flag = $(this).hasClass('highlight');
$range.on('mouseenter.highlight', function() {
$(this).toggleClass('highlight', flag);
});


});
$(document).mouseup(function() {
$('.range-bar').off('mouseenter');
x = calculateArray();
});
});

Answer
function calculateArray() {
  var x = [];
  $("div.range-bar").each(function(index, value) {
    if ($(this).hasClass("highlight"))
      x.push(0.5 + index / 2);
  });
  return x;
}
var x = [0.5, 1, 1.5, 2, 5, 5.5];

$(document).ready(function() {
var arr = x.toString().split(',');

$.each(arr,function(i){

   var double="";
   var double=parseFloat(arr[i])+parseFloat(arr[i]);

   $("div.range-bar:nth-child("+double+")").toggleClass('highlight');
});
  var $range = $('.range-bar').mousedown(function() {
    $(this).toggleClass('highlight');
    var flag = $(this).hasClass('highlight');
    $range.on('mouseenter.highlight', function() {
      $(this).toggleClass('highlight', flag);
    });


  });
  $(document).mouseup(function() {
    $('.range-bar').off('mouseenter');
    x = calculateArray();
  });
});