Reputation: 9537
I have a wrapper. Inside that wrapper I have an inner-wrapper. Inside that inner-wrapper I have a span. On that span mouseenter, I would like an alert to show the distance between the middle of that span and the right border of the wrapper (the main one: #wrapper). I tried few things with position() but did not manage to achieve what I just mentioned.
My html:
<div id="wrapper">
<div id="inner-wrapper">
<span id="me">It's me</span>
</div>
</div>
My css:
#wrapper{
width:400px;
height:300px;
margin-left:auto;
margin-right:auto;
margin-top:100px;
background-color:yellow;}
#inner-wrapper{
position:absolute;
width:100px;
margin-left:100px;
margin-top:50px;
background-color:blue;}
#me{
background-color:pink;}
My js:
$('#me').mouseenter(function(){
alert("distance from middle of span till right border of #wrapper???");
})
Upvotes: 1
Views: 679
Reputation: 911
You could use a combination of offset() and width()
$('#me').mouseenter(function(){
var middle = $(this).offset().left + $(this).width()/2;
var wrapperRight = $("#wrapper").offset().left+$("#wrapper").width();
alert( wrapperRight - middle);
})
EDIT: Fixed a the math error
Upvotes: -1
Reputation: 5286
Try this, I hope it helps
var spanLeft = $("#me").offset().left;
var wrapper = $("#wrapper").offset().left;
alert("distance from middle of span till right border of #wrapper???");
alert(spanLeft - wrapper);
Upvotes: 0
Reputation: 69915
$('#me').mouseenter(function(){
var $wrapper = $("#wrapper"), $this = $(this);
alert("distance from middle of span till right border of #wrapper is " + ($wrapper.width() - ($this.offset().left - $wrapper.offset().left + $this.width()/2)));
});
Working demo - http://jsfiddle.net/ShankarSangoli/NxhWk/
Upvotes: 2