Search code examples
javascripthtmlcssmouseevent

hide button onmouseenter isn't triggering


My onmouseenter function isn't triggering.

I created a button that would allow you to go to the top. However, once there I want the button to have a display property of none. I tried doing it in two ways. One with classList and the other with style.display = 'none'. Both didn't work, am I missing something in the logic ?

EDIT------------- onmouseleave the button should reappear. I added the function.

Here is a code pen

const topDiv = document.getElementById('topDiv')
const arrowup = document.getElementById('arrowup')

const hideArrow = () => {
  if (topDiv) {
    arrowup.classList.remove(showme');
    arrowup.classlist.add('hideme');

  } else {
    arrowup.classList.add('showme');
  }

}

 

  const showArrow = () => {
  if (!topDiv) {
    arrowup.classList.remove('hideme');
    arrowup.classList.add('showme');
  } 
}
#top {
  height: 1000px;
}

a {
  position: fixed;
  top: 10px;
}

.showme {
  display: block;
}

.hideme {
  display: none;
}
<div onmouseleave="showArrow() onmouseenter="hideArrow()" id="top">
  hello
</div>


<a class="showme" id="arrowup" onClick="hideArrow()" href="#top">
  click me
</a>


Solution

  • There are some issues:

    • onmouseenter="hideArrow" is missing brackets -> onmouseenter="hideArrow()"
    • add and remove are functions, that get the class as param -> add('showme')
    • the return is wrong -> remove it

    Working example:

    const topDiv = document.getElementById('topDiv')
    const arrowup = document.getElementById('arrowup')
    
    const hideArrow = () => {
      if (topDiv) {
        arrowup.classList.remove('showme');
        arrowup.classList.add('hideme');
      } 
      else {
        arrowup.classList.add('showme');
      }
    }
    #top {
      height: 1000px;
    }
    
    a {
      position: fixed;
      top: 50px;
    }
    
    .showme {
      display: block;
    }
    
    .hideme {
      display: none;
    }
    <div onmouseenter="hideArrow()" id="topDiv">
      hello
    </div>
    
    <a class="showme" id="arrowup" onClick="hideArrow()" href="#topDiv">
      click me
    </a>