Khaled Abu Shamat
Khaled Abu Shamat

Reputation: 1134

jQuery getElementByClassName works but not always

I have this bit of jQuery that works perfectly as wanted but not always, sometimes it does not work until I refresh the page again, I don't know why.

All I want is to disable the main screen from scrolling when the sidebar is open and make it scroll when its closed (the side bar only appears if the window is small).

Here is my jQuery for that:

jQuery(document).ready(function($) {
$(".sidebar-mobile-icon").click(function() {
    var sideBar = $(".shop-sidebar");
    for (var i = 0; i < sideBar.length; i++) {
        $("html").css("overflow", "hidden");
        if(sideBar.hasClass("opened")) {
            $("html").css("overflow", "scroll");
        }   
    }
});
});

It can be tested if you visit my website: outfityard.com , the problem is in the sidebar but it only appears with a small window browser.

Upvotes: 0

Views: 57

Answers (2)

Bram Vanroy
Bram Vanroy

Reputation: 28447

I'm not sure why you use the for-loop, but this should work.

jQuery(document).ready(function($) {
  $(".sidebar-mobile-icon").click(function() {
      if ($(".shop-sidebar").hasClass("opened")) {
        $("html, body").css("overflow", "scroll");
      } else {
        $("html, body").css("overflow", "hidden");
      }
  });
});

Upvotes: 1

Christian Pastor Cruz
Christian Pastor Cruz

Reputation: 376

Apply style to the body, not html element.

Upvotes: 0

Related Questions