I am trying to create a toggle effect for the colors of a fontawesome icon when clicking on a text link, but it only works with a button. Here is the HTML code snippet:
<div class='post'>
<i class='fas fa-heart' id='h2' style='color:red'></i>
<span>
<a href='' class='like' bid='2' cid='h2'>like</a>
</span>
</div>
<br>
<br>
<button>click</button>
Here is the working JavaScript part:
var bac=document.querySelector("button");
bac.addEventListener("click", function(){
if (document.getElementById('h2').style.color=="red"){
document.getElementById('h2').style.color="purple";
}else if(document.getElementById('h2').style.color=="purple"){
document.getElementById('h2').style.color="red";
}
});
Unfortunately, the following section does not work as expected (I want to use this because I need to add an AJAX call):
<script type="text/javascript">
$(document).ready(function(){
$('.like').click(function(){
var cid = $(this).attr('cid');
if (document.getElementById('h2').style.color=="red"){
document.getElementById('h2').style.color="purple";
}else if(document.getElementById('h2').style.color=="purple"){
document.getElementById('h2').style.color="red";
}
});
});
</script>