Determine if collection of elements are visible using JQuery like $(".someClass") - javascript

I have a collection of elements on my page, and I want to see if they are visible or not currently.
So:
$(".someClass")
How can I loop through and figure this out? because if it is visible, i have to fire another function.

$(".someClass").each(function(){
if($(this).is(":visible")){
//item is visible: do something
}
});
how about that?

$(".someClass:visible")
will return the visible ones.

What you could do:
$(".someClass").each(function(x) { if ( x.style.display != "none" && x.style.visibility != "hidden" ) { your_function(); } });
where your_function() is the name of your function.

All solutions in terms of $('.someClass').is(':visible') are unreliable. All it tells us is if a particular element has a styling of display:none or visibility:hidden. This is not the same as whether an element is visible!
Consider a situation like this:
<div style="display:none;"><div class="someClass"></div></div>
Everybody can see that the element designated by $('.someClass') is invisible. But $('.someClass').is(':visible') will return true!
The only water-proof solution is to not only check for is(':visible') on the $('.someClass'), but on all of its parent elements as well. Only if for none of the parents holds that is(':visible') === false, we can conclude that $('.someClass') is actually visible.

Related

Jquery : Hide all children, and their children and etc... of a tag

I'm making a game in DOM (javascript + jquery) and I need to switch stages, for that I need to hide all from one stage, and show all of a new one. The showing part is easy cuz I'm creating new stuff. But I'd like a clean way of finding every last single child of a div, all his descendance, cousin, niece I don't care, and hide them. To show that in code something like :
while (child = $(this).hasChildren)
{
child.hide();
}
Instead of something like that :
$(this.id).children().children().children().hide();
$(this.id).children().children().hide();
$(this.id).children().hide()
$(this.id).hide();
The goal is to hide his children, and his children's children, and so on.
I hope I'm not too confusing.
Thanks in advance for the answers!
EDIT: for someone that doesn't want to hide the children, but access them all, and you can't use .find("*") then answer number two might be more adapted for you (the one from Rajan Goswami).
If you want to perform something on all children of an element you can use this syntax:
$('#myDiv *').hide();
or using .find()
$('#myDiv').find('*').hide();
Of course you can use any function, not just .hide()
You can try the following solution:
"myParentControl" is the ID of the parent-most control.
$(document).ready(function(){
HideChildren($(#myParentControl))
})
function HideChildren(cntrl){
if ( $(cntrl).children().length > 0 ) {
$(cntrl).children().each(function(){
HideChildren(this);
$(this).hide();
})
}
}

Check if DIV is visible using javascript

i needed to hide a div on my code behind:
bool hideDiv = false
//codes to change hideDiv
myDiv.visible = hideDiv;
and i want to check visibility of my div using javascript:
if (jQuery("myDiv") != null){
//some codes
}
else{
//some codes
}
and the 'jQuery("myDiv")' is always not null (even if the div was actually not visible), what is the better way to check if a div is visible?
You can use :visible selector inside is filtering function:
if ($('#myDiv').is(':visible'))
Notes:
You probably forgot the # before the id in your selector(jQuery("myDiv")).
jQuery will never return null no matter if the searched elements exist or not, unlike document.getElementById

Selecting the parent element that is hiding its children

I feel like this could have been asked before, but I can't seem to find it, so I'll ask myself.
I want to select the parent element that is the "cause" of its children being hidden. For example, a group of elements are essentially "hidden" but not because they have display:none but because some parent along the way has display:none.
If I only have a child element and I know that it is hidden, how might I easily find the parent that is causing it to be hidden.
I realize one solution is just to recursively loop through the parents such as...
function findHiddenParent(el){
var $el = $(el);
if($el.css('display') == 'none'){
return $el;
}
return findHiddenParent($el.parent());
}
Note I haven't tested the above code, its just for conceptualizing a solution
But is there an easier way, perhaps through some selector magic?
You can use .parents() then filter that to the last element that is hidden.
$(child).parents(":hidden").last().show();
it will select the parent element highest in the hierarchy that has display: none
Demo: http://jsfiddle.net/X9W2v/
Note, :hidden will also select elements with a width/height of 0.
Here's something similar to what you've got:
function findHiddenParents ( el ) {
return $(el).parents().filter(function () {
return $(this).css('display') == 'none';
});
}
This'll return all ancestors that are hidden. If you only want the closest or the farthest, you can just return it with .first() or .last() respectively.
If you're not actually interested in which elements are hidden, but just want to reveal them all, then you can't get any simpler than this:
$(el).parents().show()
This is how I would do it in plain JavaScript. Somehow I feel it's cleaner than the jQuery solutions that involve loops or callbacks (Kevin B's one-liner looks great!). The cons are, it's longer, and it doesn't check computed styles:
<div id="container">
<div id="a" style="display: none;">A
<div id="b">B
<div id="c">C</div>
</div>
</div>
</div>
var currentNode = document.getElementById('c');
while(currentNode.parentNode && currentNode.style.display !== 'none') {
currentNode = currentNode.parentNode;
}
alert(currentNode.id);
http://jsfiddle.net/nc4h2/

Is there a CSS :visible (scroll) selector?

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.
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);
};
There is no pure CSS way of doing this. As Kirean's comment already said, why would you want to style visible elements only? Invisible elements won't show their styling anyway. If you don't want the invisible element to take up space (aka, laid out), you should use display: none;
If you REALLY want a selector to select the visible elements, you could do what Widor suggested and use jQuery. You could first use jQuery to first select the visible elements, add a class to them, then use CSS to select the elements by that class.
$('div:visible').addClass('visibleElement');
.visibleElement {
color: red;
}
There is no Way to select invisible elements, using pure CSS
http://www.w3.org/TR/selectors/
However, if you have a class name or other selector, using jquery you can do something like the following
jQuery(selector).each(function(){
Var $this=$(this);
if ($this.css('visibility')==='hidden')
//set your style
})
Edit: after your edit, there is definitely no way of selecting what is within the viewport with CSS alone. It is a context free language of sorts.
However, you can always fool around with an elements offset position with jquery and determine if it's within the current viewport(window.scrollposition or something similar). This type of solution gets messy quickly, though.
This looks like a :visible selector to me:
http://api.jquery.com/visible-selector/
EDIT: Saw your javascript tag before your 'no CSS' caveat.
But this is a CSS selector of sorts.

