I want to click like/unlike to toggle colors of an fontawesome icon. It works when I use a button but not work using a text link. html part:
<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>
Works javascript:
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";
}
});
Not work part:(I want 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>
It works if you add preventDefault()
to your click()
function.
$(document).ready(function() { $('.like').click(function(e) { e.preventDefault(); 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 src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class='post'><i class='fas fa-heart' id='h2' style='color:red'>test</i><span><a href='' class='like' bid='2' cid='h2'>like</a></span></div><br><br><button>click</button>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.