jquerytoggleclass

Jquery - Toggle Class On Multiple Buttons


I currently am running with a small JQuery function that toggles a new class if a button has been clicked.

    $(".button1").click(function () {

        $(this).toggleClass("button2");

    });

This works fine, however, my issue is that I have 5 buttons in a row and I only want one to have the new class at a time. At the moment if i click any of the other buttons they also get the new class applied. I want it, if someone clicks another button, to remove the button2 class from the original button and apply it only to the newley clicked button.

Any thoughts on achieving this?


Solution

  • Try this:

    $(".button1").click(function () {
        $(this).parent().find(".button2").removeClass("button2");
        $(this).addClass("button2");
    });