Dark mode script only works if script is in the index - javascript

I have 2 pages, each with the same code for the dark mode button.
The script on the index works, but the script in a different file doesn't. There are no errors.
Here is the script that doesn't work.
<body id = "body" class = "">
<h1 id="h1">Learn Chemistry!</h1>
start skill test
<form >
<h3 id="question"></h3>
<label for = "CO">CO:</label>
<input type = "text" id = "CO" class='input' autocomplete="off" placeholder="Answer">
<label for = "cb">Cl4Br5:</label>
<input type = "text" id = "cb" class='input' autocomplete="off" placeholder="Answer">
</form>
<button id = "check" onclick ="check()">Show answers</button>
<p id='demo'></p>
<form action='coming.html'>
<button id="next" onclick="next()">next</button>
</form>
<form action='index.html'>
<button id = "back" >back</button>
</form>
Here is the dark mode code in the same script.
<button id = "dark-btn" onclick = "darkMode();return false">Dark Mode</button>
<script src="script.js"></script>
Here is the Js function darkmode. (works only for the script in the index)
const labels=document.getElementsByTagName("labels")
const answers=document.getElementById("demo");
const content=document.getElementById("content");
const body = document.getElementById("body");
const heading1 = document.getElementsByTagName("h1")[0];
const heading3 = document.getElementsByTagName("h3")[0];
const buttons = document.getElementsByTagName("button")
const titles = [heading1, heading3,answers]
const time=document.getElementById("time");
const button = document.getElementById("dark-btn");
// console.log(labels.length);
let dark = false;
function darkMode() {
if (dark == false){
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "darks");
}
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "dark-btn");
}
for (let i = 0; i < labels.length; i++){
labels[i].setAttribute("class", "dark-txt");
}
let i = 0;
while (i < titles.length){
titles[i].setAttribute("class", "dark-txt");
i++;
}
body.setAttribute("class", "dark");
button.style.backgroundColor = "white";
button.style.color = "rgb(88, 119, 255)";
time.style.color = "white"
content.style.color="greenyellow"
dark = true;
} else {
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "dark-btn");
}
for (let i = 0; i < buttons.length; i++){
buttons[i].setAttribute("class", "");
}
for (let i = 0; i < labels.length; i++){
labels[i].setAttribute("class", "");
}
let i = 0;
while (i < titles.length){
titles[i].setAttribute("class", "");
i++;
}
body.setAttribute("class", "");
dark = false;
button.style.backgroundColor = "rgb(88, 119, 255)";
button.style.color = "white";
content.style.color="green"
}
}

#john
Here is the page that works. It is in the index.
<html >
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body id = "body" class = "">
<h1 id='h1'>Learn Chemistry!</h1>
<style>
#content{
color: green;
transform:translate(140px,30px);
line-height:6px;
font-family:sans-serif;
}
</style>
<img id="flask" src="https://www.pinclipart.com/picdir/big/1-11721_color-guard-clip-art.png">
<img id="flasktwo" src="https://www.pinclipart.com/picdir/big/1-11721_color-guard-clip-art.png">
<button type="button" id="time"
onclick="document.getElementById('date').innerHTML = Date()">
Date and Time.</button>
<p id="date"></p>
<form >
<button id="learn" name="learn"onclick="nextc();return false" >Learn</button>
</form>
<img class="example" src="c2.png">
<h3 id="title"></h3>
<p id="content"></p>
<button id="next" name="hi" onclick="nextc();return false" >Next</button>
<button id = "dark-btn" onclick = "darkMode();return false">Dark Mode</button>
<p id='demo'></p>
<!-- CONCEPTS -->
<!-- <body id = "body" class = ""> -->
<h3 class="title"></h3>
<button id="back">back</button>
<form id='next' action='q2.html'>
<button id="nexttwo" name="nexttwo" onclick="next()">Test</button>
</form>
<script src="script.js"></script>
</body>
</html>

Related

When I put removeEventListener in another conditional statement it doesn't work

