Using jQuery, I want to change the color of all elements in the current window. The page scrolls, but I don't want elements scrolled off of the view - which I don't see - to be colored - only the elements in the current view window.
Asked
Active
Viewed 357 times
1
-
Why does it matter what color things you can't see are, just change the whole page's color.. – Greg Guida Jul 25 '11 at 14:19
-
the paint is just an example. the idea is some operation for the current visible elements in the scroll position – Royi Namir Jul 25 '11 at 14:38
-
1See [How to tell if a DOM element is visible in the current viewport?](http://stackoverflow.com/questions/123999/how-to-tell-if-a-dom-element-is-visible-in-the-current-viewport) – Gabriele Petrioli Dec 31 '13 at 15:53
-
1@GabyakaG.Petrioli Thanks. I already got that , but couldnt delete the question. ( and the answer here is incorrect as u see) – Royi Namir Dec 31 '13 at 15:55
-
@RoyiNamir, just added a custom jQuery selector implementation of that answer as an answer here.. – Gabriele Petrioli Dec 31 '13 at 16:13
2 Answers
3
Here is a custom jQuery selector implementing the code from https://stackoverflow.com/a/7557433/128165
$.expr[':'].inViewport = (function(){
function isElementInViewport (el) {
var rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
);
}
return function(obj, index, meta, stack){
return isElementInViewport(obj);
};
})();
//usage
$(':inViewport').css('color','red'); // color every element fully inside viewport
$('p:inViewport').css('color','red'); // color every paragraph element fully inside viewport

Community
- 1
- 1

Gabriele Petrioli
- 191,379
- 34
- 261
- 317
1
Try ":visible" selector to select only the visible elements

ShankarSangoli
- 69,612
- 13
- 93
- 124
-
it wont work , even visible elements which are down the scroll position - will be painted - which i dont want. i want only in currect window - in the scroll position. if i will scroll down - then i want the items to be painted in red. – Royi Namir Jul 25 '11 at 14:37
-
Do you have any containers which contain the elements on the page. If yes then we can find out the scrolltop of these containers and see if they are within the current window view. – ShankarSangoli Jul 25 '11 at 14:41
-
did you read the documentation for [`:visible`](http://api.jquery.com/visible-selector/)? nowhere in there does it say anything about calculating whether the element is on the view-able portion of the screen. – Greg Guida Jul 25 '11 at 15:00
-
@Greg - I very well know what ":visible" do. I didnt knew the user is looking for the elements in the current viewport which offcourse is not possible using this selector. – ShankarSangoli Jul 25 '11 at 15:06