1

I have a page with a menu an two div.

<nav id="menu">
<ul>
    <li><a href="#" class="active">soft1</a></li>
    <li><a href="#">soft2</a></li>
</ul>
</nav>

<section>
    <div id="soft1">
        <p>content</p>
    </div>
    <div id="soft2">
        <p>content</p>
    </div>
</section>

On a click from the nav, I'd like to add a class named "active" on the menu link and to show the right div in the following. I will start with a active tab, so I have to remove the class if I click on the second.

For example : Click on the Soft2 link => add an "active" class on the soft2 link => remove the active class on the soft1 link => show the soft2 block.

I don't use any JS library. I'd like to write it in pure JS. Can you help me ?

Thank you

FrancoisD
  • 59
  • 8
  • 1
    The question referenced by @BarbaraLaird answers this perfectly. – aurbano Mar 25 '14 at 16:52
  • I just want to add classes. Tabs are already build. – FrancoisD Mar 25 '14 at 16:53
  • You can just find a way to access the attributes of DOM element using pure Javascript, fortunately we have `getAttribute` and `setAttribute` functions, here is an example fiddle http://jsfiddle.net/mFgcb/5/ just try clicking on the div to see it in action. – King King Mar 25 '14 at 16:53
  • Yes I'm able to do it for one div but I don't know how to do, when I have to manage two div. :( – FrancoisD Mar 25 '14 at 17:00

1 Answers1

1

You can do something like below to achieve this:

window.onload = function showHide() {
 var x1 = document.getElementById('a1');
      x2 = document.getElementById('a2');
  s1= document.getElementById('soft1');
  s2= document.getElementById('soft2');  
  x1.onclick = function() {
    this.setAttribute("class","active");
    x2.removeAttribute("class");
    s1.style.display = "block";
    s2.style.display = "none";

  };

  x2.onclick = function() {
    this.setAttribute("class","active");
    x1.removeAttribute("class");
    s1.style.display = "none";
    s2.style.display = "block";

  };

 };

DEMO

defau1t
  • 10,593
  • 2
  • 35
  • 47