开发者

jQuery Syntax Error - Trying to detect viewport size and select background image to use w/CSS

Please be gentle, I'm still learning. I imagine that the solution to my problem is simple and that perhaps I have just been in front of the computer too long.

I am trying to detect the size of the viewport, and then use a different sized image for a background on an element depending on the size of the viewpo开发者_运维问答rt.

Here is what I have so far:

$(document).ready(function(){

    var pageWidth = $(window).width();

    if ( pageWidth <= 1280 ) {
        $('#contact').css('background-image', 'url(../images/contact_us_low.jpg)');
    }
    elseif ( pageWidth > 1280 ) {
        $('#contact').css('background-image', 'url(../images/contact_us_high.jpg)');
    }
 });

Error:

missing ; before statement [Break on this error] elseif ( pageWidth > 1280 ) {\n (Line 7)

To me it seems like all of my semi-colons are in the right place. Two questions:

  1. Am I going about solving the problem in a sensible way? To me a simple conditional should solve this background problem, as the code is merely selecting between two images based on what size it detects the viewport to be.

  2. Can you please help point out my n00b syntax error? Sometimes it really does help to have an extra pair of eyes look at something like this, even if small.

Thank you kindly for your advice, I will continue poking and perusing the docs I have available to me.


The error is in your Javascript else If syntax. You need to have a space between else and If.


You can just do an else.

$(document).ready(function(){

    var pageWidth = $(window).width();

    if ( pageWidth <= 1280 ) {
        $('#contact').css('background-image', 'url(../images/contact_us_low.jpg)');
    } else {
        $('#contact').css('background-image', 'url(../images/contact_us_high.jpg)');
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