Search code examples
javascriptbackgroundimagescreen-resolution

Adding background img if screen resolution width >1028


Hi guys,

I'm fairly new to javascript. I have a pretty simple script I wrote to add a background image if the screen resolution width is bigger than 1028px.

Unfortunately, after trying this (on another computer, with 800x600 resolution), it doesn't work.

I'm not looking to stretch the image, just simply add it if the screen resolution width is bigger than or equal to 1024.

Here is the code:

    <SCRIPT language="JavaScript">
    <!--
    document.write('<style type="text/css">div#container_header_body {background-image:url(\'');
    if (screen.width<1024)
    {
     document.write('none;');
    }
    else
    {
      document.write('images/mmmgirl.png');
    }
    document.write('\');</style>');
    //-->
    </SCRIPT>

<link rel="stylesheet" type="text/css" href="stylesheet.css" />

Can anybody give me some insight into what I'm doing wrong?

Thanks so much. I've already learned a LOT from this place.

- - Andrew


Solution

  • Try this jsfiddle:

    var screenWidth = screen.width,
        container = document.getElementById('container_header_body');
    
    console.log(screenWidth);
    
    if (screenWidth > 1024) {
         container.style.backgroundImage = 'url(http://oddanimals.com/images/lime-cat.jpg)';
    } else {
        container.style.backgroundImage = 'none';
    }