Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: if class=active?

Tags:

jquery

$(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?

like image 848
Karem Avatar asked Sep 05 '10 15:09

Karem


People also ask

How to check if a class is present in jQuery?

The jQuery hasClass () method checks whether the specified class name exist in the selected elements. It returns a ‘true’ value when it finds the specified class is present. You will get ‘false’ if the class is not present in the element. The syntax of this method is given below:-

How do I find the class of an element in jQuery?

The class name to search for. Elements may have more than one class assigned to them. The .hasClass () method will return true if the class is assigned to an element, even if other classes also are. As of jQuery 1.12/2.2, this method supports XML documents, including SVG.

How to find if a Div has class “Check-Me” using jQuery?

We can utilize both the jQuery click () method and jQuery hasClass () method to find if the div has class “check-me”. Then we will change the text of the span and display true or false.

How to check if a HTML element has a class on click?

We can check if a HTML element has a class on click using jQuery very easily by combining the hasClass () method with a click event. We can utilize both the jQuery click () method and jQuery hasClass () method to find if the div has class “check-me”.


Video Answer


3 Answers

$(function() {    
  $('a#fav').click(function() {
    return ($(this).hasClass('active'))
      ? removeFav('<?php echo $showUP["uID"]; ?>')
      : addFav('<?php echo $showUP["uID"]; ?>');
  });
});
like image 132
sod Avatar answered Oct 19 '22 23:10

sod


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);
    });
});
like image 37
Elle H Avatar answered Oct 20 '22 00:10

Elle H


$(document).ready(function() {    
    $('a#fav').bind('click', function() {
        if ($(this).hasClass('active'))
            removeFav(<?php echo $showUP["uID"]; ?>);
        else
             addFav(<?php echo $showUP["uID"]; ?>);
    });
});
like image 36
sluukkonen Avatar answered Oct 20 '22 01:10

sluukkonen