How to tell if a DOM element is displayed?

This is not to be confused with "How to tell if a DOM element is visible?"
I want to determine if a given DOM element is visible on the page.
E.g. if the element is a child of a parent which has display:none; set, then it won't be visible.
(This has nothing to do with whether the element is in the viewport or not)
I could iterate through each parent of the element, checking the display style, but I'd like to know if there is a more direct way?
From a quick test in Firefox, it looks like the size and position properties (clientWidth, offsetTop etc.) all return 0 when an element is hidden by a parent being display:none.
Using Prototype:
if($('someDiv').visible) {...}
As I'm using MochiKit, what I came up with based on Ant P's answer was:
getElementPosition('mydiv').y != 0
I can also check whether it's in the viewport (vertically) by:
y = getElementPosition('mydiv').y
(y < getViewportPosition().y + getViewportDimensions().h &&
getViewportPosition().y < y)
Incidentally this also works in IE6.
Relying on the position being 0 is brittle. You're better off writing a helper function to iterate through the parents to check their display style directly.
Here's the iterative solution -
var elementShown = function(e){
if (e == document)
return true;
if ($(e).css('display') == 'none') //or whatever your css function is
return false;
return elementShown(e.parentNode);
}
.getClientRects() will return an empty array if the element is not displayed by inheritance (display="none" from parent/ancestor element)

Categories