0

I have a style on my web page that uses the body::before to set an image. I want to change this image with jQuery after the page loads. I've tried doing something like this but with no success.

$('body::before').css('background-image','image.jpg')

Here is my simple html:

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <script src="lib/jquery.min.js" type="application/javascript"></script>
    <title>x</title>
    <style>
      body::before {
        content: "";
        background-image: url("http://peterkellner.net/wp/wp/wp-content/uploads/2018/05/cropped-peterkellnernet-300x60.png");
        background-size: contain;
        background-repeat: no-repeat;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 9999;
        display: inline;
      }
    </style>
  </head>
  <body>
    <script src="_test.js" type="application/javascript"></script>
  </body>
</html>
Peter Kellner
  • 14,748
  • 25
  • 102
  • 188

1 Answers1

3

What you can do instead of trying to style a pseudo-element (which are not accessible through DOM API and also cannot be styled using inline styles), you can simply create a new class with the ::before element and its styles. Then you can simply add that class to the body element. Example:

.loadedBody::before {
        content: "";
        background-image: url("http://peterkellner.net/wp/wp/wp-content/uploads/2018/05/cropped-peterkellnernet-300x60.png");
        background-size: contain;
        background-repeat: no-repeat;
        position: absolute;
        top: 0;
        bottom: 0;
        left: 0;
        right: 0;
        z-index: 9999;
        display: inline;
      }

then using $(document).ready() and addClass(), just add the above class directly to body element. Something like this:

$(document).ready(function() {
    $('body').addClass('loadedBody')
})

More info here: https://api.jquery.com/addClass/

Devashish
  • 1,260
  • 1
  • 10
  • 21
  • Will this cause a memory leak in the browser if I do this over and over again without freshing the page? That is, if I have a button that toggles the class on the body element. – Peter Kellner Jun 23 '19 at 21:45
  • 1
    @PeterKellner No Peter, it won't. Memory leak might occur when this process is done very rapidly, say within a few milliseconds, and that only on small, low-end devices. But it might put in sluggishness in the page, like small stutters and a general feel of slowness on some less powerful devices. Bottomline: Go ahead with it and don't worry about a memory leak. – Devashish Jun 28 '19 at 12:10
  • @PeterKellner Hey Peter! Just a friendly reminder that if my answer worked for you, please accept it as the correct answer. Just trying to get some sweet reputation points! ;) Thanks! – Devashish Jul 06 '19 at 10:20