Search code examples
javascripthtmlimagehyperlinktap

How can a image be switched when a link is tapped?


The image should be changed as soon as the link is tapped. How can I realise this with javascript and html? I have tried and gathered information and come up with the code

    <script type="text/javascript">
      function changeImage(element) {
      document.getElementById('imageReplaceTel').src = element;}
    </script>

<a href={{callphonenumber}} style="color:white" onclick="changeImage({{asset('bundles/testProject/images/telephoneSelected.png')}})">
    <img src="{{asset('bundles/testProject/images/telephone.png')}}" width="54px" height="54px" id="imageReplaceTel" alt="Images"></img></a>

I was hoping this would work but it failed, I might be missing something as I am a beginner with javascript. Thanks


Solution

  • using javascript and html it would look like this

    <script type="text/jscript">
    function Changetheimage() {
        document.getElementById("img1").src = "imagefoldername/Imagename2.jpg";
    }
    </script>
    </head>
    <body>
    <a onclick="Changetheimage()">click here</a>
    <img src="imagefoldername/Imagename1.jpg" id="img1" alt="" />
    

    Notes: "Img1" must be replaced with the id of the image you want to change "imagefoldername/Imagename2.jpg" in the javascript must be changed to the directory of the new image you want to display and "imagefoldername/Imagename1.jpg" must be changed to the image currently displaying