0

Im having an issue with setting my bacground image by using an external js code. this is the code of the js:

$(document).ready()
{
mazdaArr = new Array();
    for (i=1;i<6;i++)
    {
        mazdaArr[i-1]= new Image();
        mazdaArr[i-1].src = 'mazda/mazda'+[i]+'.jpg';
    }   
    $('mainContent').css('background-image','url(/mazda/mazda4.jpg)');
    $('mainContent').css('background-image', 'url(' + mazdaArr[3].src + ')');
    console.log(mazdaArr[3].src);
}

everything works fine but the css attr, since I can see at the console the right link and when I click it, the image will open up in new tag. by that i guess the jquery call from html page is fine.

cant find what goes wrong here...

4
  • Aren't you missing quotation marks around the URIs? They should read like url("http://example.com/foo.png");. Commented Oct 30, 2013 at 14:50
  • Just tried to add it and it won't work... by the way the both lines should set the same background image, i've just tried to put it with the direct url and still gives nothing. Commented Oct 30, 2013 at 14:56
  • When you set URL you don't need quotes. It's weird. Commented Oct 30, 2013 at 15:06
  • Have you tried running this function from the console and seeing what happens? Commented Oct 30, 2013 at 15:07

1 Answer 1

2

A few things:

  • Looks like your string is concatinating an array literal, and not the integer i. So 'string'+[]+'string' is effectively 'string' + new Array() + 'string'.
  • Your selector for mainContent needs to either be looking for a class or an ID so either .mainContent or #mainContent.
  • Finally, you don't need to instantiate a new Image since jQuery will just update the CSS of the element with a new string for the background-image property.

Try

$(document).ready(function() {
    var mazdaArr = [],
        i = 0;
    for (i; i<5; i++) {
        mazdaArr[i] = 'mazda/mazda'+ i +'.jpg';
    }   

    $('#mainContent').css('background-image', 'url(' + mazdaArr[3] + ')');

    console.log(mazdaArr[3].src);
});
Sign up to request clarification or add additional context in comments.

5 Comments

Good find, but didn't he say the link opens correctly in a new tab?
In fairness, it doesn't need the new image part at all - the images path should suffice.
gives the same result
Just noticed the mainContent selector was missing a period or a hash, and you shouldn't need to instantiate an Image either. Try the updated example.
Glad it worked! Just updated the answer to explain why, feel free to accept it ;)

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.