April 8, 2012

Change javascript according to window width

Question by awDemo

I think this is quite simple but after 2 days of trying I’m still clueless. Basically, I need to run one set of commands if the screen is over 767 pixels wide and another if the screen is under 767 pixels.

When the screen is wider than 767 pixels, I want to:

<script type="text/javascript">

    var jsReady = false;//for flash/js communication

    // FLASH EMBED PART
    var flashvars = {};
    var params = {};

    params.quality = "high";
    params.scale = "noscale";
    params.salign = "tl";
    params.wmode = "transparent";
    params.bgcolor = "#111111";//change flash bg color here
    params.devicefont = "false";
    params.allowfullscreen = "true";
    params.allowscriptaccess = "always";
    var attributes = {};
    attributes.id = "flashPreview";

    swfobject.embedSWF("preview.swf", "flashPreview", "100%", "100%", "9.0.0", "expressInstall.swf", flashvars, params, attributes);

    <!-- and much more code... -->

</script>

When the screen is narrower than 768 pixels, I want to run:

<script type="text/javascript">  

        jQuery(function($){
            $.supersized({
                //Background image
                slides  :  [ { image : 'img/some_image.jpg' } ]                 
            });
        });

</script>

That’s right… For desktops and tablets, I want to show a full-screen video background. For smaller screens (less than 767 pixels), I want to show a single still image background.

Answer by Starx

You can get the currect size of windows using $(window).width() and attach a handler on the resize event of the form. For a simple use, It is as simple as

$(window).resize(funcion() {
    $width = $(window).width();
    if($width < 767) {
            $.supersized({
                //Background image
                slides  :  [ { image : 'img/some_image.jpg' } ]                 
            });
    } else {
        //if width is greater than 767
    }
});

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!