Please tell me why this function does not work correctly. It adds a class only after manually changing the screen width, and if the screen width is already less than 640px, then after updating the page, the class is added only if you change the screen width again.

$(document).ready(function() { $(window).resize(function() { if ($(window).width() <= '640'){ $('.header__navigation-img').on('click', function(){ $('.header__nav').toggleClass('header__nav-active'); }) } else { $('.header__nav').removeClass('header__nav-active'); } }); } 
  • You have the screen width check in the resize function, and you need this check to be in the ready function - Sergey Glazirin
  • Thanks, fixed, works. - Marian Vytak

2 answers 2

 $(document).ready(function() { $('.header__navigation-img').on('click', function() { if ($(window).width() <= 640) { $('.header__nav').toggleClass('header__nav-active'); } }); $(window).resize(function() { if ($(window).width() > 640) { $('.header__nav').removeClass('header__nav-active'); } }); $(window).resize(); $('.header__navigation-img').click(); }); 
  • And why the last 2 lines? - Marian Vytak
  • @MarianVytak To add or remove a class after the page loads. - Igor
  • Understood thanks. - Marian Vytak

To score everything in variables for good:

 $(document).ready(function() { var $window = $(window); var $nav = $('.header__nav'); var $navImage = $('.header__navigation-img'); $navImage.on('click',function(e){ if ($window.width() <= 640) { $nav.toggleClass('header__nav-active'); } }).trigger('click'); $window.resize(function() { if ($window.width() > 640) { $nav.removeClass('header__nav-active'); } }).trigger('resize'); });