How to program a button to change stylesheets with javascript - javascript

Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}

Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc

Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>

Related

I am not sure I can access the second html file using one js file, html element is showing as null when it is a button

I have 2 html files connected to one js file. When I try to access a html element in the second html file using js it doesn't work saying that is is null. I did
let elementname = document.getElementById("element") for a element in the second html page then
console.log(elementname) and it says it is null. When I do it for a element in the first html page it says HTMLButtonElement {}
Here is the html for the first Page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>Not Quuuuiiiizzzz</h1>
<h2>Join a quiz</h2>
<!--Buttons -->
<div style="text-align: center;">
<button id="btnforquiz1" onclick="gotoquiz()"></button>
<button id="btnforquiz2" onclick="gotoquiz1()"></button>
<button id="btnforquiz3" onclick="gotoquiz2()"></button>
</div>
<h2 id="h2">Create a Quuuuiiiizzzz</h2>
<script src="script.js"></script>
</body>
</html>
For the second page
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Not Quuuuiiiizzzz</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body onload="quizLoad()">
<h1 id="question">Hello</h1>
<button id="answer1"></button>
<button id="answer2"></button>
<button id="answer3"></button>
<button id="answer4"></button>
<script src="script.js"></script>
</body>
</html>
And Finally for the js file :
//setting global variables
let btn1 = document.getElementById("btnforquiz1") //getting button with id of btnforquiz1 repeat below
correct = 0
let btn2 = document.getElementById("btnforquiz2")
let btn3 = document.getElementById("btnforquiz3")
let question = document.getElementById("question")
let answer1 = document.getElementById("answer1")
let answer2 = document.getElementById("answer2")
let answer3 = document.getElementById("answer3")
let answer4 = document.getElementById("answer4")
quizNameRel = -1;
cosnole.log(question)
console.log(answer1)
//Quiz Data
Quiz_1 = {
"What is the capital of buffalo":["Idk", "Yes", "No",0],
"What is the smell of poop": ["Stinky"]
};
Quiz_2 = [
"What is wrong with you"
];
Quiz_3 = [
"What is wrong with you #2"
]
let quiz = {
name: ["History Test", "Math Practice", "ELA Practice"],
mappingtoans: [0,1,2],
QA: [Quiz_1, Quiz_2, Quiz_3]
}
//quiz data
//when body loades run showQuizzs function
document.body.onload = showQuizzs()
function showQuizzs() {
//loops throo the vals seeting the text for the btns
for (let i = 0; i < quiz.name.length; i++) {
btn1.textContent = quiz.name[i-2]
btn2.textContent = quiz.name[i-1]
btn3.textContent = quiz.name[i]
}
}
//leads to the showQuizzs
function gotoquiz() {
location.href = "quiz.html"
quizNameRel = quiz.name[0]//I was trying to create a relation so we could knoe which quiz they wnt to do
startQuiz()
}
function gotoquiz1() {
location.href = "quiz.html"
quizNameRel = quiz.name[1]
startQuiz()
}
function gotoquiz2() {
location.href = "quiz.html";
quizNameRel = quiz.name[2];
startQuiz();
}
function answerselect(elements){
whichone = Number(elements.id.slice(-2,-1))
if(Quiz_1[whichone]==Quiz_1[-1]){
correct+=1;
NextQuestion();
}else{
wrong+=1;
}
}
//gets the keys and puts it into an array
function getkeys(dictionary){
tempdict = [];
for(i in dictionary){
tempdict.push(i);
}
return tempdict;
}
function setQuestion() {
let tempdict = getkeys(Quiz_1)
console.log(tempdict, getkeys(Quiz_1));
//question.innerHTML = tempdict;
}
// startQuiz
function startQuiz() {
switch (quizNameRel){
case quiz.name[0]:
//case here
setQuestion()
break
case quiz.name[1]:
//case here
break
case quiz.name[2]:
//case here
break
}
}
//TO DO:
// Set the question
// Set the answer
// Check if correct button
This is happening because at a time you have rendered only one html file. For example if you render index1.html(first file) then your js will look for rendered element from first file only but here index2.html(second file) is not rendered so your js script is unable to find elements of that file that's the reason it shows null.
If you try to render now index2.html rather than index1.html then you will find now elements from index2.html are detected by js script but elements from index1.html are null now.

JavaScript querySelector not working when .value is added to it

I am creating my program which takes the user input on an Enter key.
I use the userInput with .value in the if statement and it works perfectly. But when I try to use it as a variable, nothing is outputted and nothing is in the console.
I tried to do querySelector("input['name = "command"]') to see if it might work but again, nothing outputted and it showed nothing in the console
var userInput = document.querySelector("input[name = 'command']")
var theInput = userInput.value.toLowerCase();
var theConsole = document.querySelector("#console");
theConsole.scrollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) {
acceptCommand();
setInterval(scrollUpdate, 1000)
}
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(theInput=== "help") theConsole.append("Help is given!", p);
//using the keywords
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input type = "text" name = "command" id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
</body>
</html>
Replace the div#console element:
<div id="console">
to this input:
<input type="text" id="console">
You will want to refer to userInput.value instead of theInput. Because theInput is set to the value at the time of setting the variable and it doesn't get updated even though the value of userInput changing.

