Div Hovers

0
451
CSS Div Hover

Given a <div>, how does one create a change in behavior when the mouse moves into the region and out of it? That was an interesting exercise on one of my websites as I searched for a solution to change the background color in a <div>.

Div Hovers With CSS

A simple solution uses CSS by use of the hover attribute on a <div>:

  1. div:hover {
  2.   background-color: red;
  3. }
  1. <div class="mybox">
  2.   <p>This is some text that is just dummy filler.</p>
  3. </div>

It should be noted that you can use this with any group content and section tag in HTML5 such as:

  • <article>
  • <section>
  • <header>
  • <footer>
  • <aside>

Div Hovers With Javascript

However, the above won’t work under Internet Explorer 6. So until IE 6 goes out of mainstream (Aug 2016: it already did) we have to work around it. Now after reading some of the Javascript solutions after Googling, I found some of them didn’t even work. Eventually I came up with a simple solution:

  1. <script type="text/javascript">
  2. function ChangeBackground(e, color) {
  3.   e.style.background = color;
  4. }
  5. </script>
<div onmouseover="ChangeBackground(this, '#ff0000')" onmouseout="ChangeBackground(this, '#efefef')">
  <p>This is some text that is just dummy filler.</p>
</div>

Try it!

  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <title>Div Hovers</title>
  5. <style>
  6.   * {
  7.     box-sizing: border-box;
  8.   }
  9.   #page {
  10.     display: flex;
  11.     flex-direction: column;
  12.     flex-wrap: wrap;
  13.     width: 640px;
  14.     margin: 1em auto;
  15.     font-size: 18px;
  16.   }
  17.   article div {
  18.     padding: 1em;
  19.     border: 1px solid black;
  20.   }
  21. </style>
  22. </head>
  23.  
  24. <body>
  25. <script type="text/javascript">
  26. function ChangeBackground(e, color) {
  27.   e.style.background = color;
  28. }
  29. </script>
  30.  
  31. <div id="page">
  32.   <header>
  33.     <h1>Div Hovers</h2>
  34.   </header>
  35.   <main>
  36.     <article>
  37.       <div onmouseover="ChangeBackground(this, '#ff0000')" onmouseout="ChangeBackground(this, '#efefef')">
  38.         <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
  39.       </div>
  40.     </article>
  41.   </main>
  42. </div>
  43. </body>
  44. </html>

Of Interest