bpoklar
bpoklar

Reputation: 69

Javascript events with checkbox (checked, unchecked)

I would like to compare this two javascript codes. My goal was to use javascript and checkbox to create toggable switch from colors a to colors b. In my final project it will be used to switch from day to night scene. I would like to know why the code withouth "EventListener" is not working? Also I would like to know if there is better solution to attach new classes or to switching between classes.

Working:

var sw = document.getElementById("sw");
var box1 = document.querySelector(".skatla1");
var box2 = document.querySelector(".skatla2");

function day() {
    box1.classList.remove("night");
    box2.classList.remove("night2");
}

function night() {
    box1.classList.add("night");
    box2.classList.add("night2");
}

sw.addEventListener('change', (event) => {
  if (event.target.checked) {
    day();
  } else {
    night();
  }
})
.box {
    width: 100%;
    height: 50vh;
    display: flex;
    justify-content: center;
    align-items: center;
}

input[type="checkbox"] {
    width: 100px;
    height: 100px;
}

.day {
    background: lightgray;
}

.day2 {
    background: rgb(141, 141, 141);
}

.night {
    background: rgb(78, 78, 78);
}

.night2 {
    background: rgb(37, 37, 37);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Day night</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="skatla1 box day night">
        <input id="sw" type="checkbox" name="switch" id="">

    </div>
    <div class="skatla2 box day2 night2">Box 2</div>
</body>
<script src="script.js"></script>
</html>

Not working:

function day() {
    box1.classList.remove("night");
    box2.classList.remove("night2");
}

function night() {
    box1.classList.add("night");
    box2.classList.add("night2");
}

function stikalo() {
    if (sw.checked === true){
        day();
    } else {
        night();
    }
}

Upvotes: 1

Views: 163

Answers (1)

Antonio Esposito
Antonio Esposito

Reputation: 301

If you want that your code works with function stikalo() without EventListener you have to change your input as:

<input id="sw" type="checkbox" name="switch" onclick="stikalo()">

Upvotes: 2

Related Questions