tags:

views:

66

answers:

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

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

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

instead How can i do this?

+9  A: 

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 write it in a more condensed format

$(function() {    
    $('a#fav').bind('click', function() {
        var uID = <?php echo $showUP["uID"]; ?>;
        ($(this).hasClass('active') ? removeFav : addFav)(uID);
    });
});
Zurahn
+1 I like your last version. Just noticed you had it, so I deleted mine. Although you could make it single line if you get rid of the `uID` variable. :o)
patrick dw
A: 
$(document).ready(function() {    
    $('a#fav').bind('click', function() {
        if ($(this).hasClass('active'))
            removeFav(<?php echo $showUP["uID"]; ?>);
        else
             addFav(<?php echo $showUP["uID"]; ?>);
    });
});
sluukkonen
A: 
$(function() {    
  $('a#fav').click(function() {
    return ($(this).hasClass('active'))
      ? removeFav('<?php echo $showUP["uID"]; ?>')
      : addFav('<?php echo $showUP["uID"]; ?>');
  });
});
sod
Please have a quick look at the 'how to format code' question on meta.stackoverflow.com: http://meta.stackoverflow.com/questions/22186/how-do-i-format-my-code-blocks
David Thomas