Reputation: 2207
I wish to write a simple javascript function that toggles the visibility of a given element. Problem is, immediately after the page load, the initial style is unknown (at least to me). How can I determine what the current value of a given element's display style element is?
Upvotes: 2
Views: 4704
Reputation: 104800
Measuring offsets will work if you are only looking at the display property, but a test for visibility requires a look into the(browser-dependent) style cascade
document.deepCss=function(who, css){
var val, dv= document.defaultView || window;
val= who.style[css];
if(!val){
if(who.currentStyle) val= who.currentStyle[css];
else val= dv.getComputedStyle(who,"").getPropertyValue(css);
}
return val || "";
}
function isVisible(who){
return !!(document.deepCss(who,'visibility') != 'hidden' &&
document.deepCss(who,'display') != 'none');
}
Upvotes: 0
Reputation: 1115
No no, jquery is not needed.
IF that's display: none you are after. Else do the same thing with visibility: hidden.
if(mynode.style.display != "none")
{ .. }
else
Upvotes: -1
Reputation: 50503
Pure Javascript way, this should work.
function getStyle(elementId){
alert(document.defaultView.getComputedStyle(document.getElementById(elementId), '').getPropertyValue("display"));
}
Upvotes: 2
Reputation: 10060
From the jQuery/Sizzle source-code:
elem.offsetWidth > 0 || elem.offsetHeight > 0 // visible
elem.offsetWidth === 0 || elem.offsetHeight === 0 // hidden
where elem
is a DOM element.
Now I'm not entirely sure why they say that an element is visible if either dimension is bigger than zero. I'd say that both dimensions should be bigger than zero for it to qualify as 'visible', but I trust they know better. (Maybe one null dimension and another non-zero dimension is not even possible within the browser).
Update: There's another discussion on the topic and an alternate solution (haven't tried it though): How do I check if an element is really visible with JavaScript?
Upvotes: 7
Reputation: 11
$(document).ready( function () {
if $('#id').hasClass('hidden')
$('#id').toggelClass('hidden');
);
hidden is CSS class to hide element
Upvotes: -3
Reputation: 50503
function getDisplayStyle(elementId){
var display = document.getElementById(elementId).style.display;
alert(display);
}
Upvotes: 1
Reputation: 28215
using jQuery, assuming your element has an id of myElement:
if($("#myElement").is(":visible")){
// yep, it's visible - handle accordingly
}else{
// nope, not visible
}
Upvotes: -1