DoGPi
DoGPi

Reputation: 11

JavaScript change background image on-click?

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')";
    }
}

Upvotes: 1

Views: 177

Answers (2)

Rahul Sharma
Rahul Sharma

Reputation: 10111

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>

Upvotes: 0

Jello
Jello

Reputation: 414

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

Upvotes: 1

Related Questions