0

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

1
  • your picture does not work as well Commented Jan 16, 2012 at 11:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.