Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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');
        }
    });
});
like image 457
user2994453 Avatar asked Mar 21 '14 04:03

user2994453


People also ask

Which property is used to change the background color selector?

The background-color CSS property sets the background color of an element.


2 Answers

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

like image 73
Arun P Johny Avatar answered Oct 31 '22 14:10

Arun P Johny


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/

like image 30
Rajaprabhu Aravindasamy Avatar answered Oct 31 '22 14:10

Rajaprabhu Aravindasamy