sri
sri

Reputation: 11

How can i change background image of the page when i click on navigation menu link using Javascript?

How can i change Background-image of the page when i click on navigation link using JavaScript ?

<li><a href="#"id="bd"onclick ="one()">facial</a></li>

<script>
 function one(){
   document.getElementById('bd').style.background-image=url(eye.jpg);
   }
</script>

Upvotes: 0

Views: 42

Answers (2)

jacoballenwood
jacoballenwood

Reputation: 3057

You could set up a class with the background image and then just add that class with JavaScript:

.eye {
   background-image: url(eye.jpg);
}

function one() {
   document.getElementById('bd').classList.add('eye');
}

That way you can also do any styling you need to do with the image.

Upvotes: 0

Pranav C Balan
Pranav C Balan

Reputation: 115242

Background image can be update with backgroundImage and the value should be string so wrap it with quotes.

<li><a href="#" id="bd" onclick="one()">facial</a>
</li>

<script>
  function one() {
    document.getElementById('bd').style.backgroundImage = 'url(eye.jpg)';
  }
</script>


Also you can simplify the code by passing the element reference.

<li><a href="#" id="bd" onclick="one(this)">facial</a>
</li>

<script>
  function one(ele) {
    ele.style.backgroundImage = 'url(eye.jpg)';
  }
</script>

Upvotes: 2

Related Questions