How can I change the background color of multiple divs by dragging over them with the (clicked) mouse?

StackOverflow https://stackoverflow.com/questions/22550424

Question

Please have a look at this example.

I have 4 divs here with white background. When I click on a div, its background changes into blue. When I click it again background switches back to white.

Now I want to highlight multiple divs by dragging over them: I click on the first div and hold the mouse button down. The div gets blue. With the clicked button I can drag over the other divs now and their color is changed as soon as the cursor is over the element.

I haved tried some things with JQuery's .mousedown Function but I did not get it to work.

HTML:

<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>

CSS

.box{
    float: left;
    height: 100px;
    width: 100px;
    border: 1px solid #000;
    margin-right: 10px;
}

.highlight{
    background: #0000FF;
}

JS

$(document).ready(function(){
   $('.box').click(function(){
        if($(this).hasClass('highlight')){
            $(this).removeClass('highlight');
        }
        else{
            $(this).addClass('highlight');
        }
    });
});
Was it helpful?

Solution

You can use the mouseenter event to handle it

$(document).ready(function () {
    var $box = $('.box').mousedown(function () {
        $(this).toggleClass('highlight');
        var flag = $(this).hasClass('highlight')
        $box.on('mouseenter.highlight', function () {
            $(this).toggleClass('highlight', flag);
        });
    });
    $(document).mouseup(function () {
        $box.off('mouseenter.highlight')
    })
});

Demo: Fiddle

OTHER TIPS

Try,

$(document).ready(function () {
    var isMouseClicked = false
    $('.box').mousedown(function () {
        isMouseClicked = true;
    }).mouseup(function () {
        isMouseClicked = false;
    }).mousemove(function () {
        if (isMouseClicked) {
            $(this).addClass("highlight");
        }
    });
});

DEMO or http://jsfiddle.net/Vk24X/2/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top