skip to Main Content

I created a submenu that expands on clicking on a toggle text using HTML CSS and JavaScript. The problem is that, after every third consecutive click, the toggle text is highlighted. How do I prevent this from happening?
I’m asking this because all the toggle submenus I’ve seen on professional websites don’t get highlighted. I am attaching part of the code for reference.

const toggleElements = document.querySelectorAll('.toggle');

toggleElements.forEach((toggle) => {
  const content = toggle.nextElementSibling;

  // Add a click event listener to toggle the content visibility
  toggle.addEventListener('click', () => {
    if (content.style.display === 'block') {
      content.style.display = 'none';
    } else {
      content.style.display = 'block';
    }

  });
});
<div>
  <div class="toggle">
    <a>Fit</a>
  </div>
  <div class="content">
    <div class="wrapper-content">
      <p> test1</p>
      <p>test2</p>
    </div>
  </div>
</div>

2

Answers


  1. Use a button not a link then you can style it to get the look you want.

    const toggleElements = document.querySelectorAll('.toggle');
    
    toggleElements.forEach((toggle) => {
      const content = toggle.nextElementSibling;
    
      // Add a click event listener to toggle the content visibility
      toggle.addEventListener('click', () => {
        if (content.style.display === 'block') {
          content.style.display = 'none';
        } else {
          content.style.display = 'block';
        }
    
      });
    });
    <div>
      <button class="toggle">fit</button>
      <div class="content">
        <div class="wrapper-content">
          <p> test1</p>
          <p>test2</p>
        </div>
      </div>
    </div>
    Login or Signup to reply.
  2. user-select: none; prevents the user from selecting and highlighting text

    const toggleElements = document.querySelectorAll('.toggle');
    
    toggleElements.forEach((toggle) => {
      const content = toggle.nextElementSibling;
    
      // Add a click event listener to toggle the content visibility
      toggle.addEventListener('click', () => {
        if (content.style.display === 'block') {
          content.style.display = 'none';
        } else {
          content.style.display = 'block';
        }
    
      });
    });
    .toggle a, .content p {
        user-select: none !important;
        -webkit-user-select: none !important;
        -moz-user-select: none !important;
        -ms-user-select: none !important;
        cursor: text !important;
    }
    <div>
      <div class="toggle">
        <a>Fit</a>
      </div>
      <div class="content" style="display: none;">
        <div class="wrapper-content">
          <p> test1</p>
          <p>test2</p>
        </div>
      </div>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search