Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: Toggle title attribute of href depending on state

Tags:

jquery

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.

like image 528
Ricardo Zea Avatar asked Oct 24 '12 17:10

Ricardo Zea


People also ask

How to toggle attr in jQuery?

click(function() { $(". list-sort"). attr('colspan', 6); });

Is jQuery toggleClass deprecated?

toggle() is now deprecated.

What is toggleClass?

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.

What does toggleClass return?

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.


1 Answers

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

like image 176
Sushanth -- Avatar answered Nov 08 '22 22:11

Sushanth --