Home > Software engineering >  jQuery .addClass applying to everything
jQuery .addClass applying to everything

Time:12-18

I have a like button that uses jQuery. The like button works as expected however due to the way I have it setup it changes every icon on the page to a heart

code:

if (data.liked) {
    updateText(this_, data.likescount, "")
    $(".like-btn").prepend("<i></i>");
    $("i").addClass("fa fa-heart-o liked-heart");  //problem line
} else {
    updateText(this_, data.likescount, "")
    $(".like-btn").prepend("<i></i>");
    $("i").addClass("fa fa-heart-o unliked-heart"); //problem line

From what i userstand the issue is that I am appending the class fa fa-heart-o ... to all i elements. How can I just apply it to the like button

full code:

<script>
    $(document).ready(function(){
         function updateText(btn, newCount, verb){
         btn.text(newCount   " "   verb)
     }

     $(".like-btn").click(function(e){
       e.preventDefault()
       var this_ = $(this)
       var likeUrl = this_.attr("data-href")
       var likeCount = parseInt(this_.attr("data-likes")) | 0
       var addLike = likeCount   1
       var removeLike = likeCount - 1
       if (likeUrl){
          $.ajax({
           url: likeUrl,
           method: "GET",
           data: {},
           success: function(data){
             console.log(data)
             var newLikes;
             if (data.liked){
                  updateText(this_, data.likescount, "")
                  $(".like-btn").prepend("<i></i>");
                  $( "i" ).addClass( "fa fa-heart-o liked-heart" );
              } else {
                  updateText(this_, data.likescount, "")
                  $(".like-btn").prepend("<i></i>");   
                  $( "i" ).addClass( "fa fa-heart-o unliked-heart" );    

              }
           }, error: function(error){
             console.log(error)
             console.log("error")
           }
         })
       }       
     })
 })
</script> 

<a  data-href='{{ post.get_api_like_url }}' data-likes="{{ post.likes.count }}" href="{{ post.get_like_url }}"><i  aria-hidden="true"></i>{{ post.likes.count }}</a>

CodePudding user response:

When you click on .like-btn, it contains i tag, why do you try again $(".like-btn").prepend("<i></i>"); in the success ? Since you have stored $(this) in the this_ variable you can easily get the target i by this_.find('i') and in the success method and then try to add or remove class from the selected i.

CodePudding user response:

You are currently targeting every '.like-btn' on the page and also targeting every <i>. As mentioned in the other answer, you can use jQuery's .find(selector) to target the existing <i> tag (rather than prepend it) and simplify your code a bit with a removeClass/addClass combo

$(document).ready(function() {

    $(".like-btn").click(function(e) {
      e.preventDefault()
      let this_ = $(this)
      let is_liked = this_.find('i').hasClass('fa-heart');
      if (is_liked) {
        this_.find('i').removeClass('fa-heart').addClass('fa-heart-o');
      } else {
        this_.find('i').removeClass('fa-heart-o').addClass('fa-heart');
      }
    })
  }) 
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css" integrity="sha512-5A8nwdMOWrSz20fDsjczgUidUBR8liPYU WymTZP1lmY9G6Oc7HlZv156XqnsgNUzTyMefFTcsFH/tnJE/ xBg==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>

<a  href="javascript:void(0)"><i ></i> 5</a>
<a  href="javascript:void(0)"><i ></i> 9</a>
<a  href="javascript:void(0)"><i ></i> 12</a>

  • Related