javascripthtmlmouseeventmouseovermouseout

Mouseover event is glitchy


I am pretty new to javascript so for lack of a better word I'm using the term "glitchy" to describe what is going on with the event. So when I hover the text "Show message", a text box is supposed to appear saying "Welcome to IT 202". While it is working, it seems very finnicky. When I hover over the text the banner flickers in and out, and it is also kinda picky as to where I am exactly hovering. So I just want to make it so when I hover the message displays and doesn't flicker, and when I mouse out it disappears.

const text = document.getElementById("text");
const banner = document.getElementById("banner");

text.addEventListener("mouseover", over);
text.addEventListener("mouseout", out);

function over() {
  banner.style.display = "block";
}

function out() {
  banner.style.display = "none";
}
h1 {
  background-color: blueviolet;
  color: white;
  width: 250px;
  border: 2px solid black;
  padding-top: 20px;
  padding-bottom: 20px;
}


#text {
  color: blueviolet;
  width: 250px;
  margin: 0;
}


p {
  font-family: "Times New Roman", Times, serif;
  font-size: 20px'
}
<h1 id="banner">Welcome to IT202</h1>
<p>
  <strong>Mouse over the text "Show Welcome" and the welcome message is displayed. Mouse out and the welcome messages disappears!</strong>
</p>
<p1 id="text">Show Welcome</p1>

I tried changing the padding and margins to see if maybe that was causing it but it didn't change anything.


Solution

  • The position of the <p1 id="text">Show Welcome</p1> element is affected by the position of the banner element. When the banner disappears, it causes a change in the position of the text, similar to a mouse-out effect. I don't know if that is what you want exactly but you can alter the visibility instead of the display, so that the position of text won't change:

    const text = document.getElementById("text");
    const banner = document.getElementById("banner");
    text.addEventListener("mouseover", over);
    text.addEventListener("mouseout", out);
    
    function over() {
      banner.style.visibility = "visible";
    }
    
    function out() {
      banner.style.visibility = "hidden";
    }
    h1 {
      visibility: hidden;
      background-color: blueviolet;
      color: white;
      width: 250px;
      border: 2px solid black;
      padding-top: 20px;
      padding-bottom: 20px;
    }
    
    #text {
      color: blueviolet;
      width: 250px;
      margin: 0;
    }
    
    p {
      font-family: "Times New Roman", Times, serif;
      font-size: 20px'
    
    }
    <h1 id="banner">Welcome to IT202</h1>
    <p><strong>Mouse over the text "Show Welcome" and the welcome message is displayed. Mouse out and the welcome messages disappears!</strong></p>
    <p1 id="text">Show Welcome</p1>

    I assume any solution that not allows the text to move as a consequence would work (placing the banner under the text, making the text position obsolete, etc.)