0

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?

2
  • 1
    Easier would be to define another class with the seperate image, and then add/remove the class from the element in your event. element.classList.add('newclass'); also see stackoverflow.com/questions/66286619/… Commented Jun 27, 2022 at 21:13
  • Using that process the background will actually be automatically replaced to that in onctextmenu on load. But if that is what you want use this indicator.style.background = 'url(imageURL)'; Commented Jun 27, 2022 at 21:30

1 Answer 1

1

Try this:

indicator.addEventListener('contextmenu', () => {
    indicator.style.backgroundImage = "url('your_image.png')";
    alert('msg');
})
Sign up to request clarification or add additional context in comments.

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.