4

The function: I want to change the class of a certain item when a user see a certain div (scrolls down to it).

How I do it now: I'm using this fine script (http://code.google.com/p/jquery-appear/) wich works really fine to just fire an jquery event when a div gets visible to the user. However it only fires once. So if you scroll down the page the jquery gets executed fine. But if I scroll up and then down again it doesent fire. This is my jquery:

$('#myDiv').appear(function() {
        $("#aDiv").addClass("active");
});

What I want to do: Make the script execute everytime "myDiv" appear and not only the first.

Does anyone have an idea on how I could do this?

Soundlink
  • 3,915
  • 2
  • 28
  • 36
Paparappa
  • 2,099
  • 3
  • 18
  • 35

4 Answers4

7

to judge the div is visible or not, you can:

$(window).scroll(function(event) {
    console.log($(".target").offset().top < $(window).scrollTop() + $(window).outerHeight());
});

so, i don't think you need any plugin.

just judge it by the expression like:

if($(".target").offset().top < $(window).scrollTop() + $(window).outerHeight()) {
    // something when the .target div visible
} else {
    // something when the .target div invisible
}
Ya Zhuang
  • 4,652
  • 31
  • 40
4

By looking at the source code of the jquery-appear plugin, it is possible to pass the argument one, to fire the event one time only (one: true), or every time it appears (one: false)

$('#myDiv').appear(function() {
    $("#aDiv").addClass("active");
}, {
    one: false
});
Soundlink
  • 3,915
  • 2
  • 28
  • 36
christianvuerings
  • 22,500
  • 4
  • 23
  • 19
  • This code didn't work however if i went in to the appear .js file and changed one to false my problem was solved. So your answer did more than inspiring me to solve it. – Paparappa Nov 08 '11 at 13:23
3

I use a similar plugin but this uses the bind method and uses an event -> http://remysharp.com/2009/01/26/element-in-view-event-plugin/

Sample usage :

$('div').bind('inview', function (event, visible) {
  if (visible == true) {
    // element is now visible in the viewport
  } else {
    // element has gone out of viewport
  }
});
Manse
  • 37,765
  • 10
  • 83
  • 108
1

This would probably be useful for you.

Anyhow, you could probably do it without a plug-in and with a simple expression instead:

var elem_top    = $("some_element").offset().top;
var elem_height = $("some_element").height();
var wind_height = $(window).height();
var scrollTop   = $(window).scrollTop;

if (elem_top > (wind_height + scrollTop) &&
   !(elem_top + elem_height) < wind_scrollTop) 
{
    //The element is inside the screen (e.g. it is directly visible)
}
Community
  • 1
  • 1
Marcus Hansson
  • 816
  • 2
  • 8
  • 17