Search code examples
javascripthtmlonmouseoveronmouseout

JavaScript's onmouseover and onmouseout events causing blinking


I have problem with JavaScript, onmouseover and onmouseout events. When mouse comes to bottom edge of desired element, mouseover and mouseout effects start blinking. Here is example:

function menuHover(field)
{
     var img = field.nextElementSibling;
     var height = img.height;
     var bottom = 0 - Math.floor(height / 2);
     bottom += 'px';
     img.style.display = 'block';
     img.style.bottom = bottom;
}

function menuHoverOut(field)
{
    var img = field.nextElementSibling;
    img.style.display = 'none';
}

DEMO: https://jsfiddle.net/index23/ety2z0zu/9/

Is there solution for this?


Solution

  • CSS would be the recommendation. But here is the answer for your question https://jsfiddle.net/ety2z0zu/11/. Please remove img.style.bottom = bottom; from your JavaScript

    function menuHover(field) {
      var img = field.nextElementSibling;
      var height = img.height;
      var bottom = 0 - Math.floor(height / 2);
      bottom += 'px';
      img.style.display = 'block';
      // console.log(height);
    }
    
    function menuHoverOut(field) {
      var img = field.nextElementSibling;
      img.style.display = 'none';
    }
    a,
    a:link {
      color: inherit;
      text-decoration: none;
    }
    body {
      background-color: #2a4b8b;
    }
    header nav {
      text-align: center;
      position: relative;
    }
    .main-nav {
      margin: 0 auto;
      padding-right: 25px;
      list-style: none;
      display: inline-block;
    }
    .main-nav li {
      float: left;
      margin-right: 23px;
      display: block;
      padding-top: 50px;
      -webkit-box-shadow: 0 4px 8px rgba(2, 3, 2, .39);
      -moz-box-shadow: 0 4px 8px rgba(2, 3, 2, .39);
      box-shadow: 0 4px 8px rgba(2, 3, 2, .39);
      position: relative;
    }
    .main-nav li a {
      display: block;
      padding-left: 25px;
      padding-right: 25px;
      padding-bottom: 3px;
      border-bottom: 5px solid #6173ad;
      border-bottom-right-radius: 5px;
      border-bottom-left-radius: 5px;
    }
    .hover-img {
      display: none;
      position: absolute;
      left: 0px;
      width: 100%;
      height: auto;
    }
    <header>
      <nav>
        <ul class='main-nav'>
          <li>
            <a href='#' onmouseover='menuHover(this);' onmouseout='menuHoverOut(this);'>LINK</a>
            <img alt='' class='hover-img' src='https://dl.dropboxusercontent.com/u/32550463/menu-hover.png' />
          </li>
          <li>
            <a href='#' onmouseover='menuHover(this);' onmouseout='menuHoverOut(this);'>LINK</a>
            <img alt='' class='hover-img' src='https://dl.dropboxusercontent.com/u/32550463/menu-hover.png' />
          </li>
        </ul>
      </nav>
    </header>