skip to Main Content

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";
        }

2

Answers


  1. 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.

    Login or Signup to reply.
  2. 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;
      };
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search