Multiple functions on JavaScript

Hi everyone :wave:
Is there a short or simplified way to write this code instead of using two functions? … it controls opening and closing of the side nav onclick.

function openNav(){
document.getElementById (“sideNav”).style. width = “80%”;
}
function closeNav(){
document.getElementById(“sideNav”).style. width = “0”;

}

How are the functions currently called? Are they attached to the same button or different buttons?

Hello
look into “ternary” functions,

example:

let result = condition ? value1 : value2;

if you have two interchangeable values, this might be what you are looking for

1 Like

Sure. You could have a function like “toggleNav” that you could call, but it would have to have some way of knowing the current state of the nav so it would know what to do. You could store that in a variable or you could read it from the DOM.

1 Like

Different buttons
Menu button for opening nav and close button (× )which appear on the open side nav bar

You can definitely use a single function. My suggestion is to start by adding a class named side-nav to the same element you current have the id="sideNav". I would make sure the width is set to 0 (which will make it so the side nav is not seen). Then you would create a new class called open-nav and use width: 80%, since this is the width you wanted when the nav is open.

I would also suggest giving an id to each button (i.e. open for the button which opens the side nav and close which closes the side nav).

Finally, you can create a function called something like toggleSideNav that has one argument (‘event’) and gets the value of event.target.id and if it is open, then you add the class open -nav to it. Otherwise, it is assumed the close button was clicked, so you would remove the class open-nav.

You could use the code you were using by changing the style directly with JavaScript, but the way I suggest is more common.

function toggleSideNav (event) {
  const targetId = event.target.id;
  const sideNav = document.getElementById(`sideNav`);
  if (targetId === 'open')
    sideNav.classList.add('open-nav');
  else {
    sideNav.classList.remove('open-nav');
  }
}

document.getElementById('open').addEventListener('click', toggleSideNav);
document.getElementById('close').addEventListener('click', toggleSideNav);
1 Like

Thank you i did it and it working