Frank Vel Frank Vel - 5 months ago 9
jQuery Question

Merging two functions for a toggle button

I have two similar functions performing a similar task, but I'm not quite sure how to best merge them as I'm still a beginner...

fiddle shows the two functions:

https://jsfiddle.net/umda6wn6/1/

<div class="content">
<div class="green button">
<b>Button</b>
</div>
<div class="red button">
<b>Button</b>
</div>
<div class="green gdiv">
GREENGREENGREENGREEN
</div>
<div class="green gdiv">
GREENGREENGREENGREEN
</div>
<div class="red rdiv">
REDREDREDRED
</div>
</div>


CSS

.button {
color: white;
background-color: green;
width: 10%;
display: inline-block;
text-align: center;
padding: 5px;
}

.red {
background-color: red;
}

.green {
background-color: green;
}

.button:hover {
cursor: pointer;
}

.buttonoff {
background-color: gray;
}


JS

$(document).ready(function() {
$(".green").click(function() {
$(".gdiv").toggle();
$(".green").toggleClass("buttonoff");
});
});

$(document).ready(function() {
$(".red").click(function() {
$(".rdiv").toggle();
$(".red").toggleClass("buttonoff");
});
});


I guess it would look somewhat like this

$(document).ready(function() {
$(".button").click(function() {
$(???).toggle();
$(this).toggleClass("buttonoff");
});


But I don't know what to put inside '???'. As I'm going to add more buttons, I'd like a way to expand this without having to add another function for every new one...

Answer

If you want to know which button was clicked, you can check out its classes this way:

$(document).ready(function() {
  $(".button").click(function() {
      //get classes of element as array
      //    index 0 would be red or green
      var classes = $( this ).prop('className').split(' ');
      //    get first letter of red/ green
      var firstletter = classes[0].substr( 0, 1 );
      $("." + firstletter + "div").toggle();
      $( "." + classes[0] ).toggleClass("buttonoff");
  });
});

Test it here https://jsfiddle.net/8sbe48oa/