Reputation: 4812
I want to add class to the element when it gets visible on screen when scrolling:
<button class='btn btn-default' >
Hello
</button>
I want to add class to 'btn-default'
when the button gets visible on screen after scrolling or when page reloads.
Upvotes: 16
Views: 14436
Reputation: 1902
Try visible selector as in :
$(window).on('scroll', function(){
if ($(".btn").is(':visible')){
$(".btn").addClass("btn-default");
}
});
Upvotes: 8
Reputation: 166
Normally you can add and remove class below code but first you add(include) any jquery min js
Add class: $('.Yourclassname').addClass('addclassname');
Remove Class: $('.Yourclassname').removeClass('removeclassname');
Upvotes: -6
Reputation: 6600
You've to use jquery $(element).is(':visible')
to check whether an element is visible in an HTML document.
This is the snippet where it will add a class when document ready and when scrolled to the element.
$(function() {
if ($('#testElement').is(':visible')) {
$('#testElement').addClass('red');
}
});
$(window).on('scroll', function() {
var $elem = $('#testElement1');
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
if (elemBottom < docViewBottom) {
alert('hi')
$('#testElement1').addClass('red');
}
});
.red {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="testElement" class="btn btn-default">
Hello
</button>
<div style="height:400px">Some content</div>
<button id="testElement1" class="btn btn-default">
Hi
</button>
Upvotes: 1