/    Sign up×
Community /Pin to ProfileBookmark

[RESOLVED] How to change an image by its id using javascript

Hi all,
I’m a bit of a noob with javascript and was wondering if someone could take a look at my code and tell me how I can apply this to individual objects on a page.
What it is trying to do is swap out a plus symbol with a minus symbol when a div is clicked on. I can get this to work for one instance but I was wondering how I could apply this to multiple images (each working seperately)?

intImage = 2;

function swapImage() {
switch (intImage) {
case 1:
IMG1.src = “Images/minussymbol.gif”
intImage = 2
return(false);
case 2:
IMG1.src = “Images/plussymbol.gif”
intImage = 1
return(false);
}
}

This works for one instance in my html code:

<div class=”mH” onclick=”toggleMenu(‘menu1’)”><IMG id=”IMG1″ name=”IMG1″ src=”plussymbol.gif” onclick=”swapImage();” ></img> UT2004:</div>

How can I roll this out (I’m guessing using getElementById) to lots of elements similar to this so that if any one of the symbols is clicked on that instance alone will change to a minus symbol?

Sorry if this is unclear.

Thanks in advance.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@hyperionXSMar 18.2012 — Try this code. As you can see, you can use it multiple times, for many images.
[CODE]
<script type="text/javascript">
function swapImage(elm) {
var possibleValues = ['minussymbol.gif', 'plussymbol.gif']
if(elm.dataUser){
elm.src = possibleValues[1]
elm.dataUser = 0;
}
else{
elm.src = possibleValues[0]
elm.dataUser = 1;
}
}
</script>
<div class="mH" onclick="toggleMenu('menu1')"><img src="plussymbol.gif" onclick="swapImage([COLOR="Red"]this[/COLOR])" />UT2004:</div>
<div class="mH" onclick="toggleMenu('menu1')"><img src="plussymbol.gif" onclick="swapImage([COLOR="Red"]this[/COLOR])" />UT2004:</div>
<div class="mH" onclick="toggleMenu('menu1')"><img src="plussymbol.gif" onclick="swapImage([COLOR="Red"]this[/COLOR])" />UT2004:</div>
[/CODE]

[COLOR="red"]dataUser[/COLOR] is an arbitrary attribute, not a standard, used just to help you achieve your goal.
Copy linkTweet thisAlerts:
@SatchelmouthauthorMar 18.2012 — Thanks Hyperion,

that worked perfectly!

Best wishes!
×

Success!

Help @Satchelmouth spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.18,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...