Question

I'm very new to jQuery.

I have two menu tabs, and am trying to get tab 'a' to toggle (switch) classes with tab 'b' upon click.

Using the .attr method doesn't seem to work. I've also tried switching it with the toggleClass but still nothing.

// toggle between login / register
$(".static-color").click(function() {
    $("#login").hide(); 
    $("#register").show();

    $(this).attr("active-color");
    $(".active-color").attr("static-color");

});

// toggle between login / register
$(".active-color").click(function() {
    $("#login").show();
    $("#register").hide();

    $(this).attr("static-color");
    $(".static-color").attr("active-color");
});

http://jsfiddle.net/h3Y6G/

Was it helpful?

Solution

What you're actually doing with .attr is just getting the value of a supposed static-colorattribute which doesn't exist.

The trick is using .addClass .removeClass or in this case .toggleClass.

Another tip I have for you is to use event delegation with the .on jQuery method. This will allow for more flexible event handling. You are actually attaching the listener to a parent element which will listen for events coming from another element matching the specified selector, like this:

$("#login-register").on('click', '.static-color', function() {
    $('.active-color, .static-color').toggleClass("active-color static-color");
    $("#login, #register").toggle();
});

Also, I see you have a bit of duplication, try to make your code more reusable. Don't Repeat Yourself!

I updated your fiddle: http://jsfiddle.net/h3Y6G/1/

OTHER TIPS

My suggestion would be to use the button class as your selector for toggling the classes, and to remove the static class. You can assume that if your button is not "active" then implicitly it will be "static", and you should style them accordingly.

Try this:

$('.button').click(function() {
    // remove active class from all buttons
    $('.button').removeClass('active-color');
    // add it to the current clicked button
    $(this).addClass('active-color');
    // get button type and deal with content accordingly
    var button_type = $(this).text().trim();
    if(button_type == "Register") {
        $("#register").show();   
        $("#login").hide();
    } else if(button_type == "Log-In") {
        $("#login").show();
        $("#register").hide();
    }
});

JSFiddle: http://jsfiddle.net/h3Y6G/2/

"active-color" isn't an attribute.

Could you mean to switch the CSS or class instead?

$(this).attr("active-color");

becomes

$(this).addClass('active-color').removeClass('static-color');

or to reverse it, just switch the names of the classes:

$(this).addClass('static-color').removeClass('active-color');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top