I have tried to solve this problem for a week but I can't find any solutions.
When I put removeEventListener in the function MediaQuery3(z) it doesn't work.
I used MediaQuery to add an event for mobile phone users and removed it for desktop users.
let firstNumber=0;
let secondNumber = 0;
function MediaQuery3(z) {
let inputSearch = document.getElementById("input-search");
let searchBtn = document.getElementById("search-btn");
if (z.matches) {
if (firstNumber==0) {
searchBtn.addEventListener("click", clickSearch);
function clickSearch() {
if (inputSearch.style.display==="none") {
inputSearch.style.display="block";
} else{
inputSearch.style.display="none";
}
}
firstNumber=1;
secondNumber=0
}
} else{
if (secondNumber==0) {
searchBtn.removeEventListener("click", clickSearch);
inputSearch.style.display="block";
}
firstNumber=0;
secondNumber=1
}}
var z = window.matchMedia("(max-width: 430px)");
MediaQuery3(z);
z.addListener(MediaQuery3) ;
<!doctype html >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<body>
<nav class="navbar navbar-expand-sm navbar-dark">
<img src="d82a392b-6975-49e1-a8fd-a6e28a195b2b_200x200.png" alt="logo" id="logo-image">
<form class="form-inline" >
<button id="search-btn" type="button" ><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABD0lEQVRIie2UPW7CQBCFP5IS0gEnoQdyAxAHSQoUUSD+Gm4DIiegoITkAOEMJIQWTDFvwY3xrqFAUZ402rX95r2xvTPwV1EGRsAHsFOsgCFQula8BWyBKCF+gOY14gcJTYAqkFfUgKme7YFGqHg5Vnn7Au9NnG+gGGIw4lx5GmbiDkIMPpVU9eDWxV2FGPwqqeDBfRJ3m0Z8iO2jgGJyvsS4wVprxSPPcb5CDN61vngYvGqdeXBPKGFNFGFHMQkdcTZk6Oom1kSRqqtjP70APGNv6Tq6Gyru0MCaKGlUbCTurvtZTIpYEy2x47vTfsD5s8RNM5mkwY0MF+N/k7sy6bmbjzc0WGAzak7gGL9vHAG+Ol6n6x8u5AAAAABJRU5ErkJggg=="/></button>
<input id="input-search" class="form-control" type="text" placeholder="" aria-label="Search">
</form>
<img src="https://img.icons8.com/pastel-glyph/64/000000/shopping-cart--v1.png" id="cart">
</nav>
</body>
</html>
The listener you add with addEventListener has to be the exact same reference to the exact same function that you give to removeEventListener. But since you've defined clickSearch as a nested function, it is actually given a different reference every time MediaQuery3 is executed, because each one is bound to a different closure. If you move clickSearch outside of the function so it's not nested, the reference will be the same both times and it'll work properly.
let firstNumber = 0;
let secondNumber = 0;
function clickSearch() {
let inputSearch = document.getElementById("input-search");
if (inputSearch.style.display === "none") {
inputSearch.style.display = "block";
} else {
inputSearch.style.display = "none";
}
}
function MediaQuery3(z) {
let inputSearch = document.getElementById("input-search");
let searchBtn = document.getElementById("search-btn");
if (z.matches) {
if (firstNumber == 0) {
searchBtn.addEventListener("click", clickSearch);
firstNumber = 1;
secondNumber = 0;
}
} else {
if (secondNumber == 0) {
searchBtn.removeEventListener("click", clickSearch);
inputSearch.style.display = "block";
}
firstNumber = 0;
secondNumber = 1;
}
}
var z = window.matchMedia("(max-width: 430px)");
MediaQuery3(z);
z.addListener(MediaQuery3);
<!doctype html >
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<body>
<nav class="navbar navbar-expand-sm navbar-dark">
<img src="d82a392b-6975-49e1-a8fd-a6e28a195b2b_200x200.png" alt="logo" id="logo-image">
<form class="form-inline" >
<button id="search-btn" type="button" ><img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAABmJLR0QA/wD/AP+gvaeTAAABD0lEQVRIie2UPW7CQBCFP5IS0gEnoQdyAxAHSQoUUSD+Gm4DIiegoITkAOEMJIQWTDFvwY3xrqFAUZ402rX95r2xvTPwV1EGRsAHsFOsgCFQula8BWyBKCF+gOY14gcJTYAqkFfUgKme7YFGqHg5Vnn7Au9NnG+gGGIw4lx5GmbiDkIMPpVU9eDWxV2FGPwqqeDBfRJ3m0Z8iO2jgGJyvsS4wVprxSPPcb5CDN61vngYvGqdeXBPKGFNFGFHMQkdcTZk6Oom1kSRqqtjP70APGNv6Tq6Gyru0MCaKGlUbCTurvtZTIpYEy2x47vTfsD5s8RNM5mkwY0MF+N/k7sy6bmbjzc0WGAzak7gGL9vHAG+Ol6n6x8u5AAAAABJRU5ErkJggg=="/></button>
<input id="input-search" class="form-control" type="text" placeholder="" aria-label="Search">
</form>
<img src="https://img.icons8.com/pastel-glyph/64/000000/shopping-cart--v1.png" id="cart">
</nav>
</body>
</html>

