Sherry
Sherry

Reputation: 95

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?

Upvotes: 3

Views: 46442

Answers (4)

jyore
jyore

Reputation: 4825

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.

HTML

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

JavaScript

$(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
        selected.button('disable').addClass('ui-state-active').removeClass('ui-state-disabled');

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

Upvotes: 7

G.A.
G.A.

Reputation: 1523

$('#mybutton').button().bind('click', function(){
    $(this).addClass('ui-state-focus');
});

This keeps it in focussed state (ie., highlighted as per jquery ui theme you have selected). Of course, you need to remove this class from all the other buttons on your toolbar.

Upvotes: 3

Kokos
Kokos

Reputation: 9121

If your button goes to a new page, you will need to use either your server side language or html (depending on your setup) to switch the classes.

If your button refreshes the current page with new content, you can use something like the following:

.active { font-weight:bold; }

$('#button').addClass('active');

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69905

Once the page load add a css class to button. Have some styles for this class which will indicate that it is selected.

Upvotes: 0

Related Questions