Boky
Boky

Reputation: 12064

Fixed div on scroll

I'm trying to create a div which will get a class only on scrolling and when the value of scroll is 210. I have next code :

$(document).ready(function() {
    var pageWidth = $(window).width();

    if(pageWidth > 700){
        var contentLeft = $('#content-left');
        var height = 210;

        $(window).scroll(function () {
            if ($(window).scrollTop() < height) {
                contentLeft.attr('class', 'content-left');
            } else {
                contentLeft.attr('class', 'content-left leftContentFixed');
            }
        });
    }
});

I try to apply this only on desktops. Thus, I do not need the class leftContentFixed if it's on a smartphone or tablet.

If I try something like :

$(document).ready(function() {
    var pageWidth = $(window).width();

    if(pageWidth > 700){
        alert("Bigger than 700");
    }else{
        alert("Smaller than 700");
    }
});

Than it works perfect, but with my code it isn't working. The class leftContentFixed is added although the screen is smaller than 700.

Any advice?

Upvotes: 1

Views: 88

Answers (1)

t1m0n
t1m0n

Reputation: 3431

You need to check screen size on resize event and check for its value when user scrolls the page. You could create mobile variable and make it true/false depends on screen size, then in scroll callback check for its value and choose correct class.

$(document).ready(function() {
  var pageWidth = $(window).width(),
    height = 210,
    contentLeft = $('.content-left'),
    mobile = false;

  $(window).on('load resize', function() {
    pageWidth = $(this).width();
    // Save mobile status
    if (pageWidth > 700) {
      mobile = false;
    } else {
      mobile = true
    }
  })

  $(window).on('scroll', function() {
    if ($(window).scrollTop() > height) {
      // Set default class
      var _class = 'content-left leftContentFixed';
      // If mobile then modify class
      if (mobile) {
        _class = 'content-left';
      }
      contentLeft.attr('class', _class);
    } else {
      var _class = 'content-left';
      contentLeft.attr('class', _class);
    }
  });

});
html {
  height: 2000px
}

.content-left {
  background: gold;
  width: 50px;
  height: 100px;
}

.content-left.leftContentFixed {
  position: fixed;
  top: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="content-left"></div>

Upvotes: 1

Related Questions