Reputation: 63
I'm looking to create a gradient highlight that follows the mouse such as in this Basic Idea example.
The highlight in the example is a single colour rgba(255,255,255,0.75)
.
I'd like a radial gradient with multiple colours, such as the CSS radial-gradient(ellipse at 100% 0%, yellow 0%, orange 50%, red 100%)
, but adjusted into jQuery so that it works within the function lightColor = "rgba(255,255,255,0.75)"
.
Also, is it possible to leave the highlight always visible inside the container, and simply anchor it to the mouse when inside it? Or it might be a different functionality entirely? Many thanks
$(function() {
var originalBGplaypen = $("#playpen").css("background-color"),
x, y, xy, bgWebKit, bgMoz,
lightColor = "rgba(255,255,255,0.75)",
gradientSize = 100;
// Basic Demo
$('#playpen').mousemove(function(e) {
x = e.pageX - this.offsetLeft;
y = e.pageY - this.offsetTop;
xy = x + " " + y;
bgWebKit = "-webkit-gradient(radial, " + xy + ", 0, " + xy + ", " + gradientSize + ", from(" + lightColor + "), to(rgba(255,255,255,0.0))), " + originalBGplaypen;
bgMoz = "-moz-radial-gradient(" + x + "px " + y + "px 45deg, circle, " + lightColor + " 0%, " + originalBGplaypen + " " + gradientSize + "px)";
$(this)
.css({ background: bgWebKit })
.css({ background: bgMoz });
}).mouseleave(function() {
$(this).css({ background: originalBGplaypen });
});
});
#playpen { background: rgb(155,155,155); text-align: center; height: 200px; line-height: 200px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<div id="playpen">Mouse Over</div>
Upvotes: 1
Views: 173
Reputation: 337626
To do what you require you can simply update the CSS which is used to create the radial gradient to match your needs. The only complexity is concatenating the x
and y
variables in to the correct place.
Also note that the demo HTML and JS you're using is very outdated. jQuery 1.4.4 is over 12 years old, and there's no longer any need to use -webkit
or -moz
prefixes on radial gradients.
Finally, to 'anchor' the radial gradient when before/after the mouse interacts with the #playpen
element, set it as the default background in CSS, and remove the mouseleave
event handler which re-sets the original radial styling.
With all that in mind, your code can be updated and simplified to just this:
jQuery($ => {
$('#playpen').on('mousemove', function(e) {
let x = e.pageX - this.offsetLeft;
let y = e.pageY - this.offsetTop;
$(this).css('background', `radial-gradient(ellipse 100px 100px at ${x}px ${y}px, yellow 0%, orange 50%, red 100%`);
});
});
#playpen {
background: radial-gradient(ellipse 100px 100px at center, yellow 0%, orange 50%, red 100%);
text-align: center;
height: 200px;
line-height: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<div id="playpen">Mouse Over</div>
Upvotes: 1