); }); }); I...">

JQuery: if class = active?

$(document).ready(function() { $('a#fav').bind('click', function() { addFav(<?php echo $showUP["uID"]; ?>); }); }); 

I need to change this, so if a # fav has class = "active", then it should do

  removeFav(<?php echo $showUP["uID"]; ?>); 

instead How can I do this?

+7
jquery
source share
3 answers

Do you want to use the hasClass function

 $(document).ready(function() { $('a#fav').bind('click', function() { if($(this).hasClass('active')) { removeFav(<?php echo $showUP["uID"]; ?>); } else { addFav(<?php echo $showUP["uID"]; ?>); } }); }); 

EDIT : And just for fun, another way to record it in a more compressed format

 $(function() { $('a#fav').bind('click', function() { var uID = <?php echo $showUP["uID"]; ?>; ($(this).hasClass('active') ? removeFav : addFav)(uID); }); }); 
+21
source share
 $(document).ready(function() { $('a#fav').bind('click', function() { if ($(this).hasClass('active')) removeFav(<?php echo $showUP["uID"]; ?>); else addFav(<?php echo $showUP["uID"]; ?>); }); }); 
+1
source share
 $(function() { $('a#fav').click(function() { return ($(this).hasClass('active')) ? removeFav('<?php echo $showUP["uID"]; ?>') : addFav('<?php echo $showUP["uID"]; ?>'); }); }); 
0
source share

All Articles