1

I did some research on here, and I left with the impression that a background image is not loaded if the associated div class is not in the HTML. This led me to believe that when using addClass() to assign a div the class with the background image, I would need to refresh the CSS to make the image load. However, it is showing up without refreshing the CSS.

Does including the class in the JavaScript cause the CSS to pre-load the image, so it is ready when the class is added? If not, why is the background image available without refreshing the CSS?

HTML

    <body>
    <div class="no-class"></div>
    </body>

CSS

    .background-image {
       background-image: url('image.png');
       background-size: 100% 100%;
     }

    .no-class {
       height: 500px;
       width:500px;
       background-color: red;
     }

JS

    $(document).ready(function () {
        $('.no-class').click(function() {
          $('.no-class').toggleClass('background-image');
         });
     })
Matthew McClure
  • 53
  • 1
  • 10

1 Answers1

-2

rearrange classes

.no-class {
   height: 500px;
   width:500px;
   background-color: red;
}
.background-image {
   background-image: url('image.png');
   background-size: 100% 100%;
}

And be sure to include Jquery

DEMO

and if you have more than 1 element with class .no-class .. use $(this)

$(document).ready(function () {
    $('.no-class').click(function() {
      $(this).toggleClass('background-image');
    });
 })
Mohamed-Yousef
  • 23,946
  • 3
  • 19
  • 28
  • Thanks for the syntax corrections - I'm still learning. I was hoping to find out why it works though. Does the browser go ahead and pre-load the background image because the class is listed in the script? Or does the class being added cause the CSS to be rerun to get the link to the background image? I could be wrong, but I thought the only images that would be loaded were ones with classes listed in the HTML. – Matthew McClure Nov 10 '15 at 04:58
  • @MatthewMcClure http://stackoverflow.com/questions/460389/browser-caching-of-css-files hope it help – Mohamed-Yousef Nov 10 '15 at 05:23