Jump to content

Using onclick to change an image


Lorne

Recommended Posts

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

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

  • 3 months later...
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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...