Search code examples
jquerywordpressmedia-queries

How to execute some piece of jquery code only when the viewport is above 1000px in WordPress


I need to execute some jquery code here when the viewport is above 1000px and above only but I can't get it to work. Please someone tell me what I'm doing wrong.

jQuery(document).ready(function($) {
  $(window).on('scroll', function() {
    var y = $(window).scrollTop();
    var width = $(window).innerWidth();

    if (window.location.pathname == '/') {
      if ($(window).innerWidth() > 1000 && y > 0) {
        $('#top').fadeIn();
        $('#header-space').fadeIn();
      } else {
        $('#top').fadeOut();
        $('#header-space').fadeOut();
      }
    } else {}
  });
});

Solution

  • You dont really need $(window).innerWidth() you can use plain js for it.

    window.innerWidth
    

    If you use Jquery it uses

    $( window ).width();
    

    https://api.jquery.com/width/

    jQuery(document).ready(function($) {
      $(window).on('scroll', function() {
        var y = $(window).scrollTop();
        var width = $(window).width();
    
        if (window.location.pathname == '/') {
          if (width > 1000 && y > 0) {
            $('#top').fadeIn();
            $('#header-space').fadeIn();
          } else {
            $('#top').fadeOut();
            $('#header-space').fadeOut();
          }
        }
      });
    });