Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Nandakishore J
Nandakishore J
4,641 Points

Can someone please help me? On the click of an id, another class needs to appear and it should get hidden on another.

I want to create a menu, and with or without JQuery, when I press an image, the menu should appear from nowhere. On the second click of the image, which acts as the button, it should be hidden back.

It would be better if there is any way, when clicking on the button, the class of a div should be changed to another div.

Thanks in advance for answering.

1 Answer

This is absolutely possible. I haven't tested the following code, but it should point you in the right direction.

Without jQuery:

document.getElementById('menuButton').onClick = function() {
  document.getElementById('aDiv').classList.remove('theClass');
  document.getElementById('anotherDiv').classList.add('theClass');
}

Javascript also has classList.contains() and classList.toggle() functions available.

With jQuery:

$('#menuButton').click(function() {
  $('#aDiv').removeClass('theClass');
  $('#anotherDiv').addClass('theClass');
});

jQuery also has hasClass() and toggleClass() functions available.