$(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?
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:-
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.
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.
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”.
$(function() {
$('a#fav').click(function() {
return ($(this).hasClass('active'))
? removeFav('<?php echo $showUP["uID"]; ?>')
: addFav('<?php echo $showUP["uID"]; ?>');
});
});
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);
});
});
$(document).ready(function() {
$('a#fav').bind('click', function() {
if ($(this).hasClass('active'))
removeFav(<?php echo $showUP["uID"]; ?>);
else
addFav(<?php echo $showUP["uID"]; ?>);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With