Skip to main content
Participating Frequently
July 9, 2018
Answered

Show/Hide Div with JavaScript [or CSS]

  • July 9, 2018
  • 5 replies
  • 14270 views

Hello,

I am having trouble getting my code to work correctly. I want to show content based on what the person clicks. I know it's probably better to write in a switch statement, but I wanted to figure it out with and if/else statement first. Could someone please tell me what I am doing wrong.

HTML

<section class="fullLength">

    <nav class ="subjectBar">

  <ul>

  <button onclick="alertName(this)" class="subjectList" id="Reading">Reading</button>

  <button onclick="alertName(this)" class="subjectListMath" id="Math">Math</button>

  <button onclick="alertName(this)" class="subjectListScience" id="Science">Science</button>

  <button onclick="alertName(this)" class="subjectListEnglish" id="English">English</button>

  <button onclick="alertName(this)" class="subjectListHomework" id="Homework">Homework</button>

  <button onclick="alertName(this)" class="subjectListStudySkills" id="Skills">Study Skillls</button>

  <button onclick="alertName(this)" class="subjectListSummerCamps" id="Camps">Summer Camps</button>

  </ul>

  </nav>

  </section>

<section class="hidingsection">

  <div class = "readingContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  <div id = "mathContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  <div id = "scienceContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  <div id = "englishContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  <div id = "homeworkContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  <div id = "skillsContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  <div id = "campsContent">

  <h1 class ="Title"></h1>

  <p class ="Text"></p>

  </div>

  </section>

JAVASCRIPT

