Reputation: 131
I'm creating thumbs up button with anchor tag when the user click on it, it background and font color change but the problem is it is changing the background color but not the font color:
function changeColor() {
document.getElementById('icon').style.color = "#fff"; // forecolor
document.getElementById('icon').style.background = "#008000"; // backcolor
}
.thumb-up {
border: 5px solid green;
width: 42%;
padding: 30px 6px 34px 32px;
border-radius: 100%;
}
<a onclick="changeColor()" href="#">
<div id="icon" class="thumb-up">
<i id="icon" class="fas fa-thumbs-up fa-5x"></i>
</div>
</a>
Problem: I want to change text and background color on click.
Upvotes: 0
Views: 113
Reputation: 167172
You have id="icon"
twice, this is a crime in HTML and that's the reason it doesn't work. Change it to class
or give different values for id
.
<div id="icon" class="thumb-up">
<i id="icon" class="fas fa-thumbs-up fa-5x"></i>
<!--^^^^^^^^ -->
</div>
In this case, you may as well remove the id="icon"
from <i>
tag. Also, there are CSS based solutions for this, if you are up for it. They are more effective.
Clarification from OP
I used the following code. Also, you should not use fas
and I changed to fa
. I get this initially:
Upon clicking, I get this:
This is the full code I used:
function changeColor() {
document.getElementById('icon').style.color = "#fff"; // forecolor
document.getElementById('icon').style.background = "#008000"; // backcolor
}
.thumb-up {
border: 5px solid green;
width: 42%;
padding: 30px 6px 34px 32px;
border-radius: 100%;
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" />
<a onclick="changeColor()" href="#">
<div id="icon" class="thumb-up">
<i class="fa fa-thumbs-up fa-5x"></i>
</div>
</a>
Upvotes: 4
Reputation: 3911
Don't use same id
names. Id names should be unique.
Your code is working fine here with changes.
function changeColor() {
document.getElementById('icons').style.color = "#fff"; // forecolor
document.getElementById('icon').style.background = "#008000"; // backcolor
}
.thumb-up {
border: 5px solid green;
width: 42%;
padding: 30px 6px 34px 32px;
border-radius: 100%;
text-align: center;
}
<a onclick="changeColor()" href="#">
<div id="icon" class="thumb-up">
<i id="icons" class="fas fa-thumbs-up fa-5x">✓</i>
</div>
</a>
I've changed the id name for fa-icon to icons
so that it will be an unique name
Upvotes: 3