javascripthtmlcssvisual-web-developer

Animation doesn't work on Javascript because of onmousedown


My script doesn't work. I tried to make it change css style on mouse over but its not working

const robert = document.getElementById('robert');

function animationOver() {
    robert.style.margin = '0.8rem 2.7rem 1.2rem 0rem';
    robert.style.boxShadow = '0 0 0 #f1faee';
    robert.style.transition = '0.5s';
}

function animationOut() {
    robert.style.margin = '0rem 3.5rem 2rem 0rem';
    robert.style.boxShadow = '0.8rem 0.8rem #e63946'
    robert.style.transition = '0.5s'
}

robert.onmouseover = animationOver();
robert.onmouseleave = animationOut();

I'm new to programming so I don't know what else to try.


Solution

  • I think it doesn't work because you're assigning to the result of calling your functions, not functions themselves.

    What you're doing is saying "when user hovers mouse - use whatever my function returns" which is nothing, so it doesn't make much sense.

    Instead, you need to do "when user hovers mouse - call my function"

    And you do it like so:

    robert.onmouseover = animationOver;
    robert.onmouseleave = animationOut;