seandaniel
seandaniel

Reputation: 151

Scroll function behaves differently depending how wide browser is when loaded

I have an image in my navigation that gets smaller when you scroll down 100px. I want this feature only to work when the width of my screen is above 1200px.

When the browser is loaded 1200px and up, the scroll function works for all widths of the browser. I want it to not work when it is less than 1200px.

When the browser is loaded 1199px or smaller, the scroll function doesn't work at all when I want it to activate at 1200px.

 <header class="header">
    <nav class="primary-nav">
      <h1><a href="#"><img src="/" alt="alt"></a></h1>
      <button class="align-right-button"><i class="fas fa-align-right"></i></button>
 </header>
.primary-nav {
  position: fixed;
  z-index: 110;
  top: 0;
  left: 0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background-color: white;
  padding: 0 5px;
  width: 100%;
  img {
    width: calc(400px / 2);
    height: calc(189px / 2);
    transition: width .35s, height .35s;
    display: block;
  }
  .align-right-button {
    font-size: 2rem;
  }
}

@media (min-width:1200px) {
  .primary-nav img {
    width: calc(400px / 1.5);
    height: calc(189px / 1.5);
  }
}
const mq1200 = window.matchMedia("(min-width: 1200px)");

$(function() {

  if (mq1200.matches) {
    $(window).scroll(function() {
      if ($(window).scrollTop() > 100) {
        $(".primary-nav img").css({'height': 'calc(189px / 2)', 'width': 'calc(400px / 2)'});
      } else {
        $('.primary-nav img').css({'height': 'calc(189px / 1.5)', 'width': 'calc(400px / 1.5)'});
      }
    });
  } else {
    $(".primary-nav img").css({'height': 'calc(189px / 2)', 'width': 'calc(400px / 2)'});
  }
});

Upvotes: 0

Views: 36

Answers (1)

Shiny
Shiny

Reputation: 5055

You're currently only checking mq1200 once, when the page is loaded - Use $(window).on('resize', ... to update the variable whenever the window is resized

Also, make sure to change const mq1200 to let mq1200 to support this change

$(function() {
  let mq1200 = window.matchMedia("(min-width: 1200px)");

  $(window).on('resize', function() {
    mq1200 = window.matchMedia("(min-width: 1200px)");
  });

  $(window).on('scroll', function() {
    if (mq1200.matches) {
      if ($(window).scrollTop() > 100) {
        $(".primary-nav img").css({'height': 'calc(189px / 2)', 'width': 'calc(400px / 2)'});
      } else {
        $('.primary-nav img').css({'height': 'calc(189px / 1.5)', 'width': 'calc(400px / 1.5)'});
      }
    } else {
      $(".primary-nav img").css({'height': 'calc(189px / 2)', 'width': 'calc(400px / 2)'});
    }
  })
});

Upvotes: 2

Related Questions