/    Sign up×
Community /Pin to ProfileBookmark

How to make buttons interact with images.

I’m a noobie to javascript in general. The question that I can’t seem to wrap my head around is how I can’t make these buttons interact with a particular image. Here is my code:

[CODE]<html>
<head>
<title>Moving Images</title>
</head>
<body>

<img src=”me.png” name=”changePic” alt=”That’s me!”>

<script language=”javascript” type=”text/javascript”>
var changingImage = new Image();
changingImage.src = “me.png”;

function changeImage() {
changingImage.setAttribute(“src”, “me2.png”);
}

</script>

<input type=”button” value=”Change Image” onClick=”changeImage()” class=”run_button”>

</body>
</html>
[/CODE]

I want to make it so that the “Change Image” button changes the .src variable of myImage. For some reason, it won’t change the data for the image. Can anyone help?

to post a comment
JavaScript

3 Comments(s)

Copy linkTweet thisAlerts:
@idungotnosnauthorMay 29.2011 — I revised the code a little bit. Still doesn't work though. Any help?

[CODE]<html>
<head>
<title>Moving Images</title>
</head>
<body>

<img src="me.png" name="changePic" alt="That's me!">

<script language="javascript" type="text/javascript">
var changingImage = getElementByName("changePic");
changingImage.src = "me.png";

function changeImage() {
changingImage.setAttribute("src", "me2.png");
}

</script>


<input type="button" value="Change Image" onClick="changeImage()" class="run_button">

</body>
</html>
[/CODE]
Copy linkTweet thisAlerts:
@ToubsMay 29.2011 — [B]document.[/B]getElement[B]s[/B]ByName()
Copy linkTweet thisAlerts:
@krieyaMay 30.2011 — Replace the below code:
<script language="javascript" type="text/javascript">

var changingImage = new Image();

changingImage.src = "me.png";

function changeImage() {
changingImage.setAttribute("src", "me2.png");
}


</script>
[/QUOTE]


With this
[CODE]<script language="javascript" type="text/javascript">
function changeImage() {
document.getElementsByName("changePic")[0].setAttribute("src", "me2.png");
}

</script>[/CODE]
×

Success!

Help @idungotnosn 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 6.16,
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: @nearjob,
tipped: article
amount: 1000 SATS,

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

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...