How can I get my JavaScript carousel to work?

I can't get my carousel working. As far as I can tell the code is right, maybe you can see the problem? Here's the code...
<!DOCTYPE html>
<html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Randy's Webpage</title>
<link rel="stylesheet" type="text/css" href="Ani.css">
</head>
<body>
<div class= "scene">
<div class= "carousel">
<div class= "cell">1</div>
<div class= "cell">2</div>
<div class= "cell">3</div>
<div class= "cell">4</div>
<div class= "cell">5</div>
<div class= "cell">6</div>
<div class= "cell">7</div>
<div class= "cell">8</div>
<div class= "cell">9</div>
<div class= "cell">10</div>
<div class= "cell">11</div>
<div class= "cell">12</div>
<div class= "cell">13</div>
<div class= "cell">14</div>
<div class= "cell">15</div>
</div>
</div>
<div class= "carousel-options">
<p>
<label>
Cells
<input class= "cells-range" type= "range" min= "3" max= "15" value= "9" />
</label>
</p>
<p>
<button class= "previous-button">Previous</button>
<button class= "next-button">Next</button>
</p>
<p class= "pee">Orientation: </p>
<label>
<input type= "radio" name= "orientation" value= "horizontal" checked />
Horizontal
</label>
<label>
<input type= "radio" name= "orientation" value= "vertical" />
Vertical
</label>
</p>
</div>
</body>
</html>
<script>
var nextButton = document.querySelector(".next-button");
nextButton.aaddEventListener("click", function() {
selectedIndex++;
rotateCarousel();
});
var cellsRange = document.querySelector(".cells-range");
cellsRange.addEventListener("change", changeCarousel);
cellsRange.addEventListener("input", changeCarousel);
function changeCarousel() {
cellCount = cellsRange.value;
theta = 360 / cellCount;
var cellSize = isHorizontal ? cellWidth : cellHeight;
radius = Math.round(cellSize / 2 / Math.tan(Math.PI / cellCount));
for (var i = 0; i < cells.length; i++) {
var cell = cells[i];
if (i < cellCount) {
//visible cell
cell.style.opacity = 1;
var cellAngle = thetaa * i;
cell.style.transform =
rotateFn + ")" + cellAngle + "deg) translateZ(" + radius + "px)";
} else {
// hidden cell
cell.style.opacity = 0;
cell.style.transform = "none";
}
}
rotateCarousel();
}
var orientationRadios = document.querySelectorAll('input[name="orientation"]');
(function() {
for (var i = 0; i < orientationRadios.length; i++) {
var radio = orientationRadios[i];
radio.addEventListener("change", onOrientationChange);
}
})();
function onOrientationChange() {
var checkedRadio = document.querySelector(
'input[name="orientation"]:checked'
);
isHorizontal = checkedRadio.value == "horizontal";
rotateFn = isHorizontal ? "rotateY" : "rotateX";
changeCarousel();
}
//set initials
onOrientationChange();
</script>
</body>
</html>
The html and css work, i cant get the pictures to cycle through or the number of cells to change. so none of the javascript is working for some reason.
it keeps saying add more details even though i already have.
You've got an extra a in one of your event listeners
Change:
nextButton.aaddEventListener( 'click', function() {
selectedIndex++;
rotateCarousel();
});
to
nextButton.addEventListener( 'click', function() {
selectedIndex++;
rotateCarousel();
});

how could get children nodes by getElementsByClassName

