简体   繁体   中英

toggle div to show hide

I have a simple block of code to hide/show two divs. It works great, the only issue I have is that I need to return the display value to the #MSOZoneCell_WebPartWPQ2 back to table. I have set it to none in the css initially. The last line doesn't seem to take effect.

here is the code:

$(function() {
$('#swap').click(function() {

    $('#MSOZoneCell_WebPartWPQ2').toggle();
    $('#example_wrapper').toggle();
    $('#MSOZoneCell_WebPartWPQ').css('display') == 'table';
});
});

You're using == operator

Try this:

$(document).ready(function(){
    $('#swap').click(function() {
        $('#MSOZoneCell_WebPartWPQ2').toggle();
        $('#example_wrapper').toggle();
        $('#MSOZoneCell_WebPartWPQ').attr('style','display:table;');
    });
});

you are sure you need "==" to set the value? or one "="

Firstly == is an equality check. You should use = to set a value.

Secondly, the css() method setter accepts two parameters. The rule to set and the value itself. Try this:

$('#MSOZoneCell_WebPartWPQ').css('display', 'table');

you should use .css( propertyName, value )

Set one or more CSS properties for the set of matched elements.

so your last line should be

$('#MSOZoneCell_WebPartWPQ').css('display', 'table');

when you call .css( propertyName )

$('#MSOZoneCell_WebPartWPQ').css('display);

you are Getting the value of said property not setting it

Get the computed style properties for the first element in the set of matched elements.


Update 1:

please note that Jquery's .show(), .hide() and .toggle() will only work with elements with block display property.

so one way to avoid changing the display property back and forth is to wrap the wanted elements in a div (container) and .toggle() it.

I have created a JSFiddle , I warped each div in a container div with a calss called "toggle" and set initial display value of one of them to "none" using style attribute.

<div class="toggle" style="display:none">

now I toggle between them using this

$('.toggle').toggle();

Update 2:

you can also use .toggleClass() here's another JSFiddle

Add this to your CSS

#example_wrapper.hiddenDiv, #MSOZoneCell_WebPartWPQ2.hiddenDiv {
  display: none;
}

add a class to the div you want initially hidden

<div id="MSOZoneCell_WebPartWPQ2" class="hiddenDiv">

toggle the class using this

$(function() {
$('#swap').click(function() {
    $('#MSOZoneCell_WebPartWPQ2').toggleClass("hiddenDiv");
    $('#example_wrapper').toggleClass("hiddenDiv");
});
});

in this example I'm using a class called "hiddenDiv", if you change it make sure the class name is the same in CSS, HTML and JS.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM