Click here to Skip to main content
16,004,653 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I've been trying to create a mini image gallery which has an img tag for the main picture called "defaultPic" and another two img tags for the sub images called "subPic1" and "subPic2". So basically the default picture is subPic1, what I want to happen is when the user click subPic2, the image in defaultPic should be replaced by subPic2 vice versa. The bigger box is the default picture meanwhile the smaller one's are subPic1 and subPic2. I've tried adding an onclick event to the sub images that when clicked, it will retrieve the image source and will be passed on to the default picture. But when I tried clicking lets say subPic2, the onclick event is not firing and nothing happens. Kindly help me on solving this one or provide better solutions to achieve the same goal.

What I have tried:

Here is the html script:

HTML
<html>
  <head>
     <title>TEST</title>
 <link rel="stylesheet" type="text/css" href="style.css"/>
 <script src="Image1.js"></script>
 <script src="Image2.js"></script>
  </head>

  <body>
    <img id="defaultPic" src="microsoftLogo1.jpg" /><br/>
    <img id="subPic1" src="microsoftLogo1.jpg" 
                  onclick="getImage1()"/><br/>
    <img id="subPic2" src="microsoftLogo2.jpg" 
                  onclick="getImage2()"/>
  </body>

</html>


Here is the css:

CSS
*{
margin: 0;
padding: 0;
 }

 #defaultPic {
border: 1px solid black;
margin: 5px;
width: 200px;
height: 200px;
 }

 #subPic1{
border: 1px solid black;
margin: 5px;
width: 50px;
height: 50px;
  }

  #subPic2{
border: 1px solid black;
margin: 5px;
width: 50px;
height: 50px;
  }


Here is the javascript code:

JavaScript
function getImage1(){
var img = document.getElementById("subPic1").src;
document.getElementById("defaultPic").src = img;
}

function getImage2(){
var img = document.getElementById("subPic2").src;
document.getElementById("defaultPic").src = img;
 }


CSS
</<pre lang="CSS"><pre lang="CSS"><pre lang="CSS">
pre>
Posted
Updated 5-Sep-17 1:14am

1 solution

to be honest I can't see what's wrong with your code, but here a working sample on JSFiddle: Edit fiddle - JSFiddle[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900