programmer
programmer

Reputation: 3113

placing existing div over an existing div and then switching between them

Consider the following HTML:

<body>
    <div id="div1" onclick="toggleDivs();">
        div1 content
    </div>
    <div id="div2" onclick="toggleDivs();" style="visibility:hidden">
        div2 content
    </div>
</body>

What I want is that when the user clicks on the currently visible div, the other div will become visible and the current div will become hidden.

I tried using jquery.toggle() and jquery.css("visibility":"hidden/visible") but none of those techniques worked.

Upvotes: 2

Views: 805

Answers (3)

lucuma
lucuma

Reputation: 18339

A much simpler z-index solution is to just subtract 1 from the visible z-index. You just need to put the div's on the page in reverse order.

$('.cycle').click(function() {
    $(this).css('z-index', $(this).css('z-index')-1);
});
​

JSFiddle: http://jsfiddle.net/lucuma/jr7tR/3/

Upvotes: 1

FishBasketGordo
FishBasketGordo

Reputation: 23142

toggle[API Ref] will work, but it operates on the display CSS attribute, not visibility. Just use display instead:

<div id="div1" onclick="toggleDivs();">
    div1 content
</div>
<div id="div2" onclick="toggleDivs();" style="display: none;">
    div2 content
</div>​

And the script:

function toggleDivs() {
    $('#div1, #div2').toggle();
}​

Here's a working example.


Addendum:

I don't care for this solution compared to the previous one as much, but if, as per the OP's comment below, you wanted to accomplish this task using the z-index, you could do it like this:

HTML:

<div id="div1" class="cycle">
    div1 content
</div>
<div id="div2" class="cycle">
    div2 content
</div>

CSS:

.cycle {
    position: absolute; /* The important thing is that the element 
                           is taken out of the document flow */
    background: #fff;
    width: 100px;
    height: 20px;
    border: solid 1px #000;
}​

JavaScript:

$(function() {
   var cycleClick = function(e) {
        var $cycle = $('.cycle');
        $cycle.each(function() {
            var $this = $(this);
            var newZIndex = ($this.css('z-index') + 1) % $cycle.length;
            $this.css('z-index', newZIndex);
        });
        return false;
    };

    $('.cycle').click(cycleClick).each(function(idx) {
        $(this).css('z-index', idx);
    });​
});

Upvotes: 5

slapthelownote
slapthelownote

Reputation: 4279

Here's a jsfiddle that works:

http://jsfiddle.net/g5chb/1/

Amended code below:

<body>
    <div id="div1" >
         div1 content
    </div>
    <div id="div2" style="display:none">
         div2 content
    </div>
</body>​

and the relevant jQuery:

$("div").click(function(){
  $("#div1").toggle();   
  $("#div2").toggle();                    
});

Upvotes: 3

Related Questions