0

I am a beginner in javascript and I have this code This code shows the user to add new input but I think I can make it shorter but I can't find the right way?

showCurs.onclick = function() {
          curses.style.display="block";

        }
        hideCurs.onclick = function() {
          curses.style.display="none";
        }

        showaddcurs.onclick = function() {
          addc.style.display="block";
        }
        hideaddcurs.onclick= function() {
          addc.style.display="none";}
        
  
        showExp.onclick = function() {
        exp.style.display="block";
      }
        showaddexp.onclick = function() {
      adde.style.display="block";
      }
        
        hidexp.onclick = function() {
        exp.style.display="none";
        }
ANFAL
  • 9
  • 5
  • 1
    Yes, with selectors and loops. Just be smarter when creating your HTML / assigning classes and do something like this: https://stackoverflow.com/questions/21700364/adding-click-event-listener-to-elements-with-the-same-class You could also take advantage of event bubbling and add the click event to all these elements parents. – chq Mar 26 '23 at 04:14

2 Answers2

2

Add a data attribute to each button indicating the ID (or some other unique attribute) of the element to be toggled. Use another attribute or the text content of the button to indicate whether the element should be shown or hidden (if the buttons are always visible and you don't already have a way to distinguish between them).

So for showCurs, hideCurs, and curses, you could have

// Use event delegation so that only one listener is added
document.addEventListener('click', (e) => {
  const button = e.target.closest('button[data-target]');
  if (!button) return;
  const target = document.getElementById(button.dataset.target);
  target.classList.toggle('hide', button.textContent === 'Hide');
});
.hide {
  display: none;
}
<button data-target="curses">Show</button>
<button data-target="curses">Hide</button>
<div id="curses">curses</div>

Further modifications only require adding in the HTML for the show/hide buttons and their associated toggle target.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

There are lots of ways to change your code to help eliminate duplicate parts. For example:

[
  [showCurs, curses, "block"],
  [hideCurs, curses, "none"],
  [showaddcurs, addc, "block"],
  [hideaddcurs, addc, "none"],
  [showExp, exp, "block"],
  [showaddexp, adde, "block"],
  [hidexp, exp, "none"]
].forEach(([click, target, effect]) => {
  click.onclick = () => {
    target.style.display = effect;
  };
});
Ouroborus
  • 16,237
  • 4
  • 39
  • 62