Search code examples
jquerycssbackground-image

toggling (show/hide) one background out of a two-background div, css jquery


I have a 2-background div arrangement, A is always to be shown within the element and B is toggled according its buttonc control click.

HTML

<div class="container"></div>

CSS

 .container{
  url(B.png) 10px 10px no-repeat, 
   url(A.png) 600px 10px no-repeat,  
  }

JQUERY

$('.container').on('click', function(){

     //$(this).css("background","A.png")? add/removeClass?
  });

How Can I get this?


Solution

  • You can play with background-size to show/hide one of the background-image:

    $('.container').on('click', function() {
      $(this).toggleClass('hide');
    });
    .container {
      width:400px;
      height:200px;
      background-image: 
      url(https://lorempixel.com/300/200/), 
      url(https://lorempixel.com/350/200/);
      background-size: cover;
      background-repeat: no-repeat;
    }
    
    .hide {
      background-size: 0 0, cover;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div class="container"></div>