When and why use :Hover and onMouserOver and onMouseOut?

Asked

Viewed 352 times

1

I’m studying about :Hover, onMouseOver and onMouseOut. Suppose in this situation I want to change the background of an image when passing the mouse on top of her.

What is the correct way to program? It’s using CSS (:Hover) or through Javascript (onMouseOver and onMouseOut)? Because?

<div id="img1">
    <img src="https://vignette.wikia.nocookie.net/unmario/images/a/ad/300px-Nsmb-mushroom-super.jpg/revision/latest?cb=20081217191119">
</div>

<div id="img2">
    <img src="https://vignette.wikia.nocookie.net/unmario/images/a/ad/300px-Nsmb-mushroom-super.jpg/revision/latest?cb=20081217191119">
</div>

  • 1

    CSS whenever possible. A question: this application will be used on tablets or phones?

  • Yes, the user will be able to access through the phone ! So it is good to avoid javascript right?

  • 1

    So it’s good to avoid this functionality :) Describes how you would do :hover or mouseover did not exist.

  • Vish, would do something like leave two images superimposed and one becomes invisible or something like kkkk (if there was no mouseoveror :hover)

2 answers

3

CSS should be used to handle layout and Javascript the logical part.

Whenever possible choose to use CSS. Please use Javascript in cases where Features CSS can’t meet your needs and may need to add functionality (polyfills) - you can use the Can I use to check the status features in the browsers.

Also consider that there are users who completely disable Javascript in the browser, there are those who use extensions that allow JS only on specific pages. Using only CSS is a guarantee that you have that your page will be displayed in the same way for all users.

  • Pow, I understood perfectly !! Thanks for the reply @Renan !! was of great help

2


This will depend on the effect you want to do, if you want it to simply change the image and nothing else, use the Hover in css, so the application will be lighter, if you want a custom Hover, the fade will take longer or something like that, use the css too, is the same case, the application will be lighter.

But if you are thinking of compatibility with older browsers, then use a javascript script.

  • Got it @Wictor, thanks for the explanation !!

  • Hover can change the image inside a div?

  • (7 minutes to accept the answer)

  • 1

    Change image src not, but you can put this image as background so you can change using css.

  • All right, I’ll try to get in here and study, thanks !!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.