I’m trying to set a background-image in a div to change every second or two with the setTimer(); I set it up and it’s saying that I have
'Invalid left-hand side in assignment'
Not sure what I’m doing that’s wrong. Can someone help out please?
<html><body>
<div class="box">
<div id="b1"></div>
</div>
<input id = 'spin' type="button" value="Spin" onclick='changeIcons()' />
<script>
var arr = new Array();
arr[0] = '1.png';
arr[1] = '2.png';
arr[2] = '3.png';
var first = document.getElementById('b1');
function changeIcons(){
for(var spinIcons= 0; spinIcons < 10; spinIcons++){
arr.sort(function() {return 0.5 - Math.random()});
var v1 = setTimeout(function(){first.style.background-image= 'url(arr[0])'}, 1000);
}
}
</script>
</body>
</html>
THIS FINALLY ENDED UP WORKING, IT HAS TIMING ISSUES AND i NEED TO MAKE A FRAMED PLACE HOLDER FOR THE BACKGROUNDIMAGES BUT IT’S WORKING:
<div class="first"></div>
<script>
for(var i=0; i<11; i++){
$("div.first").slideUp(300).delay(100).fadeIn(400);
}
</script>
THANKS TO T.J.CROWDER FOR SETTING ME STRAIGHT!!!
There are two problems.
The one causing the error you mention is here:
That makes the engine think you’re trying to assign to the result of an expression (
background - image), which is invalid on the left-hand side of an assignment. In JavaScript, property names can’t have dashes in them. You can use the camelCase versionbackgroundImageinstead.Separately, you’re always setting the background image to the string
'url(arr[0])', not putting the value fromarr[0]in the string. You need to adjust the quotes:So:
Some other notes:
You’re setting up the
setTimeoutin a loop, so you’re scheduling this to happen 10 times. But those 10 times will all happen one right after another, one second later, and they’ll all do exactly the same thing: Set the background image to whatever’s inarr[0]at that time. The fact you’re changing the order of the array 10 times previously makes no difference, because the function doesn’t receive a copy of the value ofarr[0]as of when you schedule it, it receives an enduring reference to the array, which it uses when it runs. More: Closures are not complicatedSorting the array and using index 0 seems a fairly inefficient way to pick from the array randomly.