Javascript/HTML Image Change

My task for my Javascript class is to create a script for this page that changes the image every 3 seconds. I think my code is correct, however Firebug tells me "document.getElementByID is not a function." Can someone show me what I am doing incorrectly?
This is my JS script.
<script type="text/javascript">
var i = 0
var lightArray = ["pumpkinOff.gif", "pumpkinOn.gif"]
var currentLight = document.getElementByID('light')
// ChangeLight Method Prototype
function changeLight() {
currentLight.src = lightArray[i++];
if (i == lightArray.length) {
i = 0;
}
}
setInterval(changeLight, 3000)
</script>
Here is my edited HTML code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JavaScript for Programmers</title>
</head>
<body>
<h2>Happy Halloween!</h2>
<img id="pumpkin" src="pumpkinoff.gif" alt="pumpkin">
<script src="../Script/spooky.js"></script>
</body>
</html>
Incorrect capitalisation on
var currentLight = document.getElementByID('light')
Should be:
var currentLight = document.getElementById('pumpkin')
I have attached a working fiddle:
http://jsfiddle.net/11csf4k2/
It's a typo it should be:
var currentLight = document.getElementById('light'); //Not ID
It should be Id not ID:
document.getElementById('light');
Also note that you don't have element with id light on your page. It probably should be
document.getElementById('pumpkin');

Javascript How do i compare two values and then change background color?

Why doesn't this code work? I want it to change the color of the input background whether the value is correct (green) or not (red).
<html>
<head>
<script type="text/javascript">
function funct1 () {
var username = "63XZ4";
if(username == document.getElementById('keygen').value ) {
document.getElementById('keygen').style.backgroundColor = '#5bc556';
}
else {
colorchange.style.backgroundColor = 'red';
}
}
return 0;
</script>
</head>
<body>
<input type="text" id="keygen">
<button onclick="funct1"></button>
</body>
</html>
<html>
<head>
<script type="text/javascript">
function funct1 () {
var username = "63XZ4";
var keygen = document.getElementById('keygen');
if(username == keygen.value) {
keygen.style.backgroundColor = '#5bc556';
} else {
keygen.style.backgroundColor = 'red';
}
}
</script>
</head>
<body>
<input type="text" id="keygen" />
<button onclick="funct1()">Button Title</button>
</body>
</html>
The above should help. Also, you may want to look into this:
Give more descriptive names to functions you declare.
Save time by eliminating calls to "getElementById" by storing DOM elements in variables.

How to pass div ids to javascript at onload?

I have an Html file like this:
<!doctype html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style/boxClass.css" />
<script type="text/javascript">
/* lightBox class */
function box (id1,id2) {
this.boxBackgroundDiv = document.getElementById (id1);
this.boxWorkAreaDiv = document.getElementById (id2);
}
lightBox.prototype.setBackgroundColor = function(c) {
this.boxBackgroundDiv.style.backgroundColor = c;
alert('Hello back');
};
function init (id1,id2)
{
boxObj = new box (id1,id2);
alert ("Hello");
}
</script>
</head>
<body onload="init('box1','box2')">
<div id="lightbox1" class="boxBackground">I am here</div>
<div id="lightbox2" class="boxWorkArea"><button onclick="boxObj.setBackgroundColor('Red')">I am here</button></div>
</body>
</html>
Now when I call my init function the way it is in this code via it works fine. But if I do as below via window.onload, it does not work. its not able to get the div ids in this case. But I need div ids to crate objs for my class.
<!doctype html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style/boxClass.css" />
<script type="text/javascript">
/* lightBox class */
function box (id1,id2) {
this.boxBackgroundDiv = document.getElementById (id1);
this.boxWorkAreaDiv = document.getElementById (id2);
}
lightBox.prototype.setBackgroundColor = function(c) {
this.boxBackgroundDiv.style.backgroundColor = c;
alert('Hello back');
};
function init (id1,id2)
{
boxObj = new box (id1,id2);
alert ("Hello");
}
window.onload = init ("box1",box2);
</script>
</head>
<body>
<div id="lightbox1" class="boxBackground">I am here</div>
<div id="lightbox2" class="boxWorkArea"><button onclick="boxObj.setBackgroundColor('Red')">I am here</button></div>
</body>
</html>
Two issues:
1) You are missing quotes around box2 parameter,
2) You are assigning the return value of init function (which here is a void) to window.onload handler.
You should assign the onload handler as below:
window.onload = function(){
init ("box1","box2");
}

Categories