Tim Marshall Tim Marshall - 3 months ago 8
CSS Question

How do I hide div id's with onclick menu without using jquery

Heres the menu:

<a href="" onclick="loadPage('page1')">Home</a>
<a href="" onclick="loadPage('page2')">About us</a>
<a href="" onclick="loadPage('page3')">Services</a>
<a href="" onclick="loadPage('page4')">Partners</a>
<a href="" onclick="loadPage('page5')">Contact us</a>


Heres the script so far:

<script>
var var1="";
function loadPage(varcontent){
var1=varcontent;
alert(var1);
elem.style.display = "none";
}
</script>


Here's the div:

<div id="page_1" class=welcome_bye_holder>
<h1 id="page_1">Welcome to Cyber Technician:</h1>
<p1 id="page_1">An I.T. Technician and cyber security<br> for the <br>Southport, North Sefton area.</p1>
</div>


Basically i want some JavaScript that if home is clicked then hide page 2, 3, 4 and 5. And so on. Don't post jquery tried that last time it simply didn't work.

Answer

Here is a working example https://jsfiddle.net/sxh0n7d1/28/

Couple problems.

First off, you should NOT use the same ID for multiple elements, you CLASS instead. In your case the parent div already is using the right ID when you display that ID to none all its children elements are gone too.

Change this: onclick="loadPage('page1')"

To this: onclick="loadPage('page_1')" notice this matches your <div id="page_1">

And this is not being used at all elem.style.display = "none";, what is elem (you never defined it) I changed it to this document.getElementById(var1).style.display = "none"; because var1 is being declared and set to the right id

Last but not least, I added a hashtag to your link href so the page does not reload:

<a href="#" onclick="loadPage('page_1')">Home</a>

HTML

<div id="page_1" class=welcome_bye_holder>
  <h1 class="page_1">Welcome to Cyber Technician:</h1>
  <p1 class="page_1">An I.T. Technician and cyber security
    <br> for the
    <br>Southport, North Sefton area.</p1>
</div>

Javascript, Updated since the comments specify the issue

  //this hides all div's except fot the first one
  for (var i = 1; i <= 5; i++) {
    if (i === 1)
      document.getElementById('page_' + i).style.display = "block"
    else
      document.getElementById('page_' + i).style.display = "none"
  }

  //hides all div's and shows only div that was clicked
  function loadPage(varcontent) {
    var var1 = "";
    var1 = varcontent;
    var num = var1.slice(-1);

    document.getElementById(var1).style.display = "block";
    for (var i = 1; i <= 5; i++) {
      if (i == num)
        document.getElementById('page_' + i).style.display = "block"
      else
        document.getElementById('page_' + i).style.display = "none"
    }
  }
Comments