wfareed
wfareed

Reputation: 139

Changing background of link when clicked using jQuery

I have 4 links with background color that I need to be changed when I click, I use this code to change the background :

jQuery:

$(document).ready(function() {
  $('#content_area').load($('.pm_class:first').attr('href'));

  $('.pm_class').click(function() {
    var href = $(this).attr('href');
    $(this).css('background-color', '#3B581E');
    $(this).css('color', '#fff');
    $('#content_area').hide().load(href).fadeIn('normal');
    return false;
  });
});

The issue is: when I click a different link the css in my jQuery is still applied to the previous link I clicked along with the second one. I need the first to return to the original state as shown in the image below. I need it to return back to be like the "send message" and "archive" links :

jQuery issue

Upvotes: 0

Views: 250

Answers (2)

wholerabbit
wholerabbit

Reputation: 11536

JS functions are objects, and can be assigned member variables. These work like what in some C like languages is called a "static" local variable, meaning it retains its value between invocations.

$('pm_class').click(function () { switchBG($(this)) });

function switchBG (elem) {
    if (switchBG.prev) {
        switchBG.prev.css('background', '#ffffff');
    }
    elem.css('background', '#ffff00');
    switchBG.prev = elem;
} 

You could do the same thing with a global, but this is tidier.

Upvotes: 0

James Allardice
James Allardice

Reputation: 165951

You could change the style of all .pm_class elements back to the original, and then change the styles of this to the new style:

$('.pm_class').click(function() {
    var href = $(this).attr('href');
    $(".pm_class").css({
        backgroundColor: "oldColor",
        color: "oldColor"
    });
    $(this).css({
        backgroundColor: "#3B581E",
        color: "#fff"
    });
    $('#content_area').hide().load(href).fadeIn('normal');
    return false;
});

Note that I've consolidated your calls to the css method into one, as it will accept an object representing a map of CSS properties and values as an argument.

Upvotes: 1

Related Questions