Reputation: 10834
I have a div with a text. I want to create a yellow circle background when hovering the div instead of the cursor.
Here is what I got so far: JsFiddle Demo
HTML:
<div id="board">
<div id="ball"></div>
Lorem ipsum dolor sit....
</div>
JQuery:
$(function(){
$("#board").mousemove(function(e){
var ball = $("#ball");
var ballRadius = parseInt(ball.css("width"))/2;
var parentOffset = $(this).offset();
var relX = e.pageX - parentOffset.left - ballRadius;
var relY = e.pageY - parentOffset.top - ballRadius;
ball.css("top",relY + "px");
ball.css("left",relX + "px");
ball.css("display","inline-block");
});
});
I manage to do it, but, when hovering, all my text is being shifted.
Upvotes: 0
Views: 373
Reputation: 30015
The issue is your positioning. DEMO
#board{
position:relative;
#ball{
position: absolute;
The reason is that relative positioning just lets you moving things around with top
and left
but the element still effects the layout and positioning of its siblings. Position, absolute ultimately does the same thing, but it removes that element from the layout, so it does not effect any of its siblings or other's positioning.
The other thing both relative and absolute positioning do is they make the element an offsetParent
. In other words other absolute or relatively positioned elements contained within will be positioned based on that element. Because of this you need to make the #board
either relative or absolute, so that the positioning of #ball
will be based on #board
.
PS. When storing references to a jQuery object var ball = $('#ball);
its considered a good practice to put a $
on your variable. So... var $ball = $('#ball);
. That way other developers can easily tell what variables are actually jQuery objects.
Upvotes: 1
Reputation: 4624
I managed to change it up a bit.
var relY = e.pageY - parentOffset.top - ballRadius - $(this).height();
I put the ball div at the bottom, and then subtract the height of the div to determine current Y.
Upvotes: 0
Reputation: 3830
You will want to set both the ball and the boards position to absolute
#board{
position:absolute;
margin: 0 auto;
margin-top: 50px;
padding: 15px;
width: 500px;
height: 300px;
border: 1px solid black;
overflow: hidden;
cursor: none;
font-size: 20px;
}
#ball{
position: absolute;
width: 40px;
height: 40px;
background-color: yellow;
border-radius: 100%;
top: -50px;
left: -50px;
display: none;
z-index: -1;
/* transition: all 0.1s;
-webkit-transition: all 0.1s;*/
}
Upvotes: 0
Reputation: 15229
Add position: relative
to the #board
and change #ball
from position: relative
to position: absolute
.
Upvotes: 2