John John - 3 months ago 11
CSS Question

How can I toggle background color and toggle slide at the same time?

I want to toggle background-color and slideToggle on click. I also want a hover over affect on all buttons. My hover over affect stops working after the first click. I also haven't figured out a good way to toggle background as you will see by my code.

Here is my jsfiddle

https://jsfiddle.net/johnmartin21/yLr5equc/1/

This javascript doesn't work if the same button is clicked twice.

$('#11').show().css({'background-color':'#cccccc'});
$('#22,#33,#44,#55,#66').show().css({'background-color':'white'});


Also, if you have any suggestions on how to my my javascipt cleaning/shorter, I'm happy to listen. Thanks.

Answer

With a little clean up you can simplify this whole thing a lot:

jquery

$(document).ready(function(){
  $('.button')
  .on('click', function () {

    $('.button').not(this)
      .removeClass('selected')

    $('p.displayed').not($(this).next().next())
      .slideUp()
      .removeClass('displayed')

    $(this)
      .toggleClass('selected')
      .next(/*br*/).next(/*p*/)
        .slideToggle()
        .addClass('displayed')
  })

});

css

button.selected {
  background-color: #ccc;
}

src: https://jsfiddle.net/yLr5equc/14/ (sorry, at first I forgot to hide the previous slideDown.. this is resolved now)

Comments