Created
August 3, 2018 14:09
-
-
Save kartick14/5a08f4971fbaf6f508b6565592dd8aea to your computer and use it in GitHub Desktop.
jQuery: check if element is visible on screen
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <div class="container"> | |
| <div class="text text-1"> | |
| Lorem ipsum <span></span> | |
| </div> | |
| <div class="text text-2"> | |
| Lorem ipsum <span></span> | |
| </div> | |
| </div> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $(window).scroll(function(){ | |
| $('.text').each(function(){ | |
| if(isScrolledIntoView($(this))){ | |
| $(this).children('span').text('visible'); | |
| } | |
| else{ | |
| $(this).children('span').text('invisible'); | |
| } | |
| }); | |
| }); | |
| function isScrolledIntoView(elem){ | |
| var $elem = $(elem); | |
| var $window = $(window); | |
| var docViewTop = $window.scrollTop(); | |
| var docViewBottom = docViewTop + $window.height(); | |
| var elemTop = $elem.offset().top; | |
| var elemBottom = elemTop + $elem.height(); | |
| return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop)); | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| $red:#f20; | |
| .container{ | |
| height:100rem; | |
| .text{ | |
| text-align:center; | |
| font-size:1.5rem; | |
| &.text-1{ | |
| margin-top:5rem; | |
| } | |
| &.text-2{ | |
| margin-top:50rem; | |
| } | |
| span{ | |
| color:$red; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment