1

I'm trying to change the background of the body on my HTML doc using some basic JS functions. I have set the function to target a specific ID, and then the style.background tag, if it is the current background image, then set it to another one I specified, else keep the same image. I have tried changing the code countless times now, but still can't seem to get it to change the background. Any help with this would be appreciated.

HTML:

<div class="bg-image" 
     style="background-image: url('./img/frankie.jpg');
            height: 100vh" id="bacgr"> <!--SETS BACKGROUND using id tag to change w/ JS-->
        <main role="main" class="container d-flex justify-content-center">

          <div class="starter-template">
            <h1>Bootstrap starter template</h1>
            <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
          </div>

        </main>
    </div>

JS:

let myImage = document.getElementById('bacgr').style.backgroundImage; //have to target specific image(like an array ([0])), put inside div w/ id.

myImage.onclick = function() {
    if(myImage === "url('./img/frankie.jpg')") {
      myImage == "url('./img/jesus_mobile.jpg')";
    } else {
      myImage == "url('./img/frankie.jpg')";
    }
}

2 Answers 2

1

Try this:

const el = document.getElementById('bacgr');
el.onclick = function() {
  if(this.style.backgroundImage === "url('./img/frankie.jpg')") {
    this.style.backgroundImage = "url('./img/jesus_mobile.jpg')";
  } else {
    this.style.backgroundImage = "url('./img/frankie.jpg')";
  }
}

Here is the example

Sign up to request clarification or add additional context in comments.

Comments

0

You are changing only the URL, but that will not be assigned back to the dom element.

const el = document.getElementById('bacgr');
let prev = 'url("https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa")';
el.onclick = function() {
  el.style.backgroundImage = prev === el.style.backgroundImage ? 'url("https://images.unsplash.com/photo-1583508915901-b5f84c1dcde1")' : prev;
}
<div class="bg-image" style="background-image: url('https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa');
            height: 100vh" id="bacgr">
  <main role="main" class="container d-flex justify-content-center">
    <div class="starter-template">
      <h1>Bootstrap starter template</h1>
      <p class="lead">Use this document as a way to quickly start any new project.<br> All you get is this text and a mostly barebones HTML document.</p>
    </div>

  </main>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.