Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delay GIF until onclick (CSS/Javascript)

I have a gif that loads once (i.e gif doesn't loop) when a button is clicked. This is used to signify that a user has successfully copied their serial number as shown in this screenshot:

View Image

I have set this up using the following code, CSS:

.greentickactive {
    visibility: hidden;
}

JS:

    <script>
document.getElementById("copyButton2").onclick = function() {
    document.getElementById("greentickactive").style.visibility = "visible";
}
</script>

With 'greentickactive' as the gif CSS class and 'copyButton2' representing the trigger for the state change. This is all working, but the gif must be loading when the page loads (I am presuming as I can't see it on load), and I need it to only load when the button (copyButton2) is clicked. I tried replacing;

document.getElementById("greentickactive").style.visibility = "visible";

with

document.getElementById("greentickactive").style.display = "block";

and amending the CSS to;

.greentickactive {
    display: none;
}

but this causes spacing issues on the page and still doesn't allow the gif animation to play at the correct time. Does any one know of another method to achieve this or maybe something that's wrong with this setup?


1 Answers

You can defer the loading of the image until copy is clicked, and to handle the spacing issues, just set the height & width of the element.

Assuming you have the following css for .greentickactive:

.greentickactive {
    width: 64px;
    height: 64px;
    display: inline-block;
    background-color: transparent;
    background-repeat: no-repeat;
 }

you can then change your javascript to:

document.getElementById("copyButton2").onclick = function() {
    document.getElementById("greentickactive").style.backgroundImage = 'url("/path/to/image/greentick.gif")';
}

Let me know how that works out for you.

like image 194
kennasoft Avatar answered Apr 09 '26 07:04

kennasoft