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 ideaconst 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
}
<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><ulclass="color-boxes"><li><adata-color="#000000"class="Black"href="#"title="Black"></a></li><li><adata-color="#7E392F"class="BurntHenna"href="#"title="BurntHenna"></a></li><li><adata-color="#AE856C"class="TawnyBirch"href="#"title="TawnyBirch"></a></li><li><adata-color="#DAB58F"class="Sheepskin"href="#"title="SheepSkin"></a></li></ul>
Post a Comment for "Changing Background Color On Click"