Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change picture in HTML using multiple buttons

I am going to have 5 images and 5 buttons, currently only the single button. On button click I would like to show only the image that is associated with the button. for that I would like to write single function that gets the image path as parameter. I am very new to JavaScript, Bellow is a code I found and edited a bit:

<script>
    function pictureChange(path) {
        console.log(path);
        document.getElementById("theImage").src=path;
    }
</script>
<body>
    <img id="theImage" src="http://31.media.tumblr.com/18b5f8f0a00ad01e50f7ae2f513be52d/tumblr_msqcl4iwM01soh1p8o1_500.png">
    <p><input type="button" id="theButton" value="click me!" onclick="pictureChange("http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png")"></p>
</body>
like image 333
Tamir Einy Avatar asked Dec 23 '22 14:12

Tamir Einy


1 Answers

Currently issue in you code is, when you passing string in function you need to the sequence of inverted comma's. for example while using "", you can use only '' single inverted comma's inside of it.

<script>
function pictureChange(path) {
console.log(path);
document.getElementById("theImage").src=path;
}
</script>
<body>
<img id="theImage" src="http://31.media.tumblr.com/18b5f8f0a00ad01e50f7ae2f513be52d/tumblr_msqcl4iwM01soh1p8o1_500.png">
<p><input type="button" id="theButton" value="click me!" onclick="pictureChange('http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png')"></p>
</body>

for showing 5 images, you can use single button too. As per you requirement, you can create array of images sources and pass index on button click, as well as you can do the same which you were doing in your current snippet i.e passing source on button click.

Also, for single button what you can do is pass image src and find the index of that src index in array, from that index you change to next index and assign source to your image element. Please make sure to check if you are in last index than src at 0 index will get assigned, otherwise you will get stuck in error.

updated snippet: css display: inlne-block property will help you. also you need to change the width of image, because by default it

img {
  width:85%;
}
p {
  display: inline-block;
}
<script>
function pictureChange(path) {
console.log(path);
document.getElementById("theImage").src=path;
}
</script>
<body>
<img id="theImage" src="http://31.media.tumblr.com/18b5f8f0a00ad01e50f7ae2f513be52d/tumblr_msqcl4iwM01soh1p8o1_500.png">
<p><input type="button" id="theButton" value="click me!" onclick="pictureChange('http://31.media.tumblr.com/fca646cd8fe87906e605ad7e8d039903/tumblr_mmoz4fWT6U1soh1p8o1_500.png')"></p>
</body>
like image 93
sumit chauhan Avatar answered Dec 28 '22 11:12

sumit chauhan