Reputation: 1
I have a row of six buttons on a web page. Each button makes an image appear elsewhere on the page. Click button one, and image number one appears. Click button two to replace image number one with a transparent (invisible) png and make image number two appear. And so on.
If it sounds like an image gallery, it is indeed very similar.
My script works fine, but I suspect it's not efficient or elegant because I've attached a bulky function to each button. Would a for loop do the job better?
Here's the javascript for the first button. This is repeated six times :-(
function swapSegment1() {
var image = document.getElementById("img1")
image.src = "images/frag1a.png"
var image2 = document.getElementById("img2")
image2.src = "images/frag2b.png"
var image3 = document.getElementById("img3")
image3.src = "images/frag3b.png"
var image4 = document.getElementById("img4")
image4.src = "images/frag4b.png"
var image5 = document.getElementById("img5")
image5.src = "images/frag5b.png"
var image6 = document.getElementById("img6")
image6.src = "images/frag6b.png"
}
frag1a.png is a visible image. frag2b, frag3b etc are invisible images.
I hope this is clear. Please probe for clarity if needed...
Upvotes: 0
Views: 221
Reputation: 1
Uses the ternary operator for the a/b logic
function swapSegment1()
{
for (var i = 1; 1 < 6; i++)
{
(document.getElementById) ('img' + i).src = 'images/frag' + i + (i === 1 ? 'a' : 'b');
}
}
Upvotes: 0
Reputation: 25164
With no loops but using recursion:
function swapSegment(i){
var img = document.getElementById('img' + i);
img.src = 'images/frag' + i + (i > 1 ? 'b':'a') + '.png';
--i && swapSegment(i);
}
swapSegment(6);
Upvotes: 2
Reputation: 6941
Since you are working with strings you can easily append a number:
function swapSegment(index) {
for (var i = 1; i <= 6; i++) {
if (index == i)
document.getElementById("img" + i).src = "images/frag" + i + "a.png";
else
document.getElementById("img" + i).src = "images/frag" + i + "b.png";
}
}
This could be reduced even further, but hey, this is still readable.
Upvotes: 2
Reputation: 32831
function swapSegment1() {
var image = document.getElementById("img1");
image.src = "images/frag1a.png";
for (var i = 2; i <= 6; ++i) {
image = document.getElementById("img" + i);
image.src = "images/frag" + i + "b.png";
}
}
Upvotes: 1