1

I have to create a javascript code which calls different images on the click of an image button. I have given names to the images as product1, product2, product3. I am new to JavaScript.

var count;
document.getElementById("divProduct").style.backgroundImage="url('images/product'+count)";

I am trying the above code, but it's not working

4 Answers 4

2

If you look at the syntax highlighting, + count is being treated as a string.

You put it outside of the single quotes (kind of), but you still need to put it outside of the double quotes, which are the quotes you're really using to delimit the string:

document.getElementById("divProduct").style.backgroundImage="url('images/product" + count + "')";
Sign up to request clarification or add additional context in comments.

Comments

0

You are also missing the image extension. It should be .png or .jpg or something else depending on whatever type your image is.

Also I'd like to know if you are getting any errors on the console.

Edit : For those looking for answers to this question, please also check blender's reply below mine.

1 Comment

I was getting an undefined reference error on the console because i had not given the proper attribute to the script tag. I had typed <script language="javascript" type="text/javascript"> , on correcting it to <script type="text/javascript"> it worked. I was also missing the image extensions.
0

Your code should be like Blender said and still if it doesn't work add   in you div sample:

<div id="divProduct">&nbsp;</div>

Comments

0

I think it must be like;

var count;
document.getElementById("divProduct").style.backgroundImage="url('images/product" + count + ".jpg')";

Comments

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.