Search code examples
jquerymagnific-popup

Fire Magnific Popup only above certain screen width


Having a mind blank at the moment. I wish to fire Magnific only above certain screen widths. My code is

        $(function() {
            $('.photos a').magnificPopup({
                gallery: {
                    enabled: true
                },
                type: 'image',
                zoom: {
                    duration: 250,
                    enabled: true
                }
            });
        });

Do I need to wrap it in a function and then do something with $('.photos a').click();


Solution

  • Yes. Code like $('.photos a').magnificPopup(... creates a listener; it takes an action on the page. So if you want a conditional listener, you should only define / create the listener if the condition is met.

    See jQuery: How to detect window width on the fly? and http://www.fourfront.us/blog/jquery-window-width-and-media-queries for assorted ideas on how to best detect the viewport width.

    But the net result could be structured something like this:

    var windowsize = $window.width();
    if (windowsize > 440) {
      // Any code inside here will only execute on larger window sizes.
      // So define your listener here.
      $('.photos a').magnificPopup({...
    }
    

    EDIT: It sounds like part of the issue here is how to dynamically enable or disable the widget when the user adjusts their screen size. You could potentially wrap the window width check in a .click(function(){... listener but this could get complicated, so I looked into Magnific's API documentation and found there's an option for exactly this situation.

    See http://dimsemenov.com/plugins/magnific-popup/documentation.html#options: when declaring the Magnific widget (like in your code above, add a disableOn option as follows. This will disable the widget entirely if the condition below is met.

    disableOn: function() {
      if( $(window).width() < 600 ) {
        return false;
      } else {
        return true;
      }
    }