I'M trying to do something like this:
<div id="div1">
<span onClick="change(1)"><img src="/graphics/pic1.png" /></span>
<span onClick="change(2)"><img src="/graphics/pic2.png" /></span>
<span onClick="change(3)"><img src="/graphics/pic3.png" /></span>
<span onClick="change(4)"><img src="/graphics/pic4.png" /></span>
<script language="javascript">
function change(a) {
$("#div1").css("background", "url('/graphics/pic"+a+".png')");
}
</script>
</div>
But there comes problem... It doesn't work... Did I get it right? I mean the thing with numbers and the "a"? Or I'm totally wrong? This code was just an example...
2 Answers 2
Please use it like this:
<script language="javascript">
function change(a) {
var url_img = 'url(/graphics/pic' + a + '.png)';
$("#div1").css("background", url_img);
}
</script>
Comments
To show that your code works I've run a little sample here using colors since I don't have the images. Here you can see that your code does work, although I think it could be written better (if you want to see how I'd do it just let me know). As this is functioning my theory of why it's not working for you is either that
a) Your path to the images is not correct. Make sure that your path is correct and if you need to move out one folder start by using .. before /graphics
e.i. ../graphics/pic3.png
b) The second error could be that you haven't actually installed jQuery. Follow this link to see how to install it on your website.
I hope this solves your problem, let me know if it makes sense or if you have any questions.
Working code below:
function change(a) {
$("#div1").css("background", a);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="div1">
<span onClick="change('green')"><img src="/graphics/pic1.png" /></span>
<span onClick="change('yellow')"><img src="/graphics/pic2.png" /></span>
<span onClick="change('red')"><img src="/graphics/pic3.png" /></span>
<span onClick="change('brown')"><img src="/graphics/pic4.png" /></span>
</div>
urlnotsrc.