Lorne Posted October 24, 2019 Share Posted October 24, 2019 I have several images that show different results of an event. I want my page to load with image1 visible, the rest hidden, and the user to be able to click text under the image to hide what is visible and show another image in its place. The image is in a table but does not have to be. This is my failed attempt to try and get it to work with 2 images: in my html body: <table style=" max-width: 792px"> <tr> <th> <img alt="Image not found" id="mygraph" border="0" src="Images/Graphs.gif" width="100%" height="auto"> <img alt="Image not found" id="myfilter" border="0" src="Images/GraphFilter.gif" width="100%" height="auto" style="display:none"> </th> </tr> </table> <p>Click <a onclick="SwapImage()" href="#">here</a> to swap image</p> and the javascript function executed by the click: function SwapImage(){ document.getElementsById("mygraph").style.visibility = 'hidden'; document.getElementsById("myfilter").style.visibility = 'visible'; } but the javascript does nothing. I also tried display instead of visibility none or block with no success. The first image shows up with the second hidden but does not change when clicking the text. Can anybody help ? Link to comment Share on other sites More sharing options...
Lorne Posted October 24, 2019 Author Share Posted October 24, 2019 Thought I had better add that I also tried (without success) just loading the first image with onclick executing the following code via ChangeImage('Images/GraphFilter.gif'): function ChangeImage(imgName){ var image = document.getElementsById('mygraph'); image.src = imgName; } Link to comment Share on other sites More sharing options...
Lorne Posted October 24, 2019 Author Share Posted October 24, 2019 OK - solved it. You have to use the full file path from the web server root to the image rather than the relative path from the folder with the html code to the folder with the images. This function now works. Link to comment Share on other sites More sharing options...
Makwana Prahlad Posted February 4, 2020 Share Posted February 4, 2020 Hello,@Lorne Please try this code, How to change image using onclick: <!DOCTYPE html> <html> <head> <title>onClick Demo</title> </head> <body> <script> function toggleImage() { var img1 = "http://placehold.it/350x150"; var img2 = "http://placehold.it/200x200"; var imgElement = document.getElementById('toggleImage'); imgElement.src = (imgElement.src === img1)? img2 : img1; } </script> <img src="http://placehold.it/350x150" id="toggleImage" onclick="toggleImage();"/> </body> </html> I hope above code will be useful for you. Thank you. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now