RyeGuy RyeGuy - 2 months ago 14
HTML Question

<li> element toggle between different background colors

Hello I know how to change the background color of an element by using $(this).css. However I would like to instead change the color of an element based upon the class of the button. Anyone understand why it is not going back after second click?

JS

var $begin1 = $(".begin1").click( function(e) {
e.preventDefault();
var buttonState = $(this).attr("class");
if(buttonState !='pressed'){
$begin1.removeClass('pressed');
$(this).addClass('pressed');
} else{
$(this).removeClass('pressed');
$(this).addClass('unpressed');
}
});


HTML

<li class="begin1 unpressed"><h2>Button</h2></li>


CSS

li{
list-style-type: none;
}
.begin1.unpressed,
.begin2.unpressed {
background-color: white;
color: black;
border: 2px solid #4CAF50;
margin: 0 0 10px 0;
}
li.begin1.pressed,
li.begin2.pressed{
background: #4CAF50;
color: white;
}


https://jsfiddle.net/nrebaL00/

Answer

You can simplify your code greatly. Apply the default styling from the beginning and you don't need an .unpressed class.

e.prevendDefault() is not required for an <li>, so remove that.

Note: the selector I used for jQuery is pretty generic. You may need to increase it's specificity if there are other <li> on the page that don't require the functionality. Something along the lines of adding a class to the <ul> and using that as the part of the jQuery selector. i.e. <ul class="clicky-mcclickens"> and $( '.clicky-mcclickens li' ).

$('li').on('click', function(e) {
  $(this).toggleClass('pressed');
});
li {
  list-style-type: none;
  background-color: white;
  color: black;
  border: 2px solid #4CAF50;
  margin: 0 0 10px 0;
}
.pressed {
  background: #4CAF50;
  color: white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li>
    <h2>Button 1</h2>
  </li>
  <li>
    <h2>Button 2</h2>
  </li>
</ul>

Sometimes you need more control that simply add/remove a class when an element is clicked. In those instances you can use .hasClass() to check if the element has the class in question.