skip to Main Content

i created an ajax favorite button where when a user clicks the heart button the information gets sent to the server without reload and the heart shape becomes filled with red using javascript(exactly like instagram heart button ). now i am having a problem that when the page reloads the heart filling is removed and how will each indiviual message be filled and not only the first instance ?

here is my code:

my html code:

   <a href="" class="msg-icon" onclick="toggle()" >

        <input  type="hidden" name="fav"  value="<?php echo $row['msgid']; ?>" style=""  >

        <i class="far fa-heart" id="favBtn" style="" ></i>
   </a>

my javascript code:

  function toggle(){
var btn= document.getElementById("favBtn");
if(btn.classList.contains("far")){
    btn.classList.remove("far");
    btn.classList.add("fas");
}else{
    btn.classList.remove("fas");
    btn.classList.add("far");
  }
}

how can i make it that the heart filling is only removed when the user clicks on the button again for each message?

2

Answers


  1. I see you are using PHP to load the id of the message on page load. I’m guessing you want something similar when setting the initial CSS-classes on “favBtn”. The following snippet checks a field on the same $row with php and chooses chat class to show initially based on that.

    <i class="<?php if($row['isFavorite'] {echo "fas";} else {echo "far";}) fa-heart" id="favBtn"></i>
    

    Another alternative would be to load the data with an AJAX call, but that would delay the load of the status and probably not what you are looking for in this case.

    Good luck!

    Login or Signup to reply.
  2. If those unreadable CSS class names come from an external library, consider putting them into variables with more recognizable names, and using the variables instead of the external names directly.

    For example:

    var heartOutline = 'far'
    var heartFilled = 'fas'
    
    function toggle(){
        var btn= document.getElementById("favBtn")
        if(btn.classList.contains(heartOutline)){
            btn.classList.remove(heartOutline)
            btn.classList.add(heartFilled)
        }else{
            btn.classList.remove(heartFilled)
            btn.classList.add(heartOutline)
        }
    }
    
    // they got rid of semicolons in JS because they wanted to emulate Python 
    

    I’m getting used to not using semicolons in JS.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search