0

I have this toggle button in which when i click on it the button shows that it is active and the css changes so it is darker. but when i click the other button the toggle doesn't deactivate (on/off) i want to change that so that it turns on when i click on it and off when i click on the other button.

buttons

<div class="btn-group float_right">
    <a id="gridBtn" onclick="$.views.stuff.ToggleView('gridView')" title="View as grid" class="btn" href="#"><i class="icon-th-large"></i></a>
    <a id="listBtn" onclick="$.views.stuff.ToggleView('listView')" title="View as list" class="btn" href="#"><i class="icon-th-list"></i></a>
</div>

javascript

$(document).ready(function () {
        $('a#gridBtn').click(function () {
            $(this).toggleClass("down");
        });
        $('a#listBtn').click(function () {
            $(this).toggleClass("down");
        });
    });
wakooka
  • 1,398
  • 10
  • 15
Masriyah
  • 2,445
  • 11
  • 49
  • 91

3 Answers3

3

Try this CSS trick:

<div class="btn-group float_right">
    <label>
        <input type="radio" name="viewbuttons" />
        <a id="gridBtn" .....>...</a>
    </label>
    <label>
        <input type="radio" name="viewbuttons" />
        <a id="listBtn" .....>...</a>
    </label>
</div>

Then add this CSS:

.btn-group input {display:none}
.btn-group a { /* your "deselected" styles here */ }
.btn-group input+a { /* your "selected" styles here */ }

This is extremely efficient since you don't need any jQuery to make it work ;)

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
2

You can give your #gridBtn the down class by using:

$('#gridBtn').addClass('down');

Also, there's no need for two separate click handlers:

  $('a#gridBtn, a#listBtn').click(function() {
    $(this).toggleClass('down').siblings().removeClass('down');
  });

Demo

billyonecan
  • 20,090
  • 8
  • 42
  • 64
  • is there a way to remove the hover feature from a button that has `.addClass('down')` to it? – Masriyah Apr 11 '13 at 13:29
  • It'd be better to do that using CSS, [this question here](http://stackoverflow.com/questions/5069110/remove-hover-css-behavior-from-element) should be able to help – billyonecan Apr 11 '13 at 13:37
1

You need to set the state of the other button at the same time?

$(document).ready(function () {
    $('a#gridBtn').click(function () {
        $(this).toggleClass("down");
        $('a#listBtn').attr('class', 'up');
    });
    $('a#listBtn').click(function () {
        $(this).toggleClass("down");
        $('a#gridBtn').attr('class', 'up');
    });
});
Simon Martin
  • 4,203
  • 7
  • 56
  • 93