0
votes

html head:

<script type="text/javascript" language="JavaScript">

    function getStyle() {
        var temp = document.getElementById("cont").style.display;
        return temp;
    }

    function switch01() {
        var current = getStyle();
        if (current == "none") {
            document.getElementById("cont").style.display = "block";
        }
        else {
            document.getElementById("cont").style.display = "none";
        }
    }​

</script>

body:

<a href="javascript:switch01('cont')">CONTENT</a>

CSS:

#cont{
    display: none;
}

After loading the page - first click doesn't work. After the first click - everything works.
Also, How could I show/hide the div slowly (with sliding effect, not momentally) ?

4
If you want "effects" and movement, you should take a look at jQuery. - alestanis

4 Answers

5
votes

The value you get for the first time is "undefined".

You can:

1) Set the value via javascript when page loads;

document.getElementById("cont").style.display = "none";

or

2) decode "undefined" value to none, because you know that at first the value will be none;

var temp = document.getElementById("cont").style.display;
if (temp == "undefined") 
   temp = "none";
return temp;

both pretty ugly solutions, but they work.

3
votes

If it must be inline you need to do this DEMO

<a href="#" onclick="return switch01('cont')">CONTENT</a>

and this (reversing the test for none to be a test for not block)

<script type="text/javascript" language="JavaScript">
function switch01(objId) {
  var current = document.getElementById(objId).style.display;
  document.getElementById(objId).style.display=(current!="block")?"block":"none";
  return false
}
</script>

The above ANSWERS your question

UPDATE: Since it seems you would like jQuery instead, here is how you need to code that - notice the return false which Michal missed.

<a href="#" id="toggle">CONTENT</a>

$(function() { // wait for the page to load
  $('#toggle').on("click",function(e) { // when link clicked
    $('#cont').slideToggle(); // slide open or closed
    return false; // or e.preventDefault(); // stop the click executing the href
  });​
});​
2
votes

If you want the slide effect, my recommendation is using jQuery:

$('#toggle').click(function() {
    $('#cont').slideToggle();
});​

See this DEMO.

For changing the sliding speed and more information see documentation.

1
votes

For hiding the div.. you can take a look at

     $('cont').hide(); function.

More relevant Information is available here :

     http://api.jquery.com/hide/

     http://api.jquery.com/show/

And for sliding effect Jquery is top notch in this department. You just have to pass the argument as given below.. and it does the work.

     $("cont").click(function () {
         $(this).hide("slide", { direction: "down" }, 1000);
     }); 

FYI : http://docs.jquery.com/UI/Effects/Slide