Arishorts
Arishorts

Reputation: 1

Changing an HTML Class with Hover Pseudo Class CSS

I'm newish to HTML/CSS (~2 months overall) and stack overflow (first post). Using fontawesome.com my idea is to make this icon flip when the cursor hovers over it. The icon flips when the class includes 'fa-flip' and doesn't when it's not. So I was trying to change the class with hover. How can i fix this?

HTML:

<body> <i class="fa-solid fa-user"></i> </body>

CSS:

body[class="fa-solid fa-user fa-flip"]:hover

{<i class="fa-solid fa-user fa-flip"></i>}

Upvotes: 0

Views: 56

Answers (2)

Neha Soni
Neha Soni

Reputation: 4704

The best way to achieve this behavior is to do this using Javascript / Jquery.
I used Javascript to do this.

Two mouse pointer events are enough to make it work.
onmouseover = Calls when moving the mouse pointer onto an element.
onmouseleave = Calls when moving the mouse pointer out of an element.

<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" rel="stylesheet"/>
</head>
<body>
<i class="fa-solid fa-user" onmouseover="flipIcon(this)" onmouseleave="unFlipIcon(this)"></i>

<script>
function flipIcon(el) {
 el.classList.add('fa-flip');
 // See in console if 'fa flip' class is added.
 console.log('On Mouse Hover  -  ', el.className);
}

function unFlipIcon(el) {
 el.classList.remove('fa-flip');
 // See in the console if 'fa flip' class is removed.
 console.log('On Mouse Leave  -  ',el.className);
}

</script>


</body>
</html>

Upvotes: 0

user18149985
user18149985

Reputation:

I think the problem here is the class attribute is added to <i> element, not <body> element.

Could you try this?(I am assuming the element created by the fontawesome is <i>)

i[class="fa-solid fa-user fa-flip"]:hover

Upvotes: 0

Related Questions