0

While working on the project at work, I was told to implement below JS code in CSS class rather than JS function:

function onMouseOver(e : any) {
     e.target.style.textDecoration = 'underline';
}

function onMouseLeave(e : any) {
    e.target.style.textDecoration = 'none';
}

What is the trade-off between two of them and why one of them should be preferred over another.

Short: why shouldn't I create mouseOver class in React but use CSS class? Does it take long time to implement JS function over CSS hover?

4
  • what is exactly issue, do you need css code for mouse hover. give little bit more idea Commented Nov 15, 2022 at 6:46
  • 1
    I think what they might have requested you to do is to use a hover pseudo-class instead of using Javascript. Commented Nov 15, 2022 at 6:56
  • Who so ever suggested this wants to keep the JavaScript engine free for other important work. That's all. Commented Nov 15, 2022 at 6:57
  • 2
    You should use CSS for things that CSS is built to do because it's more efficient and less error prone; it works even if javascript is disabled. It's more easily adapted to different devices and capabilities. The browser is optimized for it. And there's no need for javascript. You should use javascript only when you can't do what you need to do without it. You can apply the effect everywhere with CSS without JS having to attach listeners. Commented Nov 15, 2022 at 6:57

1 Answer 1

2

The reason why CSS is preferred over JS wherever the trade can be offered is simple.

  1. CSS works on the fly and is 10x faster than Javascript.
  2. Event listeners are functions, functions that are called every single time the event is performed. Compare that to what CSS does, :hover is a default HTML property that can be customized using CSS.

tl;dr

CSS :hover, :focus, and all the other such selectors modify the default HTML behaviour, whereas Javascript event listeners add additional functionality to existing HTML nodes. The trade-off is tremendous as soon as scalability is the subject.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.