1

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();
    }
}

3
  • Not working because there is no function call for stikalo Commented Mar 26, 2019 at 13:33
  • I have also tried with: stikalo() and is it not working. Commented Mar 26, 2019 at 13:41
  • skadookie() isn't listening for any events Commented Mar 26, 2019 at 14:07

1 Answer 1

2

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()">
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.