Uncaught TypeError: Cannot read property 'clientWidth' from null

I have a responsive WordPress theme. The menu is encoded to hide when the screen size is below 740. However, it only does this correctly on the main page. If I go to any other page, the menu crashes, but it doesn’t hide, and I get this error: "Uncaught TypeError: cannot read property" clientWidth "from null"

Here is the code, I call it in the header.php file of the topic:

var ww = document.body.clientWidth; $(document).ready(function() { adjustMenu(); $(".cat").click(function(e) { // cat class e.preventDefault(); $(this).toggleClass("active"); $(".sf-menu").toggle(); }); }); function adjustMenu() { if (ww <= 740) { //change this to your breakpoint $('.sf-menu').hide(); $(".cat").show(); if (!$(".cat").hasClass("active")) { $(".sf-menu").hide(); } else { $(".sf-menu").show(); } } else { $('.sf-menu').show(); $(".cat").hide(); } } $(window).bind('resize orientationchange', function() { ww = document.body.clientWidth; adjustMenu(); }); 
+4
source share
2 answers

I would say using $(window).width(); from jquery. It returns the width of the browser viewport. This is equivalent, or I would say, a better alternative to traditional javascript.

Your code will look something like this. Check if it works.

 var ww = $(window).width(); $(document).ready(function() { adjustMenu(); $(".cat").click(function(e) { // cat class e.preventDefault(); $(this).toggleClass("active"); $(".sf-menu").toggle(); }); }); function adjustMenu() { if (ww <= 740) { //change this to your breakpoint $('.sf-menu').hide(); $(".cat").show(); if (!$(".cat").hasClass("active")) { $(".sf-menu").hide(); } else { $(".sf-menu").show(); } } else { $('.sf-menu').show(); $(".cat").hide(); } } $(window).bind('resize orientationchange', function() { ww = document.body.clientWidth; adjustMenu(); }); function adjustMenu() { if (ww <= 740) { //change this to your breakpoint $('.sf-menu').hide(); $(".cat").show(); if (!$(".cat").hasClass("active")) { $(".sf-menu").hide(); } else { $(".sf-menu").show(); } } else { $('.sf-menu').show(); $(".cat").hide(); } } $(window).bind('resize orientationchange', function() { ww = $(window).width(); adjustMenu(); }); 
+5
source

try adding a script to the end of the document. The reason is because the beginning of the width of your document is zero, because the content has not yet been loaded, so nothing is visible, and therefore the width is zero

+7
source

All Articles