Search code examples
jqueryresizesupersized

Destroying jQuery Supersized on resize


I'm having a problem with using Supersized in a responsive website. If the window width is lower than 480px, than Supersized should be destroyed. If i resize it again for the window width to be larger than 480px, than Supersized should be reinitialized. I have this code:

$(document).ready(function() {
        var newWindowWidth = $(window).width();
        if(newWindowWidth < 480){
            $("#supersized").remove();
        } else {
            $.supersized({
                slides: [{ image: 'images/bg.jpg', title: ''}]
            });
        }
    });
    $(window).resize(function() {
        var newWindowWidth = $(window).width();
        if(newWindowWidth < 480){
            $("#supersized").remove();
        } else {
            /*var loadSupersizedDiv = jQuery('<div id="supersized"></div>').appendTo(document.body);*/
            $.supersized({
                slides: [{ image: 'images/bg.jpg', title: ''}]
            });
        }
    });

I know this isn't perfect, but the problem i'm having right now, is that the supersized div duplicates itself with every pixel on resize. Is there a way around this?

Thanks!


Solution

  • You have to check if supersized is already loaded and if not then load. Right now it loads on every resize.

    $(window).resize(function() {
        var newWindowWidth = $(window).width();
        if(newWindowWidth < 480){
            $("#supersized").remove();
        } else if ($("#supersized").length == 0 && newWindowWidth > 480) {
            var loadSupersizedDiv = jQuery('<div id="supersized"></div>').appendTo(document.body);
    
            $.supersized({
                slides: [{ image: 'kazvan-1.jpg', title: ''}]
            });
        }
    });
    

    Ok, tested it and basically what it does is just it just checks if #supersized already exists then not create a new one.