Skip to main content
Participating Frequently
July 9, 2018
Answered

Show/Hide Div with JavaScript [or CSS]

  • July 9, 2018
  • 5 replies
  • 14476 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.

Legend
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
Community Expert
Community Expert
July 10, 2018

Perhaps a bit too much information for the OP .

Nancy O'Shea— Product User & Community Expert
Nancy OShea
Community Expert
Community 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
WolfShade
Legend
July 9, 2018

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

V/r,

^ _ ^

Legend
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
Legend
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>

Legend
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.

pziecina
Legend
July 15, 2018

pziecina  wrote

If someone can do what they want using just html and css, (or just html) I don't think it is such a bad thing.

Not bad at all..........Im just wondering how far they will get without having to involve some kind of dynamic requirement, which css/html alone is quite limited in providing. I guess we have things like the html5 'required' tag now etc for form validation but its not exactly pretty, just gets the basic job done....so if you just want to get the job done I guess css/html gets you a lot further than it used to.

I guess you can produce some kind of dynamic image gallery modal and slideshow with just html/css alone, I dont know never investiagted it and a drop menu onclick....so for most websites you can probably achieve what its required. But as far as I know css isnt much good at getting values and doing maths etc? You'd know more than me because your ethos is based around avoiding stuff like js if it can be done with css/html


What always gets me when I do something using just html and css, (show/hide, lightbox, carousel, etc)is that when I look at how to improve them, I always start by looking at javascript solutions first, and only then try to think of css solutions.

Habit, I suppose!

Maths is easy in css, css calc(), and as for variables I don't want to start that disagreement again.

The problem with css, is that unlike js or even css processors, the specs take time to produce and even longer for usable browser support to be implemented.

Legend
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>

Legend
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.