Reputation: 3481
E.g html:
<DIV>Here is some text..</DIV>
<DIV><IMG src="image1.png">one</DIV>
When user clicks on the image (image1.png) I want to change the image to image2.png?
How can I do this with plain javascript?
Thanks
Upvotes: 0
Views: 304
Reputation: 86872
<DIV>Here is some text..</DIV>
<DIV><IMG id="image1" src="image1.png">one</DIV>
<script type="text/javascript">
window.onload = (function(oldLoad) {
return function() {
oldLoad && oldLoad();
// wire up image event handler
document.getElementById("image1").onClick = function() {
this.src = "image2.png";
}
}
})(window.onload)
</script>
Edit - After my comment:
There are times where many people cannot utilize the power of jQuery. The OP wanted to know in his comment what the purpose of the oldLoad was and I wanted to provide a detailed answer.
Basically what I have written here is something "similar" to jQuery's $(document).ready(). and Here is how I would utilize this example.
<script type="text/javascript">
var Core = {
windowLoadEvent: function(oldLoad, newLoad) {
return function() {
//check if the window.onload already has a function attached if so then execute
oldLoad && oldLoad();
//check if the newload has a function attached if so then execute
newLoad && newLoad();
},
myNewLoadEvent: function() {
document.getElementById("image1").onClick = function() {
this.src = "image2.png";
}
//wireup whatever else is needed.
}
}
window.onload = Core.windowLoadEvent(window.onload, Core.myNewLoadEvent)
</script>
Upvotes: 1
Reputation: 133403
Just use
<IMG src="image1.png" onclick='this.src="image2.png"'>
Pure JS
document.getElementById('img').onclick=function() {
this.src='image2.png';
};
Upvotes: 2
Reputation: 146191
You may also try this (Example)
HTML:
<div id="images">
<div><IMG src="image1_url" />one</div>
</div>
JS:
var images = document.getElementById('images');
images.onclick = function(e){
var event = e || window.event;
var target = event.target || event.srcElement;
target.src="image2_url";
};
Upvotes: 0
Reputation: 61053
<img ... onclick="this.src = 'image2.png'" />
In response to your comment, I don't have a pure JS click handler for you, but with jQuery it would look like this:
$('img').click(function() {
$(this).attr('src', 'image2.png');
});
Upvotes: 1