Reputation: 3512
I have a button that adds one word to the words
variable. When the array is at certain lengths I want an image's src
to change depending on the array length. Can't seem to get it to work.
var words = [];
var str = words;
for (var i = 0; i < str.length; i++) {
if (str[i].length === 1) {
img.src = "http://placehold.it/350x150"
if (str[i].length === 2) {
img.src = "http://placehold.it/200x150"
}
}
}
Upvotes: 1
Views: 68
Reputation: 4336
Assuming you want to dynamically change the image at certain breakpoints, you will also have to register a callback on your button to determine if an update is needed.
var words = [];
$(button).click(function() {
words.push("whatever");
var img = // get img here
if (words.length === 1) {
img.src = "http://placehold.it/350x150";
} else if (words.length === 2) {
img.src = "http://placehold.it/200x150";
}
// etc
});
Edit: Here is a fiddle so you can see it working https://jsfiddle.net/4273v7c7/
Upvotes: 1
Reputation: 414
As Oriol commented, "Nesting if(str[i].length === 2)
in if(str[i].length === 1)
is useless."
It should be:
var words = [];
var str = words;
for (var i = 0; i < str.length; i++) {
if (str[i].length === 1) {
img.src = "http://placehold.it/350x150";
}
else if (str[i].length === 2) {
img.src = "http://placehold.it/200x150";
}
}
Upvotes: 0
Reputation: 5955
You don't need a loop for that.
var words = [];
var str = [0,"http://placehold.it/350x150", "http://placehold.it/200x150", ... ];
img.src = str[words.length] || img.src;
This will do the job.
Upvotes: 0
Reputation: 1435
you are verifying the length of the position, you need to verify the array directly:
if (words.length === 1) {
img.src = "http://placehold.it/350x150"
} else if (words.length === 2) {
img.src = "http://placehold.it/200x150"
}
for that case you don't need a loop
Upvotes: 3