Home > Net >  How can I apply background image on click without it getting overriden by background color?
How can I apply background image on click without it getting overriden by background color?

Time:08-27

I am making a sort of customization menu, where the user can select background images and colors for a few elements on the page. My issue is specifically with the body tag. The user can apply both a background color a transparent background image to the body, but the problem is.. if the user selects an image then the color, the background image gets removed.

I know where my issue is but I am not able to find a way to fix it.

so when you apply first the color, then the image this is what gets displayed:

<body style="background: url("./image/STARS.png";) rgb(255, 165, 2);">

but if you go back and select a color the style changes and the image gets overriden by the color selected like this:

<body style="background: rgb(255, 165, 2);">

How can I make it so that when the image is selected, for it to be applied in the "background-image="" tag in the style instead of in the background=""

Here is my JS for both: (the bottom one is the one that applies the image)

document.querySelectorAll('.theme-colors-menu .color').forEach(color => {
        color.onclick = () => {
            let background = color.style.background;
            document.querySelector('body').style.background = background;
        }
    });
    document.querySelectorAll('.theme-colors-img-bgr .color').forEach(bgrImg => {
        bgrImg.onclick = () => {
            let background = bgrImg.style.backgroundImage;
            document.querySelector('body').style.backgroundImage = background;
        }
    });

I have also tried this for the 2nd function but it was still applied in the background tag instead of the background-image one:

document.querySelectorAll('.theme-colors-img-bgr .color').forEach(bgrImg => {
        bgrImg.onclick = () => {
            let background = bgrImg.style.backgroundImage;
            $("body").css("background-image", background);
        }
    });

Can anyone tell me what is the issue here causing it to be in the background tag rather than the background-image?

CodePudding user response:

I got it to work, at the end I changed the top function to this and it solved my issue:

document.querySelectorAll('.theme-colors-menu .color').forEach(color => {
        color.onclick = () => {
            let background = color.style.background;
            $("body").css("background-color", background);
    });

CodePudding user response:

Color could be applied as background-color property.

<body style="background: url('./image/STARS.png'); background-color: rgb(255, 165, 2);">

Example of solution

  • Related