Is there a CSS :visible (scroll) selector?
css, javascript
Solution
There is no standard pure CSS rule for assessing visibility.
As others have said, jQuery (if you wanted to use jQuery) has both a CSS selector extension `:visible` and the ability to execute `.is(':visible')` on any given jQuery object to get the computed style on any given DOM element with `.css("display")` or `.css("visibility")`.
It's not particularly simple in plain javascript to determine if an object is visible because you have to get the computedStyle (to take into account all possible CSS rules that might be affecting the element) and you have to make sure no parent objects are hidden causing the child element to be hidden. This is a function I have in my own personal library:
//----------------------------------------------------------------------------------------------------------------------------------
// JF.isVisible function
//
// Determines if the passed in object is visible (not visibility:hidden, not display: none
// and all parents are visible too.
//
// Source: http://snipplr.com/view/7215/javascript-dom-element-visibility-checker/
//----------------------------------------------------------------------------------------------------------------------------------
JF.isVisible = function(obj)
{
var style;
if (obj == document) return true;
if (!obj) return false;
if (!obj.parentNode) return false;
if (obj.style) {
if (obj.style.display == 'none') return false;
if (obj.style.visibility == 'hidden') return false;
}
//Try the computed style in a standard way
if (window.getComputedStyle) {
style = window.getComputedStyle(obj, "")
if (style.display == 'none') return false;
if (style.visibility == 'hidden') return false;
} else {
//Or get the computed style using IE's silly proprietary way
style = obj.currentStyle;
if (style) {
if (style['display'] == 'none') return false;
if (style['visibility'] == 'hidden') return false;
}
}
return JF.isVisible(obj.parentNode);
};
Problem
I want to change the style of visible elements using CSS only. Is there a selector that does it? It needs to work with Chrome and Firefox only. (I am building an extension / addon) If there isn't, is there a way to change the style of visible elements with a light javascript? Visible within the current scroll position. An element can be out of the scroll vision, or partially visible.