Reputation: 7117
On my homepage I want to create a div where the use can click to change the background color. To change this I want to use an animation like this: After the click the new color should spread circular around the mouse click and fill the whole div with the new color.
For this I have to use JavaScript right or can I do this only with CSS to? Of course I know how to setup an EventListener
in JavaScript
but I have no idea how to fill the div circular with the new color. Do you have any ideas how to do this?
Upvotes: 1
Views: 1786
Reputation: 3888
This is probably what you are looking for: http://jsfiddle.net/F9pLC/
The idea is to create a circle using border-radius
and then make it absolutely positioned. Then we can grow it from the mouse coordinates.
// You can modify this if you want
var START_RADIUS = 25;
$("#someText").click(function (e) {
// Get the width and the height
var width = $(this).width(),
height = $(this).height();
// Get the diagonal (this is what our circle needs to expand to)
var diag = Math.ceil(Math.sqrt(width * width + height * height)) * 2;
// Get the mouse coordinates
var pageX = e.pageX,
pageY = e.pageY;
// Create a circle
$('<div class="circle">').appendTo("#someText").css({
width: START_RADIUS * 2,
height: START_RADIUS * 2,
"border-radius": START_RADIUS,
top: pageY - START_RADIUS,
left: pageX - START_RADIUS,
"background-color": $("#newColor").val()
}).animate({
width: diag,
height: diag
}, {
step: function (now, fx) {
// This occurs every step of the animation
// Modify the radius so that it grows along with the width and height
if (fx.prop === "height") return;
$(this)
.css("top", pageY - START_RADIUS - now / 2)
.css("left", pageX - START_RADIUS - now / 2)
.css("border-radius", now / 2);
},
easing: "linear",
duration: 2000, // The number of milis to grow completely
done: function () {
// Remove the circle and change the background color
$("#someText").css("background-color", $(this).css("background-color")).css("z-index", "");
$(this).remove();
}
});
$("#someText").css("z-index", -3);
});
// So that when we click on the color input, it doesn't create a circle
$("#newColor").click(function(e) { e.stopPropagation(); });
Upvotes: 5