Search code examples
javascriptjqueryhtmlhovermouseout

Changing background of main div when hovering over subdiv


I have 1 container with 3 sub items and Jquery:

$(function() {
  $('.sub1').hover(function() {
    $('#container').css('background-image', 'url("../img/plan.jpg")');
  }, function() {
    // on mouseout, reset the background colour
    $('#container').css('background-color', '');
  });
});
<div id="container">
  <div class="sub1">This is link 1</div>
  <div class="sub2">This is link 2</div>
  <div class="sub3">This is link 3</div>
</div>

The goal is to change the background of "container" when hovering over "sub1", "sub2" or "sub3". Each sub has it's own background-image in css. Once mouse is not longer hovering "sub1", "sub2" or "sub3" the background will return to white.

Dont mind that theres no sub2 or sub3 functions yet, I focus on those later.

I got it working till the part of mouseout. The container background wont return to it's original state (white).

Is there some guru that can help me out?

Thanks in advance,

Roelof!


Solution

  • You are resetting background-color instead of background-image. I took the liberty of making it work for all subs too. :)

    $(function() {
      $('#container').on('mouseover', '[class^="sub"]', function() {
        var container = $('#container');
        switch ($(this).attr('class')) {
          case 'sub1':
            container.css('background-image', 'url("http://placehold.it/500x50")');
            break;
          case 'sub2':
            container.css('background-image', 'url("http://placehold.it/500x60")');
            break;
          case 'sub3':
            container.css('background-image', 'url("http://placehold.it/500x70")');
            break;
          default:
        }
      });
      
      $('#container').on('mouseout', '[class^="sub"]', function() {
        $('#container').css('background-image', '');
      });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
    <div id="container">
      <div class="sub1">This is link 1</div>
      <div class="sub2">This is link 2</div>
      <div class="sub3">This is link 3</div>
    </div>