0

I'm trying to add a jQuery plugin only when the screen size is 1200px or larger.

I want it to function on window load and resize, but i can't get it to work properly, i want it to work like a css media query, checking the window size on every resize and applying the changes, in this case the plugin.

JSFiddle

$(window).on('load resize', function() {
if (window.matchMedia("(min-width: 1200px)").matches) {
    $('.zoom').zoom(); 
  }; 
});
.center {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.zoom {
  display: flex;
  align-items: center;
  justify-content: center;
  float: left;
  width: 90%;
}

.zoom img {
  width: 70%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-zoom/1.7.20/jquery.zoom.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class=center>
<div class="zoom"><img src="https://www.aussiespecialist.com/content/asp/en_sg/sales-resources/image-and-video-galleries/jcr:content/mainParsys/hero/image.adapt.1663.medium.jpg"></div>
</div>

1 Answer 1

1

I would get the screen width using jQuery and run an if statement to execute your code. I normally nest the $(window).resize() event within the $(document).ready() event. See code below! Hope it helps...

$(document).ready(function(){
        enableZoom();
    $(window).resize(function(){
        enableZoom();
    });
});
function enableZoom(){
    var screen_width = $(window).width();
    if (screen_width > 1200){
        $('.zoom').zoom();
    }else if (screen_width <= 1200){
        $('.zoom').trigger('zoom.destroy');      
    } 
}
Sign up to request clarification or add additional context in comments.

6 Comments

it doesn't work, this initializes the plugin only on screen resize and keep it initialialized in all screen sizes.
@GabrielSouza When you say 'initializes the plugin' what to you mean? Do you mean adding the .zoom()?
yes, i want to add it only when the screen is bigger than 1200px and remove it when is not, same way as css media queries work.
@GabrielSouza I'm updating my answer with some tested code. Have a look and see what you think.
Apparently it works fine, but i don't want to depend on a plugin function to remove it, is possible to do the same thing without zoom.destroy?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.