Check if div only contains inline elements - javascript

I am trying to run a function that executes if a div only contains inline elements
I am not sure how to go about this short of having to list out every single block element and checking that the div doesn't contain that.
$(this).children().each(function(){
if(this.nodeName.toLowerCase() == 'p' || this.nodeName.toLowerCase() == 'h1' etc...){
check = true; //it contains block element so it is not only inline elements
return false;
}
});
Is there a better way?
Edit
To help clarify, I have a content editable div and the problem is that the user can delete all the block elements out of the div. I need to check this and add a block element to the div.

Check to see if those elements are actually block-level, as CSS can change their behavior completely:
var has_inline = $('#parent').children().filter(function() {
return $(this).css('display') !== 'block';
}).length > 0;
I'm not sure what you consider inline-block to be, so I'll just assume it behaves like an inline element for your purposes.
Demo: http://jsfiddle.net/hXckq/2/

How about has() in jQuery:
if ($(this).has("p,h1, ...")) { ... }

You could put the inline elements into a hash, then use in or hasOwnProperty:
var inline = {
"span": true,
"a": true,
...
};
if(this.nodeName.toLowerCase() in inline) {
}

Maybe try this, check if the css property of each element is indeed inline, this should work though I did not test this syntax may be incorrect:
$(this).children().each(function(){
if($(this).css('display', 'inline') == true){
return true;
}else{
return false;
}
}

Related

check if class does not exist on any of data- items

I have a list of div elements with a data-windows attribute:
I basically want to check if any of these are not hidden (and doing something if they are all hidden)
I'm looping through them like so, this works but I'm wondering if there's a more efficient way:
$("[data-windows]").each(function () {
if (!$(this).hasClass('hidden')) {
isSomethingShown = true;
return false;
}
});
You can use :visible pseudo selector :
if($("[data-windows]:visible").length){
//Atleast 1 is visible
}else{
//All hiden
}
or
var isSomethingShown = !!$("[data-windows]:visible").length; // Bang!Bang! [!!] convert into a boolean
Of course, if you want to explicitly check the class, both selector can be change to (and maybe should be for faster performance) $("[data-windows].hidden")
how bout this oneliner:
return $("[data-windows].hidden").length == 0 ? false : true;

How to check if HTML style attribute exists with javascript

I'm trying to find out if a specific element has an inline style attribute or not:
I'm sure there's an easy method to check this, but I can't seem to find it.
I tried multiple things already including this:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.style.display.toString=="")
alert("Empty");
else
alert("Not Empty");
Thank you for your help!
if(contentWrapper.getAttribute("style")){
if(contentWrapper.getAttribute("style").indexOf("display:") != -1){
alert("Not Empty");
} else {
alert("Empty");
}
}
if(!contentWrapper.getAttribute("style"))
OR
if(contentWrapper.getAttribute("style")==null ||
contentWrapper.getAttribute("style")=="")
the above lines will work for you (anyone can be chosen).
In second solution:
first check watches if style attribute is present in the element, 2nd check ensures that style attribute is not present as an empty string e.g. <div id="contentWrapper" style="">
Complete code is given below:
var contentWrapper = document.getElementById("contentWrapper");
if(contentWrapper.getAttribute("style")==null || contentWrapper.getAttribute("style")=="")
alert("Empty");
else
alert("Not Empty");
http://jsfiddle.net/mastermindw/fjuZW/ (1st Solution)
http://jsfiddle.net/mastermindw/fjuZW/1/ (2nd Solution)
I missed #plalx's comment the first time I scanned this page.
if (element.hasAttribute("style"))
{
var styleText = element.getAttribute("style")
}
On a related note, regarding styles...
//to get info about the end results of CSS
var computedStyle = element.currentStyle || getComputedStyle(element, null);
and
//to iterate over css styles from style tags or linked CSS
for i ...
document.styleSheets[i].rules ...
//great for searching with
var elements = document.querySelectorAll(rules[i].selectorText);
The style object has a length property which tells you if the element has any inline styles or not. This also avoids the problem of having the attribute style being present but empty.
// Would be 0 if no styles are applied and > 0 if there are inline styles applied
contentWrapper.style.length
// So you can check for it like this
contentWrapper.style.length === 0
To check style attribute exist or not for given Id
if(document.getElementById("idname").hasAttribute("style")){
alert("Style attribute found");
}else{
alert("Style attribute not found");
}

