SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Addict
    Join Date
    Feb 2013
    Posts
    278
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    simple jquery help, addClass + removeClass problem.

    Hi,

    Take a look at this fiddle: http://jsfiddle.net/j5vZN/5/

    Or this code/markup:

    Code HTML4Strict:
    <ul>
        <li><button>hello</button></li>
        <li><button>world</button></li>
    </ul>

    Code CSS:
    ul{
        width: 200px;
    }
     
    li{
        display: block;
        float: left;
        width: 100%;
    }
     
    button{
        display: block;
        width: 100%;
        color: #000;
        padding: 10px;
        text-align: left;
        text-transform: uppercase;
        background: #eee;
        margin: 0;
        border: 0;
        outline: 0;
    }
     
    .selected{
        background: #555;
        color: #fff;
    }

    Code JavaScript:
    $('ul li button').on('click', function(){
    	$(this).addClass('selected');
    	$(this).siblings().removeClass('selected');
    });

    What I want to do is add the class "selected" on click of a button, and then remove it when i click the other button. I understand now I can't use siblings, because well, they are not siblings. I guess it could be done with the <li> but how would i solve it with the buttons?

  2. #2
    SitePoint Addict
    Join Date
    Jan 2009
    Posts
    368
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You can use toggleClass and removeClass - http://jsfiddle.net/j5vZN/6/


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •