buckdanny
buckdanny

Reputation: 357

jQuery: if div is in viewport do something for one time

I want to "bounce" a div for one time if it is in the viewport.

I have something like this:

<script language="javascript" type="text/javascript"    
src="js/jquery.viewport.js">

<script type="text/javascript" charset="utf-8">

$(function() {
   $(window).bind("scroll", function(event) {

    $(".DIV:in-viewport").each(function() {

      $( ".DIV" ).effect( "bounce", {times: 1, distance: 12}, 200);

    });
   });
);

Everything is fine and the div is bouncing when its in the viewport but what can I do to exit the function after bouncing one time. At the Moment it is bouncing all time when it is in theviewport.

Thank you!

Upvotes: 0

Views: 977

Answers (2)

Gary Storey
Gary Storey

Reputation: 1814

Agree with above about unbinding but you could also use the one event handler which only fires one time then unbinds automatically:

$(window).one("scroll", bounce_my_div);

Upvotes: 1

Radley Sustaire
Radley Sustaire

Reputation: 3399

If you only want it to bounce once, the easiest way is to remove the "scroll" hook.

This will stop triggering the scroll after it has fired once.

$(function() {
  var bounce_my_div = function(event) {
    $(".DIV:in-viewport").each(function() {
      $( ".DIV" ).effect( "bounce", {times: 1, distance: 12}, 200);
    });

    $(window).unbind("scroll", bounce_my_div);
  };

  $(window).bind("scroll", bounce_my_div);
);

Note: This will not animate if you later scroll the div off the screen and back into the viewport again. Once it bounces, it's done, forever (until you refresh the page)

Upvotes: 1

Related Questions