Search code examples
jquerycsshoversticky

Css hover effect disabled after jQuery affecting different element


I set up a jQuery scroll function to make an header element sticky and become fixed at the top of the page. This part is working smoothly. However, once it becomes fixed, the navigation links are no longer registering a hover effect. I'm scratching my head on this because the jQuery event shouldn't affect the nav section at all. I thought it was a fluke or a typo, but re-creating a basic version here gave the same issue:

CodePen

Try hovering over the 3 links in the upper left corner, they get bold. But then when you scroll down til "Title" sticks, and try again - nothing. Can anyone steer me in the right direction? Thanks!

HTML

<nav>
  <ul>
    <li><a href="#">Home</a></li>
    <li><a href="#">Other</a></li>
    <li><a href="#">Thing</a></li>
  </ul>
</nav>

<h1 id="name" class="scrollName">TITLE</h1>

<div class="content">
  <h3>Stuff and Things</h3>
  <p>Bacon ipsum ... </p>
</div>

CSS

nav {
  height: 60px;
  position: fixed;
  width: 100%;
  top: 0;
  background-color: rgb(230, 230, 230);
  z-index: 5;
}

a {
  font-family: sans-serif;
  font-size: 16px;
  font-weight: 300;
  line-height: 1.8;
  text-decoration: none;
  color: black;
}

a:hover {
  font-weight: 700;
}

li {
  display: inline;
  margin-right: 10px;
}

.scrollName {
  position: absolute;
  width: 100%;
  text-align: center;
  top: 200px;
  z-index: 10;
}

.fixedName {
  position: fixed;
  width: 100%;
  top: 10px;
  margin: 0;
  text-align: center;
  z-index: 10;
}

.content {
  position: relative;
  width: 60%;
  margin: 0 auto;
  text-align: center;
  top: 300px;
}

Javascript

jQuery(document).ready(function() {
  var $nameOffset = jQuery("#name").offset().top;
  $nameOffset = $nameOffset - 9;

  jQuery(window).scroll(function() {
    var $scrollPos = jQuery(window).scrollTop();
    console.log($nameOffset);

    if ($scrollPos >= $nameOffset) {
      jQuery('#name').removeClass('scrollName').addClass('fixedName');
    } else {
      jQuery('#name').removeClass('fixedName').addClass('scrollName');
    };
  });

});

Solution

  • You can add pointer-event to the avoid this issue.

    .fixedName {
        position: fixed;
        width: 100%;
        top: 10px;
        margin: 0;
        text-align: center;
        pointer-events: none;
    

    }

    Updated codepen available in the following link

    http://codepen.io/anon/pen/ZGwppZ