Load + Hover change background color by data-* attribute

In this example below you will see how to do a Load + Hover change background color by data-* attribute with some HTML / CSS and Javascript

This awesome code was written by raeesh, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright raeesh ©


  • HTML
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

  <meta charset="UTF-8">
  <title>Load + Hover change background  color by data-* attribute </title>


  <div class="box" data-bg="red" data-hoverbg="green">Hello World</div>

<div class="box" data-bg="cyan" data-hoverbg="blue">Hello India</div>

<div class="box" data-bg="orange" data-hoverbg="yellow">Hello Lucknow</div>

<div class="box" data-bg="#04b596" data-hoverbg="#0ce211">Raeesh Alam</div>
  <script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js'></script>


    <script  src="js/index.js"></script>



/*Downloaded from https://www.codeseek.co/raeesh/load-hover-change-background-color-by-data-attribute-RMKQNg */
  $('body').append('<style type="text/css" id="styling">.box{width: 100%; max-width: 420px; border: 1px solid #f9f9f9; height: 60px;line-height: 60px;text-align: center; margin: 15px auto;font-family: "Arial";}</style>');
    $(this).addClass('data-bg-'+i); //Create Dynamic Classes
    var bgColor = $(this).data('bg');
    var hoverbgColor = $(this).data('hoverbg');
    $('#styling').append('.'+'data-bg-'+i+'{background:'+bgColor+'} .data-bg-'+i+':hover{background:'+hoverbgColor+'}');