0

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.

  • can you clarify how onmousedown is related to your question? – Maxim Mazurok Oct 28 '22 at 01:01
  • 1
    Use the [addEventListener](https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener) method and pass your events in a loop, compare the `type` of event and set your styles using a conditional depending on `mouseover`, `mouselease` – dale landry Oct 28 '22 at 02:19

2 Answers2

0

Here's a purely css version. Not sure if this is what you were looking for. There are reasons why you might want to use javascript for mouseover/out effects, but the example you provided is easily enough accomplished without it.

#robert {
  width: 100px;
  height: 100px;
  background: #222;
  transition:  0.5s;
  margin: 0rem 3.5rem 2rem 0rem;
  box-shadow: 0.8rem 0.8rem #e63946;
}

#robert:hover {
  margin: 0.8rem 2.7rem 1.2rem 0rem;
  box-shadow: 0 0 0 #f1faee;
}
<div id='robert'></div>
Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • After I stop hovering my mouse, the animation drops back instantly, and I read online that I should create it in javascript – Robert Csokmai Oct 28 '22 at 00:22
0

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;
Maxim Mazurok
  • 3,856
  • 2
  • 22
  • 37
  • it still doesn't work, I tried it too – Robert Csokmai Oct 28 '22 at 00:26
  • @RobertCsokmai seems to work for me: https://jsfiddle.net/6ksqbjLz/ – Maxim Mazurok Oct 28 '22 at 01:00
  • @RobertCsokmai Use the [browser console (dev tools)](//webmasters.stackexchange.com/q/8525) (hit `F12`), read any errors. Is your ` – Sebastian Simon Oct 28 '22 at 03:38