CSS Animations Onclick

5.7k views Asked by At

Using regular JS (not JQuery) I am trying to make some images shake after they are clicked but it is not working.

HTML:

    <img id='s1_imgB' class="fragment"... onClick="wrongAnswer()"...

JS:

    function wrongAnswer(){ 
        document.getElementById("s1_imgB").style.className = "shake";

CSS:

    .shake:hover {....

I can get the elements to shake by default using the following html. But, I want to have the CSS animation initiate after the image is clicked.

HTML:

    <img id='s1_imgB' class="fragment shake"....

When the page loads, the mouse hover affect should be inactive, then after the image is clicked, the mouse hover should cause the image to shake.

What am I doing wrong? Thanks

5

There are 5 answers

0
Björn On BEST ANSWER

I think it should be

document.getElementById("s1_imgB").className += " shake";
1
Ahmed Beheiry On

I think it should be like that:

function wrongAnswer(){ 
document.getElementById("s1_imgB").className = "shake";

without (.style )

0
T Mitchell On

You should remove the :hover identifier in your css, as it may only apply those styles after you have clicked the image and then move the mouse to trigger a hover. You would also then get the shake every time you mouseover the image. Adding the class (without hover) with JS should apply the shake styles.

You may also want to append the shake class, at the moment you are replacing fragment with shake. But it's unclear if you need to do that based on the info you've supplied.

document.getElementById("s1_imgB").className += " shake";
0
Gehtnet On

Just add the class that do the shaking-animation, when the image is clicked. Basically it is just one line:

document.getElementById('s1_imgB').classList.add("shake");

To remove the class just do:

document.getElementById('s1_imgB').classList.remove("shake");

Here is a jsfiddle that does this.

The shaking animation is from this site.

I hope I helped you.

0
Honza P. On

For me the solution was a bit more tricky (togle style ON, wait a bit and then turn it OFF again so that image shakes every time I click it, not only the first time):

            var es = document.getElementById("img");
            if (es != null) {
                es.classList.toggle("shakeit");
                setTimeout(() => (es.classList.toggle("shakeit")), 550)
            }