user1335553
user1335553

Reputation:

Flash of background-color when using jQuery .slideToggle

When I'm using jQuery's .slideToggle I see a flash of the preferred background-color at .primary-navigation, but it's not persistant. It shows the preferred background-color during the animation, but it does not stay that way when the animation is complete. I keep scratching my head, but I can't figure it out. Does anyone know why this is happening and how to solve it? This problem occurs in the latest Chrome, FF and iOS Safari.

EDIT: Here is a jsFiddle that solved the problem: jsFiddle. Thanks to scessor for the quick reply!

HTML:

<header class="banner clearfix">
 <h1 class="alpha">Site Title</h1>
 <nav class="primary-navigation-wrapper">
   <ul class="primary-navigation">
     <li><a href="#" id="current-page">Blog</a></li>
     <li><a href="#">Archives</a></li>
     <li><a href="#">About</a></li>
     <li><a href="#">Contact</a></li>
   </ul>
 </nav>
</header>

CSS:

.banner {
  background-color: blue;
}

.banner h1 {
  padding: 6px;
  float: left;
}

h1.js-toggle-navigation {
  float: right;
  padding: 6px;
  cursor: pointer;
}

.primary-navigation {
  clear: both;
  display: none;
  background-color: red;
}

.primary-navigation li {
  float: left;
  display: block;
}

.primary-navigation a {
  padding: 6px 0 6px 6px;
  display: block;
}

jQuery (1.7.2.):

<script type="text/javascript">
  jQuery(document).ready(function($){
    /* prepend menu icon */
    $('.primary-navigation-wrapper').prepend('<h1 class="js-toggle-navigation">Menu</h1>');

    /* toggle nav */
    $(".js-toggle-navigation").on("click", function(){
      $(".primary-navigation").slideToggle();
      $(this).toggleClass("active");
    });
  });
</script>

Upvotes: 0

Views: 1250

Answers (2)

Pavel Strakhov
Pavel Strakhov

Reputation: 40502

Your ul contains only floating elements, so it's default height is 0. In normal (not animated) state background isn't visible because of zero height. In animated state jQuery sets explicit height for element, so background is showing. You should add overflow: hidden to .primary-navigation class in your css to get visible background.

Upvotes: 0

scessor
scessor

Reputation: 16115

You have to end the floating of the lis. E.g. add a css overflow: hidden; to the ul with the class primary-navigation:

.primary-navigation {
  overflow: hidden;
  ...
}

Also see my example. (Only for the example I've also added a top margin, without the Menu button couldn't be clicked in the jsfiddle caused by the result label.)

Upvotes: 1

Related Questions