Reputation: 383
I am trying to apply the gradient effect, for example, if my mouse passes a grid cell it will light at first but the more I move my mouse towards that particular cell it will gradually get lighter. Here is my project https://repl.it/@antgotfan/etch-a-sketch and here is a working example (not mine btw), https://codepen.io/beumsk/pen/dVWPOW (just click on the gradient and will see the effect)
I am trying to use "this" and event.target to solve this problem but it is not working. I also tried to use fadeIn with jQuery but it is not my desired effect.
function incrementOpacity() {
let opacity = 0.1;
$(".cell").hover((event) => {
$(event.target).css({"opacity": `${opacity += 0.1}`,
"backgroundColor": "#f5f5f5"})
});
}
In the function, the opacity will increase forever but will stay white.
Upvotes: 1
Views: 299
Reputation: 29297
The issue is setting let opacity = 0.1;
outside of the .hover
event. The value should be based off of the cell being hovered, so fetch it inside the event via event.target.style.opacity
. Also, make sure it is parsed correctly as a float
to allow correct incrementing (parseFloat()
):
function incrementOpacity() {
$(".cell").hover((event) => {
let opacity = parseFloat(event.target.style.opacity);
$(event.target).css({"opacity": `${opacity + 0.1}`, "backgroundColor": "#f5f5f5"})
});
}
Here is the updated Repl.it for reference: https://repl.it/repls/GreenDigitalWireframe
Couple of optional changes; added check for maximum opacity. Anything over 1 is redundant. Also consider using mouseenter
for function so opacity is only increased when hovered on, and not hovered off:
function incrementOpacity() {
$(".cell").mouseenter((event) => {
let opacity = parseFloat(event.target.style.opacity);
if(opacity <= 0.9){
$(event.target).css({"opacity": `${opacity + 0.1}`, "backgroundColor": "#f5f5f5"})
}
});
}
Edit: For clarification, the reason using let opacity = 0.1
in conjunction with ${opacity += 0.1}
doesn't work is that in every instance of .hover
, the value opacity
was being incremented by 0.1
, but never reset. Essentially, after 9 (or 10) iterations, opacity
was at a value greater than 1, so each cell was "filled" instantly.
2nd Edit: To prevent issue with assigning multiple handles for the .hover
(or .mouseenter
) function, add event unbinding before setting:
function incrementOpacity() {
$(".cell").off("mouseenter");
$(".cell").mouseenter((event) => { ... });
}
...
function getRandomColors() {
$(".cell").off("mouseenter");
$(".cell").mouseenter((event) => { ... });
}
Also, make sure the bound event is consistent between the two functions, either .hover
or .mouseenter
.
Upvotes: 1