xxx12123
xxx12123

Reputation: 343

how to style a selected button/link with css or javascript?

I would like to style my selected button. I would like to display a light-blue border around the image of my selected button to show which page the user is on. (or just use the same hover image as the selected button image when the button is pushed.) I didn't have success with the css link selectors :visited, :focus, or :selected. Does this require a javascript solution? thanks for any pointers!

Upvotes: 5

Views: 54299

Answers (4)

Wes Eklund
Wes Eklund

Reputation: 127

jQuery Solution with your CSS

You would probably want to check first if it is selected, that way this solution works with things like Twitter Bootstrap, where you can make any element act like a button:

$(function () {
    $('div.button').click(function(){
        if ($(this).hasClass('selected') {
                $(this).removeClass('selected');
                //Insert logic if you want a type of optional click/off click code
            } 
            else
            {
                $(this).addClass('selected');
                //Insert event handling logic
            }
    })
});

Upvotes: 1

Andreas Eriksson
Andreas Eriksson

Reputation: 9027

You will, in fact, need to use javascript. I did this in a project a while back, by iterating through the links in the navbar, and setting a class called "selected" on the one the user is currently visiting.

If you use jQuery, you can accomplish it like this:

$(function() { 
    $('#navbar li').each(function() { 
        if ($(this).children('a').attr('href') == window.location.pathname)
        {
            $(this).addClass('active');
        }
    });
})

The CSS Pseudo-selector :active won't still be active after a pagereload.

Upvotes: 0

blejzz
blejzz

Reputation: 3349

i usually just a extra class name called selected

   <div class="button selected">Button 1</div> 
   <div class="button">Button 2</div>

  .selected {
      border: 1px solid #0000ff;
  }

It depends on how you display your page (using ajax or refresh on every click). If you are using javascript to load the page content than you just put an extra classname using javascript when the button is clicked.

Upvotes: 2

Prashant Lakhlani
Prashant Lakhlani

Reputation: 5806

you should use :active pseudo class in css to achieve what you want.

Upvotes: 1

Related Questions