Home > database >  hide button onmouseenter isn't triggering
hide button onmouseenter isn't triggering

Time:06-15

My onm ouseenter 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 onm ouseleave="showArrow() onm ouseenter="hideArrow()" id="top">
  hello
</div>


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

CodePudding user response:

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 onm ouseenter="hideArrow()" id="topDiv">
  hello
</div>

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

CodePudding user response:

  1. Remove the return keyword from the if condition because it causes the function to stop running at that point
  2. element.classList.add() is a function while you are assigning classes to the element using the '=' operator. So the correct way to do it is arrowup.classList.add('hideme') and arrowup.classList.remove('showme').
  • Related