theintellects
theintellects

Reputation: 1370

Change colour of elements previously clicked

I have a list of elements that I want to change color after the user has click a button (then clicked a different one). I know to change the button colour on click I would use onclick, but how would I change the colour of the button AFTER I've clicked?

For example, the user clicks Titanic. Nothing happens. Then the user clicks Titanic7, Titanic changes colours and remains that colour. Then the user clicks Titanic9. Titanic and Titanic7 both have the "visited" colour.

See JSFiddle here

Upvotes: 0

Views: 65

Answers (3)

alessandrio
alessandrio

Reputation: 4370

$(function(){
    $( "a" ).click(function() {
  $( this ).toggleClass( "color" );
});
});

css

.color{
    background: yellow;
  }

or double click

$(function(){
$( "a" ).each(function() {
  var count = 0;   
  $( "a" ).click(function() {
        count++;
        //$( this ).text( "clicks: " + count );
        $( this ).toggleClass( "color", count % 3 === 0 );
    });
});
});  

Upvotes: 0

kennypu
kennypu

Reputation: 6051

Seeing that you're already using data-, I would do something like the following:

$(function() {
    var currentButton;
    $('a.song').on('click',function() {
        if(currentButton === this) return;
        currentButton = this;
        $('a.song').each(function() {
          if($(this).data('visited') == 'true' && !$(this).hasClass('visited'))
              $(this).addClass('visited');
        });
       $(this).data('visited','true');
    });
});
  1. have a data-visited which keeps track of which button has been clicked
  2. everytime a button is clicked, check if it's the same one that was clicked previously. if not, change the background for the previously clicked button, and set the current button as visited.

example fiddle: http://jsfiddle.net/9eJPD/

Upvotes: 0

Jason P
Jason P

Reputation: 27012

If I understand you correctly, I would do something like this:

http://jsfiddle.net/KHwcU/

$('.song').click(function(e) {
    e.preventDefault();

    $('.selectnext').css('background-color', 'blue').removeClass('selectnext');
    $(this).addClass('selectnext');
});

Upvotes: 1

Related Questions