Search code examples
javascriptwindowwidth

trying to get window width with javascript


Trying to calculate window width but it is not working. My code:

var windowWidth = '';
function getWidth() {
  windowWidth = $(window).width() / parseFloat($("body").css("font-size"));
}

I want to use windowWidth but it will not let me. WHy?


Solution

  • As commented, you can just use window.innerWidth, but for your specific case it should work just fine with what you have, you just need to call the function you've written:

    window.addEventListener("load", getWidth);
    window.addEventListener("resize", getWidth);