Question

I have 4 <div>s in my code. I used JavaScript to show and hide them. Now it's getting hard to manage, thus I need to detect if a particular <div> is shown or hidden. I'm unsure on how to do this, which way would one code this? JQuery or Jqtouch can be good. thanks

Était-ce utile?

La solution

Depends on how the divs are hidden exactly but you can probably use

if(document.getElementById("myDiv").style.display=="none"){
    //do something
}

Autres conseils

If you can use jQuery to help you, you can use:

$( "yourDivSelector" ).is( ":visible" );

Without jQuery, you can do:

alert( isVisible( "divOne" ) );
alert( isVisible( "divTwo" ) );
alert( isVisible( "divThree" ) );

function isVisible( elementId ) {
    var element = document.getElementById( elementId );
    return window.getComputedStyle( element, null ).display != "none";
}

jsFiddle: http://jsfiddle.net/davidbuzatto/N3wf6/

More about window.getComputedStyle here: https://developer.mozilla.org/en-US/docs/DOM/window.getComputedStyle

This function seems to do what you want. It checks for display none and visibility hidden.

JavaScript Function Checks For DOM Element Visibility

function isVisible(obj)
{
    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) {
        var style = window.getComputedStyle(obj, "")
        if (style.display == 'none') return false
        if (style.visibility == 'hidden') return false
    }

    //Or get the computed style using IE's silly proprietary way
    var style = obj.currentStyle
    if (style) {
        if (style['display'] == 'none') return false
        if (style['visibility'] == 'hidden') return false
    }

    return isVisible(obj.parentNode)
}

Example Usage

if (isVisible(document.getElementById("myelement"))) {
    // Element is visible.
}

Demo

As im not sure 100% what your doing the hiding /showing...

but if your setting an attribute e.g. display

then..

function elementhidden()
{
    1. Get your element
    2. Check the elemnet atrribute status
    3. If its hide value then return true
    4. If its show value then return false

}

Provide an example of what your doing so i can make code..

You could use document.elementFromPoint(x, y) passing as x and y the position of your div and check it's the good object.

This supposes there is no other element covering the top-left point of your div.

And this may depend of what you mean by "visible" : "entirely visible" ? "at least a little visible" ? What about portions of the viewport that aren't visible due to scroll position ? And if the browser window is partially outside the screen (this could be tricky) ?

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top