Delal
Delal

Reputation: 131

Hide and Show using DOM

I'm trying to make a easy hide and show script that is separated from the HTML-code. But I can't get it to work. Anyone? HTML:

    <body>
        <div id="area">
            <h1>JavaScript</h1>
            <button class="button">Click!</button>
            <p class="text">Adöfkljg ldjfögj jsdflkgjh kjddflkgjh dfgkjdöjg </p>
            <button class="button">Click!!</button>
            <p class="text">dfghödifgjöoeirugeöori dijfoidj oidoi odi!</p>
        </div>
        <script src="visa.js"></script>
    </body>

JS:

var text = document.getElementsByClassName("text");
var butt = document.getElementsByClassName("button");

window.onload = start();
function start(){
    for (i=0; i<text.length; i++){
        text[i].style.visibility = "hidden";
    };

};

butt[i].onclick = function (){
        if (text[i].style.visibility = "hidden"){
            text[i].style.visibility = "visible";
        }else{
            text[i].style.visibility = "hidden"
        };

    };

Fiddle: http://jsfiddle.net/ZskCk/

Upvotes: 0

Views: 111

Answers (2)

Shay Elkayam
Shay Elkayam

Reputation: 4158

There are a few issues with your code:

  1. if (text[i].style.visibility = "hidden") is always true, it should be:

    if (text[i].style.visibility == "hidden")

  2. The following code:

    butt[i].onclick = function (){
      if (text[i].style.visibility = "hidden"){
        text[i].style.visibility = "visible";
      } else {
        text[i].style.visibility = "hidden"
      };
    };
    

was out of the for loop, so i was not defined, and also when you go into the function (in the future with a click) i will not be defined. So, I moved the event listener to the button declaration.

I've fixed the problems and updated your fiddle

basically, you can take a look and compare the new code with your original.

Upvotes: 2

lukaszfiszer
lukaszfiszer

Reputation: 2631

It seems that you're beginning coding in Javascript and HTML. In this case, I'd recommend you to have a look at jQuery as a solid framework for DOM manipulation. To answer your question using jQuery:

$(function(){
    $('.text').hide();    
    $('button').click(function(){
        $(this).next('.text').toggle()
    });
});

Working jsfiddle: http://jsfiddle.net/yLju5/1/

Upvotes: -1

Related Questions