Home > Blockchain >  How do I change img size on click, and return it to normal on toggle using javascript?
How do I change img size on click, and return it to normal on toggle using javascript?

Time:10-21

I want an image in an html file to change in size by 50% and toggle back to normal size on a second click. I tried to do it the same way I do onm ouseover but it's not working. Does anyone have any ideas on how to do this in javascript?

html code -

   <article id="featuredartists">
        <h2>Featured Artists</h2>
        <div class="artistlist group">
            <ul class="group">
                <li><img src="images/artists/Barot_Bellingham_tn.jpg" alt="Photo of Barot Bellingham" onclick="func3()"></li>
            </ul>
        </div>
    </article>

external javascript -

    function func3() {
       x = document.getElementsByTagName("img")[11];
       x.height = 50%;
       x.width = 50%;
    }

CodePudding user response:

Here's a much simpler example making use of transforms. Just toggle a class on click.

document.querySelector("img").addEventListener("click", function(){
  this.classList.toggle("half");
});
img
{
  transition-duration: 0.4s;
}

img.half
{
  transform: scale(0.5);
}
<img src="https://via.placeholder.com/100x100"/>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

If you really want it to change the size of the element and the flow, then you can just change the width/height inside the .half class.

Show code snippet

document.querySelector("img").addEventListener("click", function(){
  this.classList.toggle("half");
});
img
{
  transition-duration: 0.4s;
  width: 100px;
  height: 100px;
}

img.half
{
  width: 50px;
  height: 50px;
}
<img src="https://via.placeholder.com/100x100"/>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related