I am trying to change the color of the elements, changing their class, while the mouse is held down, giving a "paint" effect. Doing it by mouse clicks I have it, here is the code:
$(() => {
$('table').on("click", "td", (event)=> {
let selected = $(event.target);
selected.toggleClass("obstacle");
});
})
table {
border-collapse: collapse;
}
td {
padding: 20px;
border: 2px solid black;
cursor: pointer;
}
.obstacle {
background-color: red !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>
Do you know of a way to change the style by holding down the mouse? Without having to make as many clicks as changes are desired.
I have tried with events like OnMouseDown and such, but I am not able to find the way.
The idea is while the mouse is pressed, do something like this:
A greeting and thanks in advance
I leave you this solution that I made using the mousedown functions that are activated when you click and I use a variable (IsClickDown ) that tells me that it is clicking (it does not release the button) by default it paints the td where you did the event, I also use mouseenter to see the action that the pointer enters the square validating if it is being clicked or not. Lastly, the mouseup function changes the state of IsClickDown and removes the class attribute.that you add to paint the td elements. Additionally add a validation to prevent the td drag function from executing. Remember that the mousedown and mouseup functions will only be performed when done inside the table element.
mousedown
You can use the and methodsmousemove
to be able to move through the table cells so you can color them while the mouse is down, and use the eventmouseup
to declassobstacle
all td elements when you release the mouse.I use a boolean variable
seleccionado
which will allow me to detect if the mouse is pressed or not. In addition, I also check if the element already has the class so as not to assign it again if the mouse is pressed.Your modified example:
Since you're using jQuery, one solution is to use its event
mousedown
:Below you can see it in action. In addition to the changes to your code, I added a class to your stylesheet that is applied to your elements when that event is fired.
See also : jQuery mousedown() Method
Indeed, you basically have to listen to three events of
Mouse
the , the first is mousedown() which is fired when the mouse button is pressed, the second is mouseover to listen when the mouse passes overtd
its table and the last mouseup when the mouse is released . button of themouse
.