1

I have this div that I have created. I want it to expand when a link is clicked and collapse when it is clicked again. It seems to expand the div correctly but does not collapse it. Please help

<script>

        function setDisplay()
        {
            document.getElementById('divCollapse').style.display="none";
        }

        function expandSelected()
        {
            if(document.getElementById('divCollapse').style.display="none")
            {document.getElementById('divCollapse').style.display="block";}

            else if(document.getElementById('divCollapse').style.display="block")
            {document.getElementById('divCollapse').style.display="none";}

        }
    </script>
j08691
  • 204,283
  • 31
  • 260
  • 272

2 Answers2

4

you need to use == for the comparisons in your if/else if blocks. right now you are using = which is setting the display, not checking it.

<script>

    function setDisplay()
    {
        document.getElementById('divCollapse').style.display="none";
    }

    function expandSelected()
    {
        if(document.getElementById('divCollapse').style.display=="none")
        {document.getElementById('divCollapse').style.display="block";}

        else if(document.getElementById('divCollapse').style.display=="block")
        {document.getElementById('divCollapse').style.display="none";}

    }
</script>
celeriko
  • 1,564
  • 1
  • 13
  • 26
  • Thank so much! It works like a charm! can you also plese comment on how could I add a transition to the same code so it expands in a more graceful way, rather than abruptly? – user3542962 Apr 21 '14 at 15:40
  • your welcome, adding a transition is out of the scope of this question, but it will probably be easiest to use CSS3 transitions on the `height` of the div. check out [this question](http://stackoverflow.com/questions/3331353/transitions-on-the-display-property) and [this reference](https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions) to learn more about CSS3 transistions, if you are still having issues id suggest to ask another question with your updated code and any errors/issues you are getting with the transitions. – celeriko Apr 21 '14 at 16:08
3

= is an assignment operator.

Use == for comparing values.

So Try

function expandSelected() {
   if(document.getElementById('divCollapse').style.display == "none") { // See here
      document.getElementById('divCollapse').style.display = "block";
   } else if(document.getElementById('divCollapse').style.display == "block") { // See here
      document.getElementById('divCollapse').style.display = "none";
   }

}

Have a look at comparison operators.

Dhaval Marthak
  • 17,246
  • 6
  • 46
  • 68