
Apu
November 10, 2022 ›
#font-awesome
›
#HowTo
❌
How to add icon in button using JavaScript
I have a button and when someone clicks the button, I want to insert a Font Awesome loading icon to it using JavaScript.
For example, I have a <button> element with a onclick attribute and set its value to addIcon().
<button onclick="addIcon()">Click Me</button>
When the above button is clicked, the addIcon() function is executed.
Example : how to insert icon in button using javascript dynamically #
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<button id="myButton" onclick="addIcon()">
Click Me
</button>
<script>
function addIcon(){
btn = document.getElementById('myButton');
btn.innerHTML = '<i class = "fa fa-spinner fa-spin"></i> Please wait...';
setTimeout(function(){
alert("Completed!");
btn.innerHTML = 'Click Me';
}, 3000);
}
</script>
Try it Yourself »
- Inside the addIcon() function, we have stored the button in a variable and changed its value to the following code using the innerHTML property.
function addIcon(){ btn = document.getElementById('myButton'); btn.innerHTML = '<i class = "fa fa-spinner fa-spin"></i> Please wait...'; }
- Using the setTimeout() method, we have called an anonymous function after 3 seconds.
setTimeout(function(){ }, 3000);
- Inside the anonymous function, the alert() method is used and using the innerHTML property , we reset the button back to the original state.
setTimeout(function(){ alert("Completed!"); btn.innerHTML = 'Click Me'; }, 3000);
Try it Yourself »
save
listen
AI Answer
How to add icon in button using JavaScript
0
I have a button and when someone clicks the button, I want to insert a Font Awesome loadi…
asked
Apu
0 answers
2915
I have a button and when someone clicks the button, I want to insert a Font Awesome loadi…
Answer Link
answered
Apu