Javascript - button depending on title width

I am trying to make a sticky header with ul

and one div

.

The sticky header works fine, but I only want to make it sticky div

when the screen is wide >= 981px

.


code


HTML:

<div id="sub-header-info">
    <div class="wrap-perfil">
        <nav class="barra-header">
            <ul>
                <li><a class="actividad" href="index.php">Actividad</a></li>
                <li><a class="favoritos" href="#">Favoritos</a></li>
                <li><a class="seguidores" href="seguidores.php">Seguidores</a></li>
                <li><a class="seguidos" href="seguidos.php">Siguiendo</a></li>
            </ul>
        </nav>
    </div>
</div>
<div class="wrap-perfil">
    <div class="boton-seguir"><a href="#">Seguir</a></div>
</div>

      

CSS

.boton-seguir {
    float:right;
    position: relative;
    top: -40px;
}
.boton-fixed {
    position: fixed;
    top: 161;
    right: 90px;
}

      

JavaScript:

var stickyOffset = $('#sub-header-info').offset().top;

$(window).scroll(function(){
  var sticky = $('#sub-header-info'),
      scroll = $(window).scrollTop();

  if (scroll >= stickyOffset) sticky.addClass('fixed');
  else sticky.removeClass('fixed');
});

var stickyOffset2 = $('.boton-seguir').offset().top;
    var boton = $('.boton-seguir');
        scroll = $(window).scrollTop();

    if (screen.width >= 981 && scroll >= stickyOffset2)
        boton.addClass('boton-fixed')

      


What I used:

enter image description here

Here . Live Demo

What's wrong here? Can anyone help me?

Thanks in advance.

+3


source to share


1 answer


First of all, because your button is not inside a sticky div, you will have to make it sticky as well. Change your JavaScript like this:

var stickyOffset = $('#sub-header-info').offset().top;

$(window).scroll(function(){
  var sticky = $('#sub-header-info'),
      scroll = $(window).scrollTop(),
      stickyBtn = sticky.next();

  if (scroll >= stickyOffset) {
    sticky.addClass('fixed');
    stickyBtn.addClass('fixedBtn');
  }
  else {
    sticky.removeClass('fixed');
    stickyBtn.removeClass('fixedBtn');
  }
});

      



Now you can catch this button with media queries like:

@media only screen and (min-width: 981px) {
  .wrap-perfil.fixedBtn {
    position:fixed;
    /* We need a z-index greater than #sub-header-info */
    z-index: 1000000;
    /* Probably better to remove the negative-top off of the child element, 
     * but this hack will demonstrate how it works.  :) */
    top: 60px;
  }
}
@media only screen and (max-width: 980px) {
  .wrap-perfil.fixedBtn {
    /* Add CSS for smaller screens here. */
  }
}

      

+3


source







All Articles