0

I have 2 separate div classes called demo-heart and demo-coal. The functionality I am trying to enable: when the user clicks on the fa-heart icon, it turns into fa-coal. When the user clicks on the fa-coal, it turns into fa-heart.

<div class = "demo-heart">
    <a href = "#" onclick="myFunction()">
        <i class="fa fa-heart fa-3x"></i>
    </a>
</div>

<div class = "demo-coal">
    <a href = "#" onclick="myFunction()">
        <i class="fa fa-coal fa-3x"></i>
    </a>
</div>  

This is what I ahve so far and it doesn't seem to be working. But I also want it to be able to switch back to the original fa-heart when the user clicks on it. Any suggestions?

<script>
    function myFunction(){
        $(".demo-heart").html("<a href = '#'><i class='fa fa-coal fa-3x'></i></a>");
    }
 </script>
1
  • Instead of replacing the content of (every) div element, just toggle the class of the and i element. Commented Nov 11, 2013 at 15:43

2 Answers 2

3

Remove the inlined onclick handler, then use jQuery .click() to register the click handler

jQuery(function(){
    $('.fa').click(function(){
        $(this).toggleClass('fa-heart fa-coal')
    })
})

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

1 Comment

@TusharGupta yes a typo... fixed
1

A much simpler solution is to have one HTML structure and toggle the class within it:

<div class="demo-heart">
    <a href="#">
        <i class="fa fa-heart fa-3x"></i>
    </a>
</div>
$('.demo-heart a').click(function(e) {
    e.preventDefault();
    $('i', this).toggleClass('fa-heart fa-coal');
});

Note that I removed the onClick attribute in favour of a cleaner jQuery event handler.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.