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');
}
});
});
The background-color CSS property sets the background color of an element.
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
Try,
$(document).ready(function () {
var isMouseClicked = false
$('.box').mousedown(function () {
isMouseClicked = true;
}).mouseup(function () {
isMouseClicked = false;
}).mousemove(function () {
if (isMouseClicked) {
$(this).addClass("highlight");
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With