How to change text inside span with jQuery, leaving other span contained nodes intact?

I have the following HTML snippet:
<span class="target">Change me <a class="changeme" href="#">now</a></span>
I'd like to change the text node (i.e. "Change me ") inside the span from jQuery, while leaving the nested <a> tag with all attributes etc. intact. My initial huch was to use .text(...) on the span node, but as it turns out this will replace the whole inner part with the passed textual content.
I solved this with first cloning the <a> tag, then setting the new text content of <span> (which will remove the original <a> tag), and finally appending the cloned <a> tag to my <span>. This works, but feels such an overkill for a simple task like this. Btw. I can't guarantee that there will be an initial text node inside the span - it might be empty, just like:
<span class="target"><a class="changeme" href="#">now</a></span>
I did a jsfiddle too. So, what would be the neat way to do this?
Try something like:
$('a.changeme').on('click', function() {
$(this).closest('.target').contents().not(this).eq(0).replaceWith('Do it again ');
});
demo: http://jsfiddle.net/eEMGz/
ref: http://api.jquery.com/contents/
Update:
I guess I read your question wrong, and you're trying to replace the text if it's already there and inject it otherwise. For this, try:
$('a.changeme').on('click', function() {
var
$tmp = $(this).closest('.target').contents().not(this).eq(0),
dia = document.createTextNode('Do it again ');
$tmp.length > 0 ? $tmp.replaceWith(dia) : $(dia).insertBefore(this);
});
​Demo: http://jsfiddle.net/eEMGz/3/
You can use .contents():
//set the new text to replace the old text
var newText = 'New Text';
//bind `click` event handler to the `.changeme` elements
$('.changeme').on('click', function () {
//iterate over the nodes in this `<span>` element
$.each($(this).parent().contents(), function () {
//if the type of this node is undefined then it's a text node and we want to replace it
if (typeof this.tagName == 'undefined') {
//to replace the node we can use `.replaceWith()`
$(this).replaceWith(newText);
}
});
});​
Here is a demo: http://jsfiddle.net/jasper/PURHA/1/
Some docs for ya:
.contents(): http://api.jquery.com/contents
.replaceWith(): http://api.jquery.com/replacewith
typeof: https://developer.mozilla.org/en/JavaScript/Reference/Operators/typeof
Update
var newText = 'New Text';
$('a').on('click', function () {
$.each($(this).parent().contents(), function () {
if (typeof this.tagName == 'undefined') {
//instead of replacing this node with the replacement string, just replace it with a blank string
$(this).replaceWith('');
}
});
//then add the replacement string to the `<span>` element regardless of it's initial state
$(this).parent().prepend(newText);
});​
Demo: http://jsfiddle.net/jasper/PURHA/2/
You can try this.
var $textNode, $parent;
$('.changeme').on('click', function(){
$parent = $(this).parent();
$textNode= $parent.contents().filter(function() {
return this.nodeType == 3;
});
if($textNode.length){
$textNode.replaceWith('Content changed')
}
else{
$parent.prepend('New content');
}
});
Working demo - http://jsfiddle.net/ShankarSangoli/yx5Ju/8/
You step out of jQuery because it doesn't help you to deal with text nodes. The following will remove the first child of every <span> element with class "target" if and only if it exists and is a text node.
Demo: http://jsfiddle.net/yx5Ju/11/
Code:
$('span.target').each(function() {
var firstChild = this.firstChild;
if (firstChild && firstChild.nodeType == 3) {
firstChild.data = "Do it again";
}
});
This is not a perfect example I guess, but you could use contents function.
console.log($("span.target").contents()[0].data);
You could wrap the text into a span ... but ...
try this.
http://jsfiddle.net/Y8tMk/
$(function(){
var txt = '';
$('.target').contents().each(function(){
if(this.nodeType==3){
this.textContent = 'done ';
}
});
});
You can change the native (non-jquery) data property of the object. Updated jsfiddle here: http://jsfiddle.net/elgreg/yx5Ju/2/
Something like:
$('a.changeme3').click(function(){
$('span.target3').contents().get(0).data = 'Do it again';
});
The contents() gets the innards and the get(0) gets us back to the original element and the .data is now a reference to the native js textnode. (I haven't tested this cross browser.)
This jsfiddle and answer are really just an expanded explanation of the answer to this question:
Change text-nodes text
$('a.changeme').click(function() {
var firstNode= $(this).parent().contents()[0];
if( firstNode.nodeType==3){
firstNode.nodeValue='New text';
}
})
EDIT: not sure what layout rules you need, update to test only first node, otherwise adapt as needed

How do I change the CSS property "display" in javascript

How do I change the CSS property display, in JavaScript, from display:none to display:normal for these divs?
#hide_0 { display:none }
#hide_1 { display:none }
#hide_2 { display:none }
#hide_3 { display:none }
#hide_4 { display:none }
#hide_5 { display:none }
Only one at a time. I need to display one and hide the rest.
What I used:
var persistent_element='hide_1';
function link_update(link_display)
{
var local_element;
local_element=document.getElementById(persistent_element);
local_element.style.display='none';
local_element=document.getElementById(link_display);
local_element.style.display='block';
persistent_element=link_display;
}
How I connected it : m4 is a minified - connects onclick to these methods
m4('l1',function {return link_update(hide_1);});
m4('l2',function {return link_update(hide_2);});
m4('l3',function {return link_update(hide_3);});
m4('l4',function {return link_update(hide_4);});
m4('l5',function {return link_update(hide_5);});
m4('l6',function {return link_update(hide_6);});
To use javascript to change the style, you can do it like this:
// hide an element
document.getElementById("hide_0").style.display = "none";
// show a block element
document.getElementById("hide_1").style.display = "block";
// to go back to the default or CSS specified value
document.getElementById("hide_2").style.display = "";
So, if you wanted to hide all and show one, you could do that with this function:
function showOneHideOthers(base, len, numToShow) {
// objects must have ids like base_0, base_1, etc...
for (var i = 0; i < len; i++) {
if (i != numToShow) {
document.getElementById(base+i).style.display = "none";
}
}
document.getElementById(base+numToShow).style.display = "block";
}
showOneHideOther("hide_", 6, 2);
P.S. normal is not a valid value for the display property. The typical values are block, none and inline and there are others like inline-block, table, etc....
Your question is not particularly clear, but the essence of what you want to do is simple. You can get a reference to a DOM element which has an id using getElementById, and you can change the display property:
document.getElementById("hide_0").style.display = "none"; //or "block"
However, you have several element that you want to hide/show (I'm not sure when you want to do so), so it may be easier to use a different method of selecting the elements (such as getElementsByTagName, or getElementsByClassName, but it depends on your HTML and what you're actually trying to do).
You can set a css property on an element using the style method.
div.style.display = '';

How do I check if an element is hidden in jQuery?

How do I toggle the visibility of an element using .hide(), .show(), or .toggle()?
How do I test if an element is visible or hidden?
Since the question refers to a single element, this code might be more suitable:
// Checks CSS content for display:[none|block], ignores visibility:[true|false]
$(element).is(":visible");
// The same works with hidden
$(element).is(":hidden");
It is the same as twernt's suggestion, but applied to a single element; and it matches the algorithm recommended in the jQuery FAQ.
We use jQuery's is() to check the selected element with another element, selector or any jQuery object. This method traverses along the DOM elements to find a match, which satisfies the passed parameter. It will return true if there is a match, otherwise return false.
You can use the hidden selector:
// Matches all elements that are hidden
$('element:hidden')
And the visible selector:
// Matches all elements that are visible
$('element:visible')
if ( $(element).css('display') == 'none' || $(element).css("visibility") == "hidden"){
// 'element' is hidden
}
The above method does not consider the visibility of the parent. To consider the parent as well, you should use .is(":hidden") or .is(":visible").
For example,
<div id="div1" style="display:none">
<div id="div2" style="display:block">Div2</div>
</div>
The above method will consider div2 visible while :visible not. But the above might be useful in many cases, especially when you need to find if there is any error divs visible in the hidden parent because in such conditions :visible will not work.
None of these answers address what I understand to be the question, which is what I was searching for, "How do I handle items that have visibility: hidden?". Neither :visible nor :hidden will handle this, as they are both looking for display per the documentation. As far as I could determine, there is no selector to handle CSS visibility. Here is how I resolved it (standard jQuery selectors, there may be a more condensed syntax):
$(".item").each(function() {
if ($(this).css("visibility") == "hidden") {
// handle non visible state
} else {
// handle visible state
}
});
From How do I determine the state of a toggled element?
You can determine whether an element is collapsed or not by using the :visible and :hidden selectors.
var isVisible = $('#myDiv').is(':visible');
var isHidden = $('#myDiv').is(':hidden');
If you're simply acting on an element based on its visibility, you can just include :visible or :hidden in the selector expression. For example:
$('#myDiv:visible').animate({left: '+=200px'}, 'slow');
Often when checking if something is visible or not, you are going to go right ahead immediately and do something else with it. jQuery chaining makes this easy.
So if you have a selector and you want to perform some action on it only if is visible or hidden, you can use filter(":visible") or filter(":hidden") followed by chaining it with the action you want to take.
So instead of an if statement, like this:
if ($('#btnUpdate').is(":visible"))
{
$('#btnUpdate').animate({ width: "toggle" }); // Hide button
}
Or more efficient, but even uglier:
var button = $('#btnUpdate');
if (button.is(":visible"))
{
button.animate({ width: "toggle" }); // Hide button
}
You can do it all in one line:
$('#btnUpdate').filter(":visible").animate({ width: "toggle" });
The :visible selector according to the jQuery documentation:
They have a CSS display value of none.
They are form elements with type="hidden".
Their width and height are explicitly set to 0.
An ancestor element is hidden, so the element is not shown on the page.
Elements with visibility: hidden or opacity: 0 are considered to be visible, since they still consume space in the layout.
This is useful in some cases and useless in others, because if you want to check if the element is visible (display != none), ignoring the parents visibility, you will find that doing .css("display") == 'none' is not only faster, but will also return the visibility check correctly.
If you want to check visibility instead of display, you should use: .css("visibility") == "hidden".
Also take into consideration the additional jQuery notes:
Because :visible is a jQuery extension and not part of the CSS specification, queries using :visible cannot take advantage of the performance boost provided by the native DOM querySelectorAll() method. To achieve the best performance when using :visible to select elements, first select the elements using a pure CSS selector, then use .filter(":visible").
Also, if you are concerned about performance, you should check Now you see me… show/hide performance (2010-05-04). And use other methods to show and hide elements.
How element visibility and jQuery works;
An element could be hidden with display:none, visibility:hidden or opacity:0. The difference between those methods:
display:none hides the element, and it does not take up any space;
visibility:hidden hides the element, but it still takes up space in the layout;
opacity:0 hides the element as "visibility:hidden", and it still takes up space in the layout; the only difference is that opacity lets one to make an element partly transparent;
if ($('.target').is(':hidden')) {
$('.target').show();
} else {
$('.target').hide();
}
if ($('.target').is(':visible')) {
$('.target').hide();
} else {
$('.target').show();
}
if ($('.target-visibility').css('visibility') == 'hidden') {
$('.target-visibility').css({
visibility: "visible",
display: ""
});
} else {
$('.target-visibility').css({
visibility: "hidden",
display: ""
});
}
if ($('.target-visibility').css('opacity') == "0") {
$('.target-visibility').css({
opacity: "1",
display: ""
});
} else {
$('.target-visibility').css({
opacity: "0",
display: ""
});
}
Useful jQuery toggle methods:
$('.click').click(function() {
$('.target').toggle();
});
$('.click').click(function() {
$('.target').slideToggle();
});
$('.click').click(function() {
$('.target').fadeToggle();
});
This works for me, and I am using show() and hide() to make my div hidden/visible:
if( $(this).css('display') == 'none' ){
/* your code goes here */
} else {
/* alternate logic */
}
You can also do this using plain JavaScript:
function isRendered(domObj) {
if ((domObj.nodeType != 1) || (domObj == document.body)) {
return true;
}
if (domObj.currentStyle && domObj.currentStyle["display"] != "none" && domObj.currentStyle["visibility"] != "hidden") {
return isRendered(domObj.parentNode);
} else if (window.getComputedStyle) {
var cs = document.defaultView.getComputedStyle(domObj, null);
if (cs.getPropertyValue("display") != "none" && cs.getPropertyValue("visibility") != "hidden") {
return isRendered(domObj.parentNode);
}
}
return false;
}
Notes:
Works everywhere
Works for nested elements
Works for CSS and inline styles
Doesn't require a framework
I would use CSS class .hide { display: none!important; }.
For hiding/showing, I call .addClass("hide")/.removeClass("hide"). For checking visibility, I use .hasClass("hide").
It's a simple and clear way to check/hide/show elements, if you don't plan to use .toggle() or .animate() methods.
Demo Link
$('#clickme').click(function() {
$('#book').toggle('slow', function() {
// Animation complete.
alert($('#book').is(":visible")); //<--- TRUE if Visible False if Hidden
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="clickme">
Click here
</div>
<img id="book" src="https://upload.wikimedia.org/wikipedia/commons/8/87/Google_Chrome_icon_%282011%29.png" alt="" width="300"/>
Source (from my blog):
Blogger Plug n Play - jQuery Tools and Widgets: How to See if Element is hidden or Visible Using jQuery
ebdiv should be set to style="display:none;". It works for both show and hide:
$(document).ready(function(){
$("#eb").click(function(){
$("#ebdiv").toggle();
});
});
One can simply use the hidden or visible attribute, like:
$('element:hidden')
$('element:visible')
Or you can simplify the same with is as follows.
$(element).is(":visible")
Another answer you should put into consideration is if you are hiding an element, you should use jQuery, but instead of actually hiding it, you remove the whole element, but you copy its HTML content and the tag itself into a jQuery variable, and then all you need to do is test if there is such a tag on the screen, using the normal if (!$('#thetagname').length).
When testing an element against :hidden selector in jQuery it should be considered that an absolute positioned element may be recognized as hidden although their child elements are visible.
This seems somewhat counter-intuitive in the first place – though having a closer look at the jQuery documentation gives the relevant information:
Elements can be considered hidden for several reasons: [...] Their width and height are explicitly set to 0. [...]
So this actually makes sense in regards to the box-model and the computed style for the element. Even if width and height are not set explicitly to 0 they may be set implicitly.
Have a look at the following example:
console.log($('.foo').is(':hidden')); // true
console.log($('.bar').is(':hidden')); // false
.foo {
position: absolute;
left: 10px;
top: 10px;
background: #ff0000;
}
.bar {
position: absolute;
left: 10px;
top: 10px;
width: 20px;
height: 20px;
background: #0000ff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="foo">
<div class="bar"></div>
</div>
Update for jQuery 3.x:
With jQuery 3 the described behavior will change! Elements will be considered visible if they have any layout boxes, including those of zero width and/or height.
JSFiddle with jQuery 3.0.0-alpha1:
http://jsfiddle.net/pM2q3/7/
The same JavaScript code will then have this output:
console.log($('.foo').is(':hidden')); // false
console.log($('.bar').is(':hidden')); // false
expect($("#message_div").css("display")).toBe("none");
$(document).ready(function() {
if ($("#checkme:hidden").length) {
console.log('Hidden');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="checkme" class="product" style="display:none">
<span class="itemlist"><!-- Shows Results for Fish --></span> Category:Fish
<br>Product: Salmon Atlantic
<br>Specie: Salmo salar
<br>Form: Steaks
</div>
To check if it is not visible I use !:
if ( !$('#book').is(':visible')) {
alert('#book is not visible')
}
Or the following is also the sam, saving the jQuery selector in a variable to have better performance when you need it multiple times:
var $book = $('#book')
if(!$book.is(':visible')) {
alert('#book is not visible')
}
Use class toggling, not style editing . . .
Using classes designated for "hiding" elements is easy and also one of the most efficient methods. Toggling a class 'hidden' with a Display style of 'none' will perform faster than editing that style directly. I explained some of this pretty thoroughly in Stack Overflow question Turning two elements visible/hidden in the same div.
JavaScript Best Practices and Optimization
Here is a truly enlightening video of a Google Tech Talk by Google front-end engineer Nicholas Zakas:
Speed Up Your Javascript (YouTube)
After all, none of examples suits me, so I wrote my own.
Tests (no support of Internet Explorer filter:alpha):
a) Check if the document is not hidden
b) Check if an element has zero width / height / opacity or display:none / visibility:hidden in inline styles
c) Check if the center (also because it is faster than testing every pixel / corner) of element is not hidden by other element (and all ancestors, example: overflow:hidden / scroll / one element over another) or screen edges
d) Check if an element has zero width / height / opacity or display:none / visibility:hidden in computed styles (among all ancestors)
Tested on
Android 4.4 (Native browser/Chrome/Firefox), Firefox (Windows/Mac), Chrome (Windows/Mac), Opera (Windows Presto/Mac WebKit), Internet Explorer (Internet Explorer 5-11 document modes + Internet Explorer 8 on a virtual machine), and Safari (Windows/Mac/iOS).
var is_visible = (function () {
var x = window.pageXOffset ? window.pageXOffset + window.innerWidth - 1 : 0,
y = window.pageYOffset ? window.pageYOffset + window.innerHeight - 1 : 0,
relative = !!((!x && !y) || !document.elementFromPoint(x, y));
function inside(child, parent) {
while(child){
if (child === parent) return true;
child = child.parentNode;
}
return false;
};
return function (elem) {
if (
document.hidden ||
elem.offsetWidth==0 ||
elem.offsetHeight==0 ||
elem.style.visibility=='hidden' ||
elem.style.display=='none' ||
elem.style.opacity===0
) return false;
var rect = elem.getBoundingClientRect();
if (relative) {
if (!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2, rect.top + elem.offsetHeight/2),elem)) return false;
} else if (
!inside(document.elementFromPoint(rect.left + elem.offsetWidth/2 + window.pageXOffset, rect.top + elem.offsetHeight/2 + window.pageYOffset), elem) ||
(
rect.top + elem.offsetHeight/2 < 0 ||
rect.left + elem.offsetWidth/2 < 0 ||
rect.bottom - elem.offsetHeight/2 > (window.innerHeight || document.documentElement.clientHeight) ||
rect.right - elem.offsetWidth/2 > (window.innerWidth || document.documentElement.clientWidth)
)
) return false;
if (window.getComputedStyle || elem.currentStyle) {
var el = elem,
comp = null;
while (el) {
if (el === document) {break;} else if(!el.parentNode) return false;
comp = window.getComputedStyle ? window.getComputedStyle(el, null) : el.currentStyle;
if (comp && (comp.visibility=='hidden' || comp.display == 'none' || (typeof comp.opacity !=='undefined' && comp.opacity != 1))) return false;
el = el.parentNode;
}
}
return true;
}
})();
How to use:
is_visible(elem) // boolean
Example of using the visible check for adblocker is activated:
$(document).ready(function(){
if(!$("#ablockercheck").is(":visible"))
$("#ablockermsg").text("Please disable adblocker.").show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ad-placement" id="ablockercheck"></div>
<div id="ablockermsg" style="display: none"></div>
"ablockercheck" is a ID which adblocker blocks. So checking it if it is visible you are able to detect if adblocker is turned On.
$(document).ready(function() {
var visible = $('#tElement').is(':visible');
if(visible) {
alert("visible");
// Code
}
else
{
alert("hidden");
}
});
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<input type="text" id="tElement" style="display:block;">Firstname</input>
You need to check both... Display as well as visibility:
if ($(this).css("display") == "none" || $(this).css("visibility") == "hidden") {
// The element is not visible
} else {
// The element is visible
}
If we check for $(this).is(":visible"), jQuery checks for both the things automatically.
Simply check visibility by checking for a boolean value, like:
if (this.hidden === false) {
// Your code
}
I used this code for each function. Otherwise you can use is(':visible') for checking the visibility of an element.
Because Elements with visibility: hidden or opacity: 0 are considered visible, since they still consume space in the layout (as described for jQuery :visible Selector) - we can check if element is really visible in this way:
function isElementReallyHidden (el) {
return $(el).is(":hidden") || $(el).css("visibility") == "hidden" || $(el).css('opacity') == 0;
}
var booElementReallyShowed = !isElementReallyHidden(someEl);
$(someEl).parents().each(function () {
if (isElementReallyHidden(this)) {
booElementReallyShowed = false;
}
});
But what if the element's CSS is like the following?
.element{
position: absolute;left:-9999;
}
So this answer to Stack Overflow question How to check if an element is off-screen should also be considered.
A function can be created in order to check for visibility/display attributes in order to gauge whether the element is shown in the UI or not.
function checkUIElementVisible(element) {
return ((element.css('display') !== 'none') && (element.css('visibility') !== 'hidden'));
}
Working Fiddle
Also here's a ternary conditional expression to check the state of the element and then to toggle it:
$('someElement').on('click', function(){ $('elementToToggle').is(':visible') ? $('elementToToggle').hide('slow') : $('elementToToggle').show('slow'); });
if($('#postcode_div').is(':visible')) {
if($('#postcode_text').val()=='') {
$('#spanPost').text('\u00a0');
} else {
$('#spanPost').text($('#postcode_text').val());
}

Categories