Reputation: 15
I have 9 components (divs) inside one bigger. If I click on any of them it will toggle class that changes color of clicked div to red. I want to click and hold mouse button on one div and swipe mouse over other divs to change theirs color to red without the need to click every time. What's the best approach to achieve that result? Thanks for all tips and help!
Upvotes: 0
Views: 36
Reputation: 441
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
</head>
<body>
<style>
#mainDiv .CH {
height:200px;
text-align:center;
vertical-align:middle;
background-color:#ccc;
border:1px solid #fff;
}
#mainDiv .CH.highlighted {
background-color:green;
}
.CH{
height:100px;
}
</style>
<script>
$(function() {
var isMouseDown = false;
$("#mainDiv .CH")
.mousedown(function() {
isMouseDown = true;
$(this).toggleClass("highlighted");
return false; // prevent text selection
})
.mouseover(function() {
if (isMouseDown) {
$(this).toggleClass("highlighted");
}
});
$(document)
.mouseup(function() {
isMouseDown = false;
});
});
</script>
<div id="mainDiv" class="container">
<div class="row">
<div class="col-lg-4 CH">1</div>
<div class="col-lg-4 CH">2</div>
<div class="col-lg-4 CH">3</div>
</div>
<div class="row">
<div class="col-lg-4 CH">4</div>
<div class="col-lg-4 CH">5</div>
<div class="col-lg-4 CH">6</div>
</div>
<div class="row">
<div class="col-lg-4 CH">7</div>
<div class="col-lg-4 CH">8</div>
<div class="col-lg-4 CH">9</div>
</div>
</div>
</body>
Upvotes: 1