Skip to content Skip to sidebar Skip to footer

Changing Background Color On Click

I'm trying to allow users changing the background color by clicking one of the boxes. I came into this code but it doesn't work:

Solution 1:

We are missing some CSS in your question. I answer because you seemed to miss the jQuery library but perhaps you did have that AND some CSS that would expand the links to something clickable

This works if you add the jQuery library and some way to make the links visible, text or in this case display inline-block with a padding

$(document).ready(function() {
  $("ul li a").click(function(e) {
    e.preventDefault(); // not strictly needed but a good idea
    const color = $(this).data("color");
    $("body").css("background", color);
  });
  $("[data-color]").each(function() {
    $(this).closest("li").css({"background-color": this.dataset.color})
  })
});
ul {
  list-style-type: none;
}

a {
  text-decoration: none;
  display:inline-block;
  padding:15px;
}

.color-boxes {
  display: inline-block;
  float: right
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="color-boxes">
  <li>
    <a data-color="#000000" class="Black" href="#" title="Black"></a>
  </li>
  <li>
    <a data-color="#7E392F" class="BurntHenna" href="#" title="BurntHenna"></a>
  </li>
  <li>
    <a data-color="#AE856C" class="TawnyBirch" href="#" title="TawnyBirch"></a>
  </li>
  <li>
    <a data-color="#DAB58F" class="Sheepskin" href="#" title="SheepSkin"></a>
  </li>
</ul>

Post a Comment for "Changing Background Color On Click"