Home > front end >  JavaScript change background image on-click?
JavaScript change background image on-click?

Time:01-13

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  
     style="background-image: url('./img/frankie.jpg');
            height: 100vh" id="bacgr"> <!--SETS BACKGROUND using id tag to change w/ JS-->
        <main role="main" >

          <div >
            <h1>Bootstrap starter template</h1>
            <p >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')";
    }
}

CodePudding user response:

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

CodePudding user response:

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  style="background-image: url('https://images.unsplash.com/photo-1570215171323-4ec328f3f5fa');
            height: 100vh" id="bacgr">
  <main role="main" >
    <div >
      <h1>Bootstrap starter template</h1>
      <p >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>

  •  Tags:  
  • Related