Prains
Prains

Reputation: 17

How can i change background image through js code?

I have background image installed in css:

.indicator {
  grid-area: b;
  background-color: yellow;
  background-image: url(./maxresdefault.jpg);
}

and want to change it on event like that:

indicator.oncontextmenu = function() {
  indicator.style.background = '';
  alert('msg');
}

but have no clue which type of command is used to change the background image in css by js. how do i change it?

Upvotes: 0

Views: 69

Answers (1)

Kanol77
Kanol77

Reputation: 33

Try this:

indicator.addEventListener('contextmenu', () => {
    indicator.style.backgroundImage = "url('your_image.png')";
    alert('msg');
})

Upvotes: 1

Related Questions