June 26, 201511 yr Hi, Is it possible for an element, say a div or img, to be visible only if a specified section or id on the webpage was on screen. How can I achieve this? Thanks, R
June 26, 201511 yr Yes, you can do this with JavaScript / jQuery. You could create a function that shows an element when the scrollbar is at a certain position. Got an example of what you want?
June 27, 201511 yr Author Yeah. I've been trying to do this. And can this be done using CSS rather than Javascript or jQuery? Thanks
June 27, 201511 yr You can get the offset().top value of the support section, then compare that with the current scroll position plus the window height. Make this comparison on the scroll event then once the values overlap then add a class to the element and do as you wish in your CSS. var isElementInViewport = function() { var scrollTop = $(window).scrollTop(), winHeight = $(window).height(), element = $('#supportSection'), elementOffset = element.offset().top; if (elementOffset < scrollTop + winHeight) { element.addClass('fade-in'); } } $(window).scroll(isElementInViewport); Beware though of attaching functionality to scroll events, they can fire hundreds of times a second and if there's any complexity there or DOM interactions your scroll performance will suffer. It might be worth looking into scroll throttling if you find this to be the case. Edited June 27, 201511 yr by rbrtsmith
June 27, 201511 yr There might be an alternative sollution. There is a method called getBoundingClientRect() Apparently you can use it to return if an element is within a defined bounding box. If you set the bottom- and right-propperties of the bounding box to the clientHeight/clientWidth you can detect if the element is in the viewport or not without any fixed values. See how to create the function here http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport/7557433#7557433 Depending on what the function returns you can toggle between visible and a hidden class for the other element. Like rbrtsmith said scroll events can be resource intensive so if you don't mind a small delay you could call the function with a timer event every 500 ms or so. se setInterval(); Edited June 27, 201511 yr by Nillervision
Create an account or sign in to comment