Coloring divs onclick after button click

I have the following:

$(function() {
  var b = $("#btn");
  var a = $(".a");
  var c = $(".c");
  var e = $(".e");
  var g = $(".g");

  b.click(function() {
    a.click(function() {
      var cls = this.className;
      var clss = cls.slice(-1);

      switch (clss) {
        case "c":
          $(this).css({
            "background-color": "red"
          });
          break;
        case "e":
          $(this).css({
            "background-color": "green"
          });
          break;
        case "g":
          $(this).css({
            "background-color": "blue"
          });
          break;
      }
    });
  });
});
      

.a {
  background-color: yellow;
  border: 1px black solid;
}
      

<div class="a c">1</div>
<div class="a c">2</div>
<div class="a e">3</div>
<div class="a e">4</div>
<div class="a g">5</div>
<div class="a g">6</div>
<input type="button" value="button" id="btn">
      

Run code


This code should do the following: When you click .a

, after you clicked #btn

, it should grab the second variable and color:

  • .c

    - red
  • .e

    on green
  • .g

    to blue

But that doesn't happen at all. Please help me understand and solve my code.

Thank.

+3


source to share


1 answer


Works as you expected, the only problem is you are missing the jQuery library in your snippet.



$(function() {
  var b = $("#btn");
  var a = $(".a");

  function color() {

  }
  b.click(function() {
    a.click(function() {
      var cls = this.className;
      var clss = cls.slice(-1);

      switch (clss) {
        case "c":
          $(this).css({
            "background-color": "red"
          });
          break;
        case "e":
          $(this).css({
            "background-color": "green"
          });
          break;
        case "g":
          $(this).css({
            "background-color": "blue"
          });
          break;
      }
    });
  });
});
      

.a {
  background-color: yellow;
  border: 1px black solid;
}
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="a c">1</div>
<div class="a c">2</div>
<div class="a e">3</div>
<div class="a e">4</div>
<div class="a g">5</div>
<div class="a g">6</div>
<input type="button" value="button" id="btn">
      

Run code


+2


source







All Articles