I am trying to access to children of body by getElementById using following code:
function myFunction() {
var body = document.getElementById("textBody");
var x = body.getElementsByClassName("myDIV");
for(var i=0; i < x.length; i++) {
var y = x[i].getElementsByTagName("h1");
var z = x[i].getElementsByTagName("mynode");
for (var i = 0; i < y.length; i++) {
y[i].setAttribute("class", "democlass");
z[i].setAttribute("class", "democlass");
}
}
}
.democlass {
color: red;
}
<body id="textBody">
<div class="myDIV">
<h1 name="demoNode">Hello World</h1>
<mynode> hi there </mynode>
</div>
<div class="myDIV">
<h1 name="demoNode">Hello World</h1>
<mynode> hi there </mynode>
</div>
<h1 name="demoNode">Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>
<button onclick="myFunction()">Try it</button>
</body>
The code should color the header text into red color. But it seems not to be working for me. Would you please let me know why? What I know it could not have access to the exact nodes which I am waiting for.
In your styling you are referring to the democlass as a class whereas it is set as an id attribute. You can refer to my code for changes
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body class="textBody">
<div class="myDIV">
<h1 name="demoNode">Hello World</h1>
<mynode> hi there </mynode>
</div>
<div class="myDIV">
<h1 name="demoNode">Hello World</h1>
<mynode> hi there </mynode>
</div>
<h1 name="demoNode">Hello World</h1>
<p>Click the button to create a "class" attribute with the value "democlass" and insert it to the H1 element above.</p>
<button onclick="myFunction()">Try it</button>
</body>
<script>
function myFunction() {
//var body = document.getElementsByClassName("textBody"); (This code is not required)
var x = document.getElementsByClassName("myDIV");
for(var i=0; i < x.length; i++) {
var y = x[i].getElementsByTagName("h1");
var z = x[i].getElementsByTagName("mynode");
//initialise the second loop with a different variable
for (var j = 0; j < y.length; j++) {
y[j].setAttribute("id", "democlass");
z[j].setAttribute("id", "democlass");
}
}
}
</script>
<style type="text/css">
//Id reference for styling
#democlass {
color: red;
}
</style>
</html>

Javascript event handler is not working

I am trying to to increment/decrement a value in a paragraph when a button is clicked.
$(document).ready(function() {
var breakTime = 5;
var section = 25;
var start = "Start";
var stop = "Stop";
function Pomodoro(element, target) {
this.element = element;
this.target = target;
};
Pomodoro.prototype.incrementer = function incrementer() {
// this takes care of break and section timers incrementing
this.element.click(function() {
breakTime++;
var el = this.target;
el.html(breakTime);
});
};
// end
Pomodoro.prototype.decrementer = function decrementer() {
// this takes care of break and section timers incrementing
breakerDec.element.click(function() {
breakTime--;
var el = breakerDec.target.html(breakTime);
});
};
// end
var breakerInc = new Pomodoro();
var ele = $("#inner1");
var tar = $("#par");
breakerInc.element = ele;
breakerInc.target = tar;
breakerInc.incrementer.bind(breakerInc);
//end
var breakerDec = new Pomodoro();
breakerDec.element = $("#inner2");
breakerDec.target = $("#par");
breakerDec.decrementer();
var sectionInc = new Pomodoro($("#inner3"), $("#par2"));
sectionInc.incrementer.bind(sectionInc);
});
and i am getting no result when i click the button.
this is the html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Pomodoro Timer</title><!-- End of Title -->
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="wrapper">
<div class="top">
<div class="div div-1"><p id="par" class="breaktime-1">5</p>
<div class="inner-div inner-1"><button id="inner1" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner2" type="button" class="btn">-</button></div>
</div>
<div class="div div-2"><p id="par2" class="breaktime">25</p>
<div class="inner-div inner-1"><button id="inner3" type="button" class="btn">+</button></div>
<div class="inner-div inner-2"><button id="inner4" type="button" class="btn">-</button></div>
</div>
</div>
<div class="div div-3">
<h3 class="heading">section</h3>
<button type="button" class="btn-Start-Stop"></button
</div>
<div><p></p></div>
</div>
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script>
<script type="text/javascript" src="main.js"></script>
</body>
</html>
Here is one (trimmed-down) solution just using vanilla javascript:
function changeValue() {
var breaktime = this.parentNode.getElementsByClassName('breaktime')[0];
var val = breaktime.innerHTML;
if (this.className === 'increment') {
val++;
}
else if (this.className === 'decrement') {
val--;
}
breaktime.innerHTML = val;
}
function startStop() {
var values = [];
var breaktimes = document.getElementsByClassName('breaktime');
breaktimes[1].classList.toggle('decrementing');
if (breaktimes[1].classList.contains('decrementing') === true) {
values[1] = parseInt(breaktimes[1].innerHTML);
values[1]--;
breaktimes[1].innerHTML = values[1];
var decrementer = setInterval(function(){
values[0] = parseInt(breaktimes[0].innerHTML);
values[1] = parseInt(breaktimes[1].innerHTML);
if (breaktimes[1].classList.contains('decrementing') !== true) {
clearInterval(decrementer);
}
values[1]--;
breaktimes[1].innerHTML = values[1];
if (values[1] === values[0]) {
window.alert('The counter has reached ' + values[1]);
clearInterval(decrementer);
}
}, 1000);
}
}
var buttons = document.getElementsByTagName('button');
var startStopButton = buttons[(buttons.length -1)];
for (var i = 0; (i+1) < buttons.length; i++) {
buttons[i].addEventListener('click',changeValue,false);
}
startStopButton.addEventListener('click',startStop,false);
<section>
<div>
<p class="breaktime">5</p>
<button id="inner1" type="button" class="increment">+</button>
<button id="inner2" type="button" class="decrement">-</button>
</div>
<div>
<p class="breaktime">25</p>
<button id="inner3" type="button" class="increment">+</button>
<button id="inner4" type="button" class="decrement">-</button>
</div>
<div>
<h3>Section</h3>
<button type="button" class="btn-Start-Stop">Start / Stop</button>
</div>
<div>
<p></p>
</div>
</section>
If you'd like to implement logic using constructors, you can bind events inside of initialization of your instance.
Here is reworked your code based on your html. But code could be improved, so Pomodoro instance can be able not only to decrease or increase, but do both functions.
Also some template engine can give you ability to easy define amount of increase/decrease blocks you want to add to your page.

