Jordan Carter
Jordan Carter

Reputation: 1336

How to check Offset left value?

I'm trying to make something happen when my element has moved a certain left amount.

var box = $('#box');    
box.css('left', '500px'); //This is moving the box. I have a transition set in my css
if (box.offset().left == 200){
    alert("yes");
}

It doesn't alert yes, though. I tried outputting the offset().left position into the console, and it DOES reach 200. Am I just using inproper syntax?

Upvotes: 2

Views: 768

Answers (2)

Jordan Carter
Jordan Carter

Reputation: 1336

I was able to accomplish what I needed through the position() function. I have a side scrolling image that moves to the left, and you control a snowball that must hop over trees. I needed to detect when the image had moved a certain distance to the left, which meant it collided with a tree in the image.

	if (
	  (sideScroller.position().left < -960 && sideScroller.position().left > -1200 + mobileDelay) && (snowball.css('bottom') == '75px')
	) {
	  hitTree()
	}

mobileDelay was just some additional value for mobile devices, and hit tree just caused the snowball to evaporate when it hits a tree, lol. Position() works like a charm here.

I would just like to point out that Rayon's answer works as well, however I personally prefer to leave as much animation to CSS as possible, since in my experience it always runs smoother. Due to the large image, and the timed interval involved, using jQuery animation was not ideal in this situation.

Upvotes: 0

Rayon
Rayon

Reputation: 36609

Using elem.css('left','500px') will set the left of the element to 500px. As you are comparing with 200, it will never meet that condition. Even in the soultion provided below, you still con not reallt compare it with single value as the progress will never be one pixle at a time. In provided solution, range of 200 - 250 is given.

Use progress option of jQuery animate

Try this:

var box = $('#box');
var datatDiv = $('#data');
box.animate({
  'left': '500px'
}, {
  duration: 5000,
  progress: function() {
    var leftVal = box.offset().left
    if (leftVal > 200 && leftVal < 250) {
      datatDiv.text("YES");
    } else {
      datatDiv.text("NO");
    }
  }
});
#box {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="box">BOX</div>
<br>
<div id='data'></div>

Fiddle here

Upvotes: 1

Related Questions