jQuery addClass example
Change class name on click in jQuery
by tomoshige
HTML
<article>
<section class="main">
<div class="main-inner">
<div>
<img src="http://placehold.jp/bdbdbd/ffffff/560x300.jpg" alt="" class="fade--in fade--up">
</div>
<div class="flex">
<div>
<img src="http://placehold.jp/bdbdbd/ffffff/560x300.jpg" alt="" class="fade--in fade--down">
</div>
<div>
<img src="http://placehold.jp/bdbdbd/ffffff/560x300.jpg" alt="" class="fade--in fade--left">
</div>
</div>
<div>
<img src="http://placehold.jp/bdbdbd/ffffff/560x300.jpg" alt="" class="fade--in fade--right">
</div>
</div>
</section>
</article>
SCSS
body {
background-color: #ddd;
}
article {
padding: 50px 0;
}
img {
max-width: 100%;
height: auto;
}
.main-inner {
width: 100%;
max-width: 600px;
margin: 0 auto;
overflow: hidden;
background-color: #fff;
div {
text-align: center;
}
}
.fade--in {
opacity : 0;
transition : all 1000ms;
&.fade--up {
transform : translate(0, 50px);
}
&.fade--down {
transform : translate(0, -50px);
}
&.fade--left {
transform : translate(-50px, 0);
}
&.fade--right {
transform : translate(50px, 0);
}
&.fade--05sec {
transition : all 500ms;
}
&.fade--2sec {
transition : all 2000ms;
}
&.scroll--in {
opacity : 1;
transform : translate(0, 0);
}
}
JavaScript
$(window).on('scroll' , function (){
fadein();
});
function fadein (){
$('.fade--in').each(function(){
var elemPos = $(this).offset().top; // element top
var scroll = $(window).scrollTop(); // scroll position
var windowHeight = $(window).height();
var scrollBottomPos = scroll + windowHeight; // scroll bottom
// var elemBottomPos = elemPos + windowHeight; // element bottom
if (scroll > elemPos - windowHeight + 100){
$(this).addClass('scroll--in');
} else if ( scrollBottomPos < elemPos ) {
$(this).removeClass('scroll--in');
}
if (scroll == 0){
$(this).removeClass('scroll--in');
}
});
}