how to use addEventListener to get list of elements?

Can someone help out here? i have this project going on... i want that when the list items in the 'players' array are clicked, they should move to the 'actual-players' list. i want to use an event listener.... below are my codes...
JAVASCRIPT
function init(){
var players = ["Player1", "Player2", "Player3", "Player4",
"Player5"];
var listItems = document.getElementById("first");
for (var i = 0; i < players.length; i++){
var newPlayersList = document.createElement("li");
newPlayersList.ClassName = "list-item";
var listItemsValue = document.createTextNode(players[i]);
newPlayersList.appendChild(listItemsValue);
listItems.appendChild(newPlayersList);
}
//Below is where i write the codes to set the elements of the 'players' array to move to the 'actual-players' list. But it doesn't work!
var players = document.getElementsByClassName("list-item");
for(var i=0; i<players.length; i++){
players[i].addEventListener("click", function(){
var text = this.innerHTML;
var liElement = document.createElement("li");
liElement.ClassName = "test";
var text = document.createTextNode(text);
liElement.appendChild(text);
var lis = document.getElementById("actual-
players").getElementsByTagName("li");
if (lis.length == 4){
alert("Don't let more than four players");
} else {
document.getElementById("actual-
players").appendChild(liElement);
this.remove();
}
});
}
}
window.onload = function(){
init();
};
HTML
<html>
<head>
<title>Table Soccer Teams</title>
<link rel="stylesheet" type="text/css" href="soccer.css" />
<script type="text/javascript" src="table_soccer.js" ></script>
</head>
<body>
<a id="reset" href="javascript:location.reload(true)"
class="btn">Reset</a>
<div id="soccer_field">
<div class="players" onsubmit="return(validateForm ());">
<h2>Possible Players</h2>
<ul id="first"></ul>
<p class="one">Click on names above <br>to select actual
players</p>
</div>
<div class="actual_players">
<h3>Actual Players</h3>
<ul id="actual-players" ></ul>
<p class="two">Click button below to <br>generate Teams</p>
<br>
<a id="generate" href ="#" class="btn">Click here</a>
</div>
</div>
</body>
</html>

Categories