Search code examples
jqueryzooming

Add class on page zoom. Remove when 100%


I have a fixed navbar. I'd like to add a class of .zoomed to it when the page is zoomed and remove the class when normal size or 100%. I've found this detect-zoom.js plugin:

https://github.com/yonran/detect-zoom

…from this thread:

How to detect page zoom level in all modern browsers?

…that detects the page zoom but I'm a bit clueless when it comes to adding/removing the class. I've managed to get it to add the class when 'zoomed in' but I need to remove the class when at normal 100%. This is what I have which is using bits from the plugin demo:

<script src=detect-zoom.js></script>
<script>
    'use scrict';
    var zoomLevel = document.getElementById('zoom-level');
    window.onresize = function onresize() {
        $(".navbar").addClass("zoomed");
    }
    onresize();

    if ('ontouchstart' in window) {
        window.onscroll = onresize;
    }
</script>

My css would be:

.zoomed{ position: absolute; }

Basically I only want the class on the navbar when a page is zoomed. When not zoomed the class should be removed. I'm guessing an 'if' statement but I've tried a few things but doesn't seem to work.


Solution

  • In your onresize() function:

      // remove zoomed class
      $(".navbar").removeClass("zoomed");
    
      // 1 is 100%
      var zoom = DetectZoom.zoom();
    
      // +
      if(zoom > 1)
        $(".navbar").addClass("zoomed in");
    
      // -
      if(zoom < 1)
        $(".navbar").addClass("zoomed out");    
    

    (the fiddle)