0

I'm new to Javascript and I am trying to simplify my life by integrating many functions into one.

I have a very simple operation which allows for the click of a button to load a specific image in place of a default image. As oppose to having many functions which do the same thing, I'd rather have just one.

I imagine you can store the images in an array and select them by position?

Here is what I have so far.

function swap1() {
  document.getElementById("default").src="321.jpg";
}

function swap2() {
  document.getElementById("default").src="432.jpg";
}

function swap3() {
  document.getElementById("default").src="742.jpg";
}

 

<input type="button" onClick="swap1()">
<input type="button" onClick="swap2()">
<input type="button" onClick="swap3()">

2 Answers 2

6

use function parameters:

function swap(imgNumber)
{
document.getElementById("default").src=imgNumber+".jpg";
}

and later:

<input type="button" onclick="swap('321')">
<input type="button" onclick="swap('432')">
<input type="button" onclick="swap('742')">

To answer the comment (not very best js code but to show idea of variables):

var clip=false;
function setClip(val) {
   clip=val;
}
function swap(imgNumber)
{
   if(clip==true)
     document.getElementById("default").src=imgNumber+"clip.jpg";
  else
     document.getElementById("default").src=imgNumber+".jpg";
 }


<input type="button" onclick="swap('321')">
<input type="button" onclick="swap('432')">
<input type="button" onclick="swap('742')">
<input type="button" onclick="setClip(true)">

Simply you add variable which takes true/false - last button set clip variable to true - we changed swap function to check if clip is true - if yes - it loads different file

Sign up to request clarification or add additional context in comments.

1 Comment

This worked perfectly. I have one additional question if I may. Basically I am using this to display satellite imagery which has undergone specific classifications. The images are all stored as .jpg. The user has the ability (as you are already aware) to click on separate buttons, 321, 432, 742. Is it possible to add one additional button which if clicked after one of the proceeding buttons would load either (321clip.jpg, 432clip.jpg, 742clip.jpg) ? Sort of like a sequential chain of events?
2

You could do this

JS

function swap(string img)
{
    document.getElementById("default").src=img;
}

HTML

<input type ="button" onClick="swap('321.jpg')">
<input type ="button" onClick="swap('432.jpg')">
<input type ="button" onClick="swap('742.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.