I need to accomplish something quite simple, and what I have so far only works half way.
I have a link <a href="#" class="favorites">Favorite</a>
as you can see it has no title attribute.
When page is loaded a script adds this title attribute:
<a href="#" class="favorites" title="Add to Favorites">Favorites</a>
When clicked, a class checked is toggled and then the title attribute should be changed, so the end result would be like this:
<a href="#" class="favorites checked" title="Item added to Favorites">Favorites</a>
I have this code but although it changes the title attribute for the new one, when clicked again the title attribute isn't swapped, which what I need:
$('.favorites').attr('title','Add to Favorites').click(function(){
$(this).toggleClass('checked').attr('title','Added to Favorites');
});
Any ides how I can 'toggle' attributes on click?
I created this DEMO to show this problem.
Thanks in advance.
click(function() { $(". list-sort"). attr('colspan', 6); });
toggle() is now deprecated.
The toggleClass() method toggles between adding and removing one or more class names from the selected elements. This method checks each element for the specified class names. The class names are added if missing, and removed if already set - This creates a toggle effect.
toggleClass( function [, state ] ) A function returning one or more space-separated class names or an array of class names to be toggled in the class attribute of each element in the matched set. Receives the index position of the element in the set, the old class value, and the state as arguments.
Try this
$('.favorites').attr('title', 'Add to Favorites').click(function() {
$(this).toggleClass('checked');
var title = 'Add to Favorites' ;
if( $(this).hasClass('checked')){
title = 'Added to Favorites';
}
$(this).attr('title', title);
});
Check FIDDLE
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