1

Here is my code. When I "toggle thumbs-up glyphicon" and try to get value of its class name on click of downvote button. It gives undefined value.

P.s. When I try to get its value in its own function, it works fine.

 <div style="float:right">
     <a class="upvotebtn" href="#" ><i class="fa fa-thumbs-o-up"></i>10000</a>
     <a class="downvotebtn" href="#" ><i class="fa fa-thumbs-o-down"></i>10000</a>
</div>

$('.upvotebtn').click(function(){
    $(this).find('i').toggleClass('fa-thumbs-o-up').toggleClass('fa-thumbs-up');
    $(this).toggleClass('upvotebtn').toggleClass('upvotebtn-highlight');
});

$('.downvotebtn').click(function(){
        $(this).find('i').toggleClass('fa-thumbs-o-down').toggleClass('fa-thumbs-down');
        $(this).toggleClass('downvotebtn').toggleClass('downvotebtn-highlight');     
});
Ankit Kathiriya
  • 1,221
  • 10
  • 17
Muhammad Ateeq Azam
  • 1,009
  • 1
  • 12
  • 26

3 Answers3

1

You should set event handlers using .on, as it is dynamic in nature. Also you can pass multiple classes in single .toggleClass

$(document).on("click", '.upvotebtn', function(){
    $(this).toggleClass('upvotebtn upvotebtn-highlight').find('i').toggleClass('fa-thumbs-o-up fa-thumbs-up');

});
$(document).on("click", '.downvotebtn', function(){
        $(this).toggleClass('downvotebtn downvotebtn-highlight').find('i').toggleClass('fa-thumbs-o-down fa-thumbs-down');
});

Moreover, i really doubt that the classes you are toggling are not what you want.

void
  • 36,090
  • 8
  • 62
  • 107
0

You are changing the class of the button and then attempting to select by that class. That won't work. Instead, toggle a class that you don't use in the selector. For example:

$('.upvotebtn').click(function(){
    $(this).find('i').toggleClass('fa-thumbs-o-up').toggleClass('fa-thumbs-up');
    $(this).toggleClass('upvotebtn-highlight');

});
raduation
  • 792
  • 5
  • 11
0

This code works for me.

$(document).ready(function(){
  $('.upvotebtn').click(function(){
    $(this).find('i').toggleClass('fa-thumbs-o-up fa-thumbs-up');
    $(this).toggleClass('upvotebtn upvotebtn-highlight');
  });

  $('.downvotebtn').click(function(){
    $(this).find('i').toggleClass('fa-thumbs-o-down fa-thumbs-down');
    $(this).toggleClass('downvotebtn downvotebtn-highlight');
  });
});
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>

<div style="float:right">
     <a class="upvotebtn" href="#" ><i class="fa fa-thumbs-o-up"></i>10000</a>
     <a class="downvotebtn" href="#" ><i class="fa fa-thumbs-o-down"></i>10000</a>
</div>
Ankit Kathiriya
  • 1,221
  • 10
  • 17