<script>

  function alertName(a)

  {

  if(a.id == 'Reading')

  {

  var x = document.getElementsByClassName('readingContent');

  if (x.style.display === "none")

  {

        x.style.display = 'block';

  x.style.visibility = 'visible';

    }

  else

  {

  x.style.display = 'none';

  x.style.visibility = 'hidden'

  }

  }

  else

  {

  alert(a);

  }

CSS

.readingContent{

    display: none;

  visibility: hidden;

}

This topic has been closed for replies.
Correct answer Nancy OShea

pziecina​ I am very interested in seeing how you would solve my problem with html/css. Please give me your reasoning on why you would do it that way instead of using Javascript.


Pure CSS & HTML will work for everyone.  But a lot of people use script blockers for security reasons.  For those people, JS links will not work.

Below is a pure CSS & HTML approach (tested in latest Firefox & Chrome).

<!doctype html>

<html lang="en">

<head>

<meta charset="utf-8">

<title>Show/Hide with CSS</title>

<meta name="viewport" content="width=device-width, initial-scale=1">

<meta http-equiv="X-UA-Compatible" content="IE=edge">

<style>

/**basic page styles**/

body {

    font-family: Baskerville, "Palatino Linotype", Palatino, "Century Schoolbook L", "Times New Roman", "serif"Cambria, "Hoefler Text", "Liberation Serif", Times, "Times New Roman", "serif";

    font-size: 2.5vw;

    background: #CCC url(https://placeimg.com/500/500/nature) no-repeat center center;

    background-size: cover;

}

.container {

    width: 80%;

    border-radius: 10%;

    margin: 0 auto;

    padding: 2%;

    background: rgba(255,255,255,0.7);

    text-align:center;

}

img {

    max-width: 100%;

    margin: 0 auto;

    vertical-align: baseline;

    display: block

}

/**show/hide with CSS**/

div#tabs p {display:none;}

div#tabs p.tab1:target,

div#tabs p.tab2:target,

div#tabs p.tab3:target {display:block;}

</style>

</head>

<body>

<div class="container">

<h1>My Awesome Website</h1>

<hr>

<div id='tabs'>

<h2 class="nav-tab-wrapper">

<a href="#tab1" class="nav-tab tab1">TAB 1</a> |

<a href="#tab2" class="nav-tab nav-tab-active tab2">TAB 2</a> |

<a href="#tab3" class="nav-tab tab3">TAB 3</a></h2>

<!--Tab content-->

<p id='tab1' class='tab1'>Tab 1 stuff goes here... <img src="https://placeimg.com/400/300/nature" alt="placholder"> </p>

<p id='tab2' class='tab2'>Tab2 stuff <img src="https://placeimg.com/400/300/arch" alt="placholder"></p>

<p id='tab3' class='tab3'>Tab3 stuff <img src="https://placeimg.com/400/300/animals" alt="placholder"></p>

<!--/tabs--></div>

<!--/container--></div>

</body>

</html>

5 replies

TheBCMan
Participating Frequently
July 10, 2018

Ok going the other way... an "optimized" take on the question. Running example: Edit fiddle - JSFiddle

JavaScript:

init=function(){

     $('[buttonlist] button').click(function(){                              // bind to button clicks

          var pressed = $(this).html().toLowerCase().replace(/\s/g, '');     // what was pressed?

          $( '.readingContent div' ).hide();                                 // hide all elements again

          $( '.readingContent, div[data=' + pressed + ']' ).show();          // show the main element (again) and the element pressed

     })

};

$(document).ready(function(){ init(); });

CSS:

.readingContent, .readingContent div{                         /* hide all entire block and the elements initially */

     display: none;

}

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>

<section class="fullLength">

     <nav class="subjectBar">

          <ul buttonlist>

               <button>Reading</button>

               <button>Math</button>

               <button>Science</button>

               <button>English</button>

               <button>Homework</button>

               <button>Study Skills</button>

               <button>Summer Camps</button>

          </ul>

     </nav>

</section>

<section class="readingContent">

     <div data="reading">

          <h1>Reading</h1>

          <p></p>

     </div>

     <div data="math">

          <h1>Math</h1>

          <p></p>

     </div>

     <div data="science">

          <h1>Science</h1>

          <p></p>

     </div>

     <div data="english">

          <h1>English</h1>

          <p></p>

     </div>

     <div data="homework">

          <h1>Homework</h1>

          <p></p>

     </div>

     <div data="studyskills">

          <h1>Study Skills</h1>

          <p></p>

     </div>

     <div data="summercamps">

          <h1>Summer Camps</h1>

          <p></p>

     </div>

</section>

You don't need to complicate HTML code with classes, just use attributes and child html elements to refer to them. You can bind JavaScript events the same was CSS is applied to large sections of code.

Brainiac
July 10, 2018

Thanks for posting your version. The more code contributions, which show optional ways of acheiving the same result, the better. We can all learn and expand our knowledge.

Nancy OShea
Adobe Expert
July 10, 2018

Perhaps a bit too much information for the OP .

Nancy O'Shea— Product User, Community Expert &amp; Moderator
Nancy OShea
Adobe Expert
July 9, 2018

Is this a learning exercise or a real project?

I ask because you can easily toggle content with Bootstrap classes and a data-target.

https://getbootstrap.com/docs/4.0/components/collapse/

Nancy O'Shea— Product User, Community Expert &amp; Moderator
WolfShade
Brainiac
July 9, 2018

If you use something like Bootstrap, you can do this without JavaScript.

V/r,

^ _ ^

Brainiac
July 9, 2018

Bootstrap uses javascript, the jQuery library - you could use one of the default options which ships with it to show an element but nothing like rolling your own if you want to grasp how the code functions really work, rather than stumbling along  using a front end framework and not understanding what is happening and why, that just leads you to not really wanting to explore beyond a very small world.

If you ever need to write some besoke app or solution, which a good deal of websites are starting to deploy, Bootstrap isnt going to help you much, it could infact be working against you, isolating you to a small selection of options and no incentive to wander beyond what it offers.......until.....

pziecina
Brainiac
July 9, 2018

If you are using flexbox, you could also just use 'visibility: collapse;' which was included as part of the flexbox specs -

see section 4.4 in https://www.w3.org/TR/2017/CR-css-flexbox-1-20171019/

TheBCMan
Participating Frequently
July 9, 2018

You are missing the closing bracket on your first if statement

<script>

     function alertName(a){

          if(a.id == 'Reading'){

               var x = document.getElementsByClassName('readingContent');

               if (x.style.display === "none"){

                    x.style.display = 'block';

                    x.style.visibility = 'visible';

               } else {

                    x.style.display = 'none';

                    x.style.visibility = 'hidden'

               };

          } else {

               alert(a);

          }; // you are missing this closing bracket

     }

</script>

Brainiac
July 9, 2018

TheBCMan  wrote

You are missing the closing bracket on your first if statement

<script>      function alertName(a){           if(a.id == 'Reading'){                var x = document.getElementsByClassName('readingContent');                if (x.style.display === "none"){                     x.style.display = 'block';                     x.style.visibility = 'visible';                } else {                     x.style.display = 'none';                     x.style.visibility = 'hidden'                };           } else {                alert(a);           }; // you are missing this closing bracket      } </script>

That's really not an efficient way of doing what needs to be achieved because you are requesting each 'id' individually.....so end up with more code than is strictly required.

Using a class name and looping through the code, attaching an event listener is a more economical approach.

TheBCMan
Participating Frequently
July 10, 2018

TheBCMan  wrote

@osgood_ : Of course it's not the best way to do it, but read his question, he wants to know / learn what is wrong, not someone show him how to do it I could have rewritten the code in 2-3 lines of jQuery with the toggle function but I choose to answer his question

The problem with this forum, is that we have to work out if the poster just wants their question answered, or if they wish to know not just how to do do something using what they have posted, but alternate methods.

At the same time this post was being answered, another post was asking why a Dw behaviour was crashing Dw, and the poster marked their answer correct which was an alternative way to do what they wished, not an answer though that fixed the problem.

Most of us could have given a better method of doing what that poster wanted than using Dw js behaviours, but that was I thought not what the user was asking. In this post however, the user asked how to do a show/hide behaviour, (using js). That left the possible answers open to each individual replying, some choosing js/jQuery and myself suggesting that html/css alone could be used if the poster was interested. As the poster did not reply to my post(s) I did not post my solution.

Web development is no longer restricted to only using js to do such things as show/hide content, and that applies to many things that where once the domain of having to use js. For this forum, we try to take into account that many poster may not know what html/css and even js is capable of now, and suggesting alternative methods has become part of answering users questions.


You are literally blasting me for answering his question of "could someone please tell me what I am doing wrong" ... using his code?

Brainiac
July 9, 2018

I can do it in jQuery, a javascript library, if you can use that, see code below:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Show Hide Containers</title>

<style>

.hide {

display: none;

}

</style>

<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="

crossorigin="anonymous"></script>

<script>

$(document).ready(function(){

$('.alertName').css('cursor' , 'pointer').click(function(){

let name = $(this).attr('name');

$('.hide').hide();

$('.' + name).show();

});

});

</script>

</head>

<body>

<nav class ="subjectBar">

<button  class="alertName subjectList" name="readingContent">Reading</button>

<button  class="alertName subjectListMath" name="mathContent">Math</button>

<button  class="alertName subjectListScience" name="scienceContent">Science</button>

<button  class="alertName subjectListEnglish" name="englishContent">English</button>

<button  class="alertName subjectListHomework" name="homeworkContent">Homework</button>

<button  class="alertName subjectListStudySkills" name="skillsContent">Study Skillls</button>

<button  class="alertName subjectListSummerCamps" name="campsContent">Summer Camps</button>

</nav>

<section class="hidingsection">

<div class="hide readingContent">

<h1 class ="Title">Reading Content</h1>

<p class ="Text">Reading Text</p>

</div>

<div class="hide mathContent">

<h1 class ="Title">Math Content</h1>

<p class ="Text">Math Text</p>

</div>

<div class="hide scienceContent">

<h1 class ="Title">Science Content</h1>

<p class ="Text">Science Text</p>

</div>

<div class="hide englishContent">

<h1 class ="Title">English Content</h1>

<p class ="Text">English Text</p>

</div>

<div class="hide homeworkContent">

<h1 class ="Title">Homework Content</h1>

<p class ="Text">Homework Text</p>

</div>

<div class="hide skillsContent">

<h1 class ="Title">Skills Content</h1>

<p class ="Text">Skills Text</p>

</div>

<div class="hide campsContent">

<h1 class ="Title">Camps Content</h1>

<p class ="Text">Camps Text</p>

</div>

</section>

</body>

</html>

Brainiac
July 9, 2018

See jQuery solution above BUT if you do want to do this with vanilla javascript, see code below:

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<title>Show Hide Containers</title>

<style>

.hide {

display: none;

}

</style>

</head>

<body>

<nav class ="subjectBar">

<button  class="alertName" name="readingContent">Reading</button>

<button  class="alertName" name="mathContent">Math</button>

<button  class="alertName" name="scienceContent">Science</button>

<button  class="alertName" name="englishContent">English</button>

<button  class="alertName" name="homeworkContent">Homework</button>

<button  class="alertName" name="skillsContent">Study Skillls</button>

<button  class="alertName" name="campsContent">Summer Camps</button>

</nav>

<section class="hidingsection">

<div class="hide readingContent">

<h1 class ="Title">Reading Content</h1>

<p class ="Text">Reading Text</p>

</div>

<div class="hide mathContent">

<h1 class ="Title">Math Content</h1>

<p class ="Text">Math Text</p>

</div>

<div class="hide scienceContent">

<h1 class ="Title">Science Content</h1>

<p class ="Text">Science Text</p>

</div>

<div class="hide englishContent">

<h1 class ="Title">English Content</h1>

<p class ="Text">English Text</p>

</div>

<div class="hide homeworkContent">

<h1 class ="Title">Homework Content</h1>

<p class ="Text">Homework Text</p>

</div>

<div class="hide skillsContent">

<h1 class ="Title">Skills Content</h1>

<p class ="Text">Skills Text</p>

</div>

<div class="hide campsContent">

<h1 class ="Title">Camps Content</h1>

<p class ="Text">Camps Text</p>

</div>

</section>

</body>

</html>

<script>

var alertName = document.getElementsByClassName("alertName");

var myFunction = function() {

var hide = document.getElementsByClassName("hide");

for (var i = 0; i < hide.length; i++) {

hide.style.display = "none";

}

var name = this.getAttribute("name");

var show = document.querySelector('.' + name);

if (show.style.display = "none") {

show.style.display = "block";

}

else {

show.style.display = "none";

}

};

for (var i = 0; i < alertName.length; i++) {

alertName.addEventListener('click', myFunction);

}

</script>

kingpat27Author
Participating Frequently
July 10, 2018

Thank you Osgood​, but why doesnt the reading button work? The code seems to seems to be the same.