Jonathan
Jonathan

Reputation: 724

Adding class to div when inside viewport

I'm trying to make a div element get an additional class added to it when it's inside the viewport. To achieve this I'm using a minified JQuery 1.11.0.

This is my JQuery code:

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
    $('.textbox').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('visible');
        }
    });

});

I'm sure my class is visible but it's not adding the visible class for some reason. Any ideas why? The CSS of my two affected classes are as follows:

.textbox {
    width: 70%;
    margin: 0 auto;
    opacity: 0;
    transition: all .5s;
    top: -10px;
    position: relative;
}
.textbox .visible {
    opacity: 1;
    top: 0;
}

Upvotes: 1

Views: 14751

Answers (2)

issue is in the inequalities, they should be stated like this:

elemTop <= docViewTop &
docViewBottom <= elemBottom

elemBottom should be greater than docViewBottom (since the latter has to be closer to the top) and elemTop bellow docViewTop (since we need docViewTop to be bellow elemTop, the former will be further away from top, so the value will be greater).

Upvotes: 0

Mihai T
Mihai T

Reputation: 17697

it's working. you just need to set .textbox.visible in css without spaces between the classes. they are 2 classes of the same element, so no space between them. see snippet below

or jsFiddle

( red div is you visible div )

function isScrolledIntoView(elem) {
    var docViewTop = $(window).scrollTop();
    var docViewBottom = docViewTop + $(window).height();

    var elemTop = $(elem).offset().top;
    var elemBottom = elemTop + $(elem).height();

    return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

$(window).scroll(function () {
    $('.textbox').each(function () {
        if (isScrolledIntoView(this) === true) {
            $(this).addClass('visible');
        }
    });

});
.textbox {
    width: 70%;
    margin: 0 auto;
    opacity: 0;
    transition: all .5s;
    top: 0px;
    position: relative;
		background:red;
		height:300px;
}
.textbox.visible {
    opacity: 1;
    top: 0;
}
.anotherdiv {
	width:100%;
	background:blue;
	height:100vh;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="anotherdiv">

</div>
<div class="textbox">

</div>

Upvotes: 7

Related Questions