Jquery – how to set jquery button active state


I have this right navigation that uses the jquery button. If the user clicks it, the page will load. What I need is once the page reload, the button should show that it was selected.

How do I do this using the jquery button?

Best Solution

Why don't you use the jQuery UI Tab widget? You could also try using the buttonset widget?

If those are not optimal for you, then you can use some CSS stuff to your advantage. The following code sets up two jQuery UI buttons that will keep their active state when clicked, remove the active state from the other, and update a div with which has been clicked.


<button id="btn" class='nav'>Button 1</button>
<button id="btn2" class='nav'>Button 2</button>
<div id="data">Init....</div>


$(function() {

    //Variable of previously selected
    var selected = [];

    //Setup Buttons
    $('.nav').button().click(function() { 
        //Enable previous
        if(selected[0]) {
            selected.button('enable').removeClass('ui-state-active ui-state-hover'); 

        //Cache the previous
        selected = $(this);

        //Disable this and keep color attributes

        //Do Normal Button Click Stuff Here
        $('#data').text(selected.text() + ' was clicked');