Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery hover multiple blocks

I'm using jQuery hover function to hover over the box-empty class. On the hover, it replaces the box-empty to box-full.

  1. On hover over a block, how can I hover over all previous blocks too?
  2. When clicking on the block, how can I add the class box-full to all previous blocks?

Edit: Sorry, I forgot to mention that I need to include the block which has been clicked/hover also (not only the previous ones).

enter image description here

Here's my code:

HTML:

<div class="wrap"> 
    <span class="box box-empty"></span>
    <span class="box box-empty"></span>
    <span class="box box-empty"></span>
    <span class="box box-empty"></span>
</div>

jQuery:

$('.box-empty').hover(function () {
        $(this).addClass('box-full');
        $(this).removeClass('box-empty'); 
    }, function () {
        $(this).addClass('box-empty');
        $(this).removeClass('box-full');
    });

Demo: http://jsfiddle.net/aCP9x/

like image 791
user1251698 Avatar asked Apr 09 '26 07:04

user1251698


2 Answers

You need to use prevAll(). You will also need addBack() to include the element currently being hovered over. Try this:

$('.box-empty').hover(function () {
    $(this).prevAll().addBack().toggleClass('box-full box-empty');
});

Updated fiddle

Note I also simplified your code by using toggleClass, which means the same function can run on mouseenter and mouseleave within the hover.

like image 127
Rory McCrossan Avatar answered Apr 11 '26 20:04

Rory McCrossan


A pure CSS aproach:

span:hover ~ span, span:hover {
    border: 1px solid #000;
    background: #000;
}

jsFiddle here

As mentioned by Fabrício Matté below, you can take advantage of the CSS checkbox hack, allowing you to effectively toggled between selected/unselected.

like image 24
Josh Crozier Avatar answered Apr 11 '26 21:04

Josh Crozier