2

I am working in JavaScript and i want to select an element from an array, and insert into the css that element.But it's not working.What's wrong with it?

function touch(index) {
  var images = ["Data\Images\heroim-banner.png", "image3.png", "image1.png"];
  var page = $('#page');

  if (index == 0) {
    page.css('background-image', 'url(' + images[0] + ')');
  }
  if (index == 1) {

  }
  if (index == 2) {

  }
}
2
  • use index === 0 and can you fiddle your code Commented Jun 1, 2015 at 13:16
  • Your code appears to be correct. Perhaps the path to the images isn't right? Also, ensure you are calling the function using an index. touch(0) for instance Commented Jun 1, 2015 at 13:18

2 Answers 2

1

What's not working? I can see what you're trying to achieve, but there're probably better solutions. Anyway, this should work for what you're trying to do:

function touch(index) {
   var images = ["Data/Images/heroim-banner.png", "image3.png", "image1.png"];
   var page = $('#page');

   page.css('background-image', 'url("' + images[index] + '")');

}

The backwards slashes were probably the cause. Also, make sure those links are correct.

Sign up to request clarification or add additional context in comments.

Comments

1

I've prepared jsfiddle

I would like make some comments to your code:

  • you should use url like this "Data/Images/heroim-banner.png", because \ this is sybmol for screened.
  • if you set "Data/Images/heroim-banner.png" in this case it means that "<executable path>/Data/Images/heroim-banner.png". If "/Data/Images/heroim-banner.png" in that case it will be "<root>/Data/Images/heroim-banner.png". Please check path where contains your image.
  • also you should execute this code touch(0) (see my jsfiddle)
  • if you want select your elements from array by index parameter, so you should do it like this:

page.css('background-image', 'url(' + images[index] + ')');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.