Jquery hover keep firing on a tag

The idea is that when users mouse over each name in the list, the div with id preview will have background image. The first a does not have a problem, but when I added the href, JavaScript keep firing the hover event. What is the problem here?

HTML

<ul>
  <li><a>John</a></li>
  <li><a href="#">Sam</a></li>
  <li><a href="#">Tom</a></li>
</ul>
<div id="preview"></div>

JavaScript

jQuery(function() {
  var names = $('a');
  var bg = document.getElementById('preview');

  names.hover(
    changeBackground, handlerOut
  );

  function changeBackground(e) {
    console.log('hover');
    var image = 'http://londonalley.com/wp-content/uploads/2014/08/creativesUS3bb-1920x1080.jpg';
    if (bg.style.cssText.length == 0) {
      bg.style.cssText = builtStyle(image);
      bg.style.display = "block";
    }
  }

  function builtStyle(image) {
    return "width: 100%;height: 100%;opacity: .6;position: absolute;top:0px;left: 0px;z-index: 101;opacity:.9: 1;display: block;visibility: visible;background-image: url(" +
      image + ");"
  }


  //handle mouse leaves
  function handlerOut() {
    console.log('out');
    if (bg.style.cssText) {
      bg.style.cssText = "";
    }

  }
});

JSfiddle: https://jsfiddle.net/rattanak22/q96a6dz4/

Answers 1

  • After looking at your site, simply, change your css rules to:

    #content-wrapper {
        position: relative;
        z-index: 102;
        overflow: hidden;
    }
    #preview{
       pointer-events: none;
    }
    

Related Articles