Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fire event when div is visible to visitor with jQuery?

Tags:

html

jquery

css

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?

like image 711
Paparappa Avatar asked Dec 07 '22 18:12

Paparappa


2 Answers

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
}
like image 88
Ya Zhuang Avatar answered Dec 10 '22 11:12

Ya Zhuang


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
});
like image 26
christianvuerings Avatar answered Dec 10 '22 11:12

christianvuerings