Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript - Sticky button depending on the width header

I'm trying to make a sticky header with an ul and one div.

The sticky header work fine, but i want to make sticky the div too, only when the screen width are >= 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 spected:

enter image description here

Here is a Live Demo .

What is wrong here? Can anyone help me?

Thanks in advance.

like image 458
Ferrmolina Avatar asked Feb 01 '26 18:02

Ferrmolina


1 Answers

First of all, because your button is not inside of the sticky div, you're going to have to make it sticky as well. Modify 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 that button with media queries like this:

@media only screen and (min-width: 981px) {
  .wrap-perfil.fixedBtn {
    position:fixed;
    /* We need a z-index greater than #sub-header-info's */
    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. */
  }
}
like image 155
Jonathan Avatar answered Feb 04 '26 16:02

Jonathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!