I'm trying to change a Font Awesome icon on action using JS.
I'm implementing the icon through pseudo element ::before
.
Assigning the icon through CSS using content:'\f0c2'
displays the icon fine, but if I transfer the string through a dataset - content: attr(data-content)
, it just renders the string on the page.
How can I get it to work? Is there a better way to do it?
Here's a JSFiddle with all relevant code I've used.
const element = document.querySelector('.data');
const btn = document.querySelector('.btn');
const changeIcon = () => {
element.dataset.content = '\\f185';
}
btn.addEventListener('click', changeIcon);
.container {
display: grid;
place-items: center;
margin-top: 6rem;
font-family: sans-serif;
color: lightblue;
gap: 1rem;
}
.btn {
padding: 1em 2em;
background-color: lightblue;
color: white;
border-radius: 10px;
}
.btn:hover {
background-color: white;
color: lightblue;
border: 1px solid lightblue;
}
.icon-before::before {
display: inline-block;
text-rendering: auto;
-webkit-font-smoothing: antialiased;
font: var(--fa-font-solid);
margin-right: 0.2em;
}
.string::before {
content: '\f0c2';
}
.data::before {
content: attr(data-content);
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<div class='container'>
<h2 class='element string icon-before'>
Added through string
</h2>
<h2 class=' element data icon-before' data-content="\f0c2">
Added through dataset
</h2>
<a class='btn'>Press Me</a>
</div>