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 :D 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";
}
I found a solution 🤦🏻♂️ I made background size as default. so there will be only 2 choices since cover doesn't work. If there is a better approach in this problem, please let me know. I'll appreciate it. It will help me gain knowledge for future projects Thanks! :D
Maybe this will Help You:
var coverval = document.getElementById("BGcover");
var containval = document.getElementById("BGcontain");
var autoval = document.getElementById("BGauto");
function backgroundfunc(){
document.querySelector("body").style.backgroundSize = coverval.checked ? "cover" : "none";
document.querySelector("body").style.backgroundSize = autoval.checked ? "auto" : "auto";
document.querySelector("body").style.backgroundSize = containval.checked ? "contain" : "none";
}
body{
background:url('https://cdn.mos.cms.futurecdn.net/ntFmJUZ8tw3ULD3tkBaAtf.jpg');
background-size:auto;
}
<html>
<head>
</head>
<body>
<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>
</body>
</html>