How to use DOM to change background-size with radio buttons (JAVASCRIPT)


I want to ask if there is an alternative approach to this. I am very new to javascript

I have 3 radio buttons that will change the background-size of a DIV.
I managed to make it possible by using ternary in which it changes background size if its checked. DOM.
Apparently the Cover doesn’t work. I have tested multiple times but only the auto and contain works when the radio is checked. There is no default background size value in the css.
It seems like its default is auto, although Cover doesn’t work when checked while Contain does.
Thank you 😀
Here are the codes.

                <div class="radiobtn">

                <input type="radio" id="bgCOVER" name="radiobtnnm" value="COVER" onclick="backgroundfunc()">
                <label for="BGcover">Background Cover</label> 

                    <input type="radio" id="bgAUTO" name="radiobtnnm" value="AUTO" onclick="backgroundfunc()">
                <label for="BGauto">Background Auto</label> 

                    <input type="radio" id="bgCONTAIN" name="radiobtnnm" value="CONTAIN" onclick="backgroundfunc()">
                <label for="BGcontain">Background Contain</label> 
            </div>

JAVASCRIPT:

function backgroundfunc() {
var coverval = document.getElementById("bgCOVER");
document.getElementById("outputjs").style.webkitBackgroundSize = coverval.checked ? "cover" : "none";

var autoval = document.getElementById("bgAUTO");
document.getElementById("outputjs").style.backgroundSize = autoval.checked ? "auto" : "auto";

var containval = document.getElementById("bgCONTAIN");
document.getElementById("outputjs").style.backgroundSize = containval.checked ? "contain" : "none";

}

Source: CSS – Stack Overflow

November 24, 2021
Category : News
Tags: css | DOM | html | javascript

Leave a Reply

Your email address will not be published. Required fields are marked *

Sitemap | Terms | Privacy | Cookies | Advertising

Senior Software Developer

Creator of @LzoMedia I am a backend software developer based in London who likes beautiful code and has an adherence to standards & love's open-source.