A problem in Changeable Themes with JavaScript [closed] - javascript
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 9 months ago.
Improve this question
I tried to test myself in JavaScript so I decided to make changeable themes website in codepen with JavaScript this is my code:enter image description here
but it didn't work. please help me with it.
While #LoaiMasri was on a good track to solve the issue, there is still great way of improvement. Espacially to make the code shorter and more efficient if you have more themes to add.
First change you should consider over LoaiMasri's solution is to use a switch-statement over listing tons of if/else-statements.
However that will be to complicated for more then just a handfull of themes. The most efficient way is to add the themes through CSS. For that you do LoaiMasri's approach of using the value-attribute on the option tag. However give it a more direct value like theme-1, theme-2...
Then you use the script below:
document.getElementById('Themes').addEventListener('change', function() {
document.body.className = "";
let theme = document.getElementById("Themes").value;
document.body.classList.add(theme);
});
document.body.className = ""; -> This will remove all classes from the body-tag and works as a reset.
let theme = document.getElementById("Themes").value; -> That gets the value from the option-tag.
document.body.classList.add(theme); -> This will add now a class to the body-tag that equals the value of the option-tag.
All you now have to is to add classes to your CSS that equal the value of the option-tag. This will now solve the issue with 5 lines of JS code no matter how many themes you want to add (which is already smaller then LoaiMasri's solution).
document.getElementById('Themes').addEventListener('change', function() {
document.body.className = "";
let theme = document.getElementById("Themes").value;
document.body.classList.add(theme);
});
.theme-1 {
background-color: white;
color: black;
}
.theme-2 {
background-color: black;
color: white;
}
.theme-3 {
background-color: darkgray;
color: white;
}
<select id="Themes">
<option value="theme-1">White</option>
<option value="theme-2">Black</option>
<option value="theme-3">Dark</option>
</select>
document.getElementById("Themes").addEventListener("change", function () {
document.body.style.backgroundColor = this.value;
});
this is a answer but I recommended to add values as a number
like this code
<select id="Themes">
<option value="1">White</option>
<option value="2">Black</option>
<option value="3">Dark</option>
</select>
document.getElementById("Themes").addEventListener("change", function () {
let theme = document.getElementById("Themes").value;
if (theme == 1) {
document.body.style.backgroundColor = "white";
document.body.style.color = "black";
} else if (theme == 2) {
document.body.style.backgroundColor = "black";
document.body.style.color = "white";
} else if (theme == 3) {
document.body.style.backgroundColor = "darkgrey";
document.body.style.color = "white";
}
});
Related
JavaScript Background Color Toggle [closed]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers. This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers. Closed 3 years ago. Improve this question I have this simple function that is just simply supposed to toggle the background color of a button from aqua to red and back again. However, when I call this function, all it does is change it to red and I'm not sure why. I have looked at other similar examples on here and I feel like I'm doing it correctly. Would love some help! <button id = "button1" onclick="myFunction()">This is a button</button> button { background-color: Aqua; } function myFunction() { if (document.getElementById("button1").style.backgroundColor === "Aqua"){ document.getElementById("button1").style.backgroundColor = "Red"; document.getElementById("button1").innerHTML = "I'm RED!!"; } else { document.getElementById("button1").style.backgroundColor = "Aqua"; document.getElementById("button1").innerHTML = "I'm back BABY!!"; } }
it works like this if ($("#yourselector").css('background-color')=="rgb(220, 20, 60)") alert("matched"); you need to convert name to red, green, blue components, you might use this tool http://www.yellowpipe.com/yis/tools/hex-to-rgb/color-converter.php
The simplest wya to do this is to pass this into your onclick() function and use a ternary operator to determine the toggle state. function myFunction(btn) { const isRed = btn.style.backgroundColor === "red"; btn.style.backgroundColor = isRed ? "aqua" : "red"; btn.innerHTML = isRed ? "I'm back BABY!!" : "I'm RED!!"; } button { background-color: aqua; } <button id="button1" onclick="myFunction(this)">This is a button</button>
the first if statement should have lowercase aqua.. like the following function myFunction() { if (document.getElementById("button1").style.backgroundColor === "aqua") { document.getElementById("button1").style.backgroundColor = "red"; document.getElementById("button1").innerHTML = "I'm RED!!"; } else { document.getElementById("button1").style.backgroundColor = "aqua"; document.getElementById("button1").innerHTML = "I'm back BABY!!"; } } I found out by doing console.log(document.getElementById("button1").style); and in the log you will have the object where you can unfold and find that the css selector is in lowercase, also make red the same to avoid confusion. hope it helps
Program doesn't work and I don't know why [closed]
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers. This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers. Closed 6 years ago. Improve this question I am making a script that is supposed to display a button and a coloured circle on a webpage. When this button is pressed, it is supposed to change the colour of the circle. There are 3 colours which are supposed to be looped through so they should change, in order, every time I press the button. The issue is, when i run my code, it simply displays the coloured circle I chose when making the tag and doesn't change when I press the button. Here's my code: <!doctype html> <html> <head> <title>Traffic Lights</title> </head> <body> <img id="trafficimg" src="green.jpg" alt="Change Now!"> <button type="button" onClick="changelight()"> Change the Lights! </button> <script> var assets = ["red.jpg","yellow.jpg","green.jpg"] var state = 1 var colour = "" function changelight() { if state == 1{ var colour = "green"; if state == 2{ var colour = "orange"; if state == 3{ var colour = "red"; } if colour.includes("green"){ document.getElementById("trafficimg").setAttribute('src', assets[0]); state=state+1; if colour.includes("green"){ document.getElementById("trafficimg").setAttribute('src', assets[1]); state=state+1; if colour.includes("green"){ document.getElementById("trafficimg").setAttribute('src', assets[2]); state=state - 2; } } } </script> </body> </html> I would be helpful to get simple solutions that don't change the code too much if possible, though, any help is much appreciated. Thank you all.
You need to wrap the conditions in parenthesis if (state == 1) { // ^ ^ colour = "green"; // no need to redeclare color } // missing curly bracket at the end of if statement Working example with state as index for the image array. var assets = ["https://dummyimage.com/50x50/F00/000000&text=+", "https://dummyimage.com/50x50/FF0/000000&text=+", "https://dummyimage.com/50x50/0F0/000000&text=+"], state = 0; function changelight() { state++; // increment state state %= assets.length; // remainder operator for keeping state in range of array document.getElementById("trafficimg").setAttribute('src', assets[state]); } <img id="trafficimg" src="https://dummyimage.com/50x50/F00/000000&text=+" alt="Change Now!"><br> <button type="button" onClick="changelight()"> Change the Lights! </button>
Hi there are multiple errors (actually numerous) errors in your short snippet. BTW, I think you wanted to make this: var state = 1; var colour = "green"; function changelight(state) { if (state == 1){color = "green";} if (state == 2){color = "orange";} if (state == 3){color = "red";} switch(color){ case 'green': {document.getElementById("para1").style.background = 'green'; break;} case 'orange': {document.getElementById("para1").style.background = 'orange'; break;} case 'red':{document.getElementById("para1").style.background = 'red'; break;} } } <p id="para1" style="background:green;width:50px;height:50px;border-radius:50%;"></p> <button type="button" onClick="changelight(1)"> green</button> <button type="button" onClick="changelight(2)"> orange</button> <button type="button" onClick="changelight(3)"> red</button>
javascript make background color change every time you click [closed]
Closed. This question needs details or clarity. It is not currently accepting answers. Want to improve this question? Add details and clarify the problem by editing this post. Closed 7 years ago. Improve this question So i'm making this button which changes background-color when you click it, but when you click it again the color goes back to default(the color it was before you first clicked). this is my HTML: <span onclick="Switch(this)" class="button" id="button1">button</span> and my javascript: <script type="text/javascript"> function Switch(obj) { var div = document.getElementById(obj); if(div.style.backgroundColor === "#6DFC93"){ div.style.backgroundColor = "#27D956"; }else{ div.style.backgroundColor = "#6DFC93"; } } </script> Any suggestions?
What you can do is make an array of colors and use math.random to randomly pick a color from that array every time you click the button. its loads of fun to button mash the button! Hope this helps var myColors = ['red', 'purple', '#E84751', 'blue', 'orange', '#323643']; function clickMe(){ var randomize = Math.floor(Math.random()*myColors.length); $('.box').css("background-color", myColors[randomize]); } .THEbtn{ border: 1px solid #323643; border-radius: 50px; } .box{ margin-top: 10px; height: 300px; width: 100%; border: 1px solid black; border-radius: 5px; } <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button class='THEbtn' onclick='clickMe()'>Click Me</button> <div class='box'></div>
Referring to How to get hex color value rather than RGB value?, and considering that the parameter passed to the Switch function is already the current object, my solution is (the value obj.style.backgroundColor is in rgb format): var hexDigits = new Array("0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"); function rgb2hex(rgb) { if (rgb.trim().length == 0) { return ""; } var savedValue = rgb; rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/); if (rgb == null) { return savedValue; // if not RGB format } return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } function Switch(obj) { if(rgb2hex(obj.style.backgroundColor) == "#6DFC93"){ obj.style.backgroundColor = "#27D956"; }else{ obj.style.backgroundColor = "#6DFC93"; } } <span onclick="Switch(this)" class="button" id="button1">button</span>
you already have an object why do getElementById? function Switch(obj) { if(obj.style.backgroundColor === "#6DFC93"){ obj.style.backgroundColor = "#27D956"; }else{ obj.style.backgroundColor = "#6DFC93"; } }
If you want to change the color just after first clicking, then this should work fine. function Switch(obj) { obj.style.backgroundColor = "#27D956"; }
A slightly different route, which is applicable if you also have access to the CSS, is to simply toggle a class which changes the colour element.classList.toggle( 'button--isSwitched' ) Note that classList isnt supported absolutely everywhere but there are polyfills available. .button { background-color: blue; } .button--isSwitched { background-color: red; }
onmouseover function Javascript for changing the background of a section
I was trying to write a function that changes the color of background of a section by going over it with the mouse - using 'onmouseover'. I was looking for similar question and tried the solutions that was offered but it did not work on my code. Here is what i did: function Rectangle(count){ var newRec = document.createElement("SECTION"); newRec.style.width="202px"; newRec.style.height="312px"; newRec.style.border="1px solid #3f3f3f"; newRec.style.background = "#FFFFFF"; newRec.style.display = "inline-block"; newRec.style.margin= "44px"; newRec.style.size= "50px"; var appendRec = function() { document.addEventListener("onmouseover", myFunction); document.getElementsByTagName('main')[0].appendChild(newRec); }; function myFunction() { document.getElementTagName("SECTION").style.background = "#000000"; }; appendRec(); }; Can anyone tell me what i did wrong? And I was trying to work with the console but this code doesn't say anything is wrong...
document.getElementTagName("SECTION").style.background = "#000000"; is wrong. First, it's called getElementsByTagName(). And second, it returns an array, not just one element. Solution: Give the <section> an id and use getElementById() instead.
You just need document.getElementById('WhichElementWillBeHoveredID').onmouseenter = function() { // when entering element... } document.getElementById('WhichElementWillBeHoveredID').onmouseleave = function() { // when leaving element } Sure... you can easily use CSS as well.. SELECTOR:hover { background-color: #444 }
I created a fiddle to change background color and this is the only requirenment then I think it is good http://jsbin.com/cagawa/edit?html,css,output #mydiv{ background: #cccccc; } #mydiv:hover{ background: #ffdd00; }
try change var appendRec = function() { document.addEventListener("onmouseover", myFunction); document.getElementsByTagName('main')[0].appendChild(newRec); }; to var appendRec = function() { document.getElementsByTagName('main')[0].appendChild(newRec); newRec.addEventListener("mouseover", myFunction); }; I edited littlebit code, try now :)
If im not wrong on line 12: document.addEventListener("onmouseover", myFunction); should be replaced by document.addEventListener("onmouseover",myFunction());
Changing background Image depending on level in game javascript?
So I'm building a water pipe base game which can be seen here http://www.mckenziedave.co.uk/client_files/gabi_pipes/ I thought id post it rather than explain it. Im using HTML5 and JS script but I have hit a little problem, I wish to change the background depending on what level the user is on. Would this be best done by CSS or could I implement it into the java script? Instead of posting all the scripts I have just posted the level selector and level creator (the game board works on a basis of 0/1). $(document).ready(function(){ PipeGame.configure({ cols: 4, rows: 6, startX:0, StartY:0, lastX:3, lastY:5, godMode: true, autoStart: null }); var board =[[[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]], [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0]]]; PipeGame.setGameBoard(board); var slider = new Slider($(".options")) }); var Slider = function(el){ this.el = el; this.dragging = false; this.startx = this.el.offset().left; this.el.on("touchstart",this.startDrag.bind(this)); this.el.on("touchmove",this.drag.bind(this)); this.el.on("touchend",this.stopDrag.bind(this)); } Slider.prototype.startDrag = function(e){ this.startx = e.originalEvent.touches[0].pageX; this.dragging = true; } Slider.prototype.stopDrag = function(e){ this.dragging = false; } Slider.prototype.drag = function(e){ var pos = Math.round($(".plumbing-creator").position().left - (this.startx - e.originalEvent.touches[0].pageX) ); if(this.dragging){ this.el.css({left: pos +"px"}) } } var levels = { level1: [[["0","1","0","1"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","1","1"],["0","1","1","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","0","1","1"],["1","1","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","0","0","0"],["0","0","1","1"],["1","0","1","0"],["1","0","1","0"],["1","1","0","0"]]], level2: [[["0","1","1","0"],["0","1","1","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","1","1","0"],["0","1","1","0"],["0","0","0","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","0","0","0"],["0","1","1","0"],["0","1","1","0"],["0","0","0","0"],["0","0","0","0"]],[["0","0","0","0"],["0","0","0","0"],["0","0","0","0"],["0","1","1","0"],["0","1","0","1"],["0","1","1","0"]]], level3: [[["0","1","0","1"],["0","1","1","0"],["0","0","1","1"],["1","1","0","0"],["0","1","1","0"],["1","1","0","0"]],[["0","1","0","1"],["0","1","0","1"],["0","1","0","1"],["0","1","0","1"],["0","1","0","1"],["0","1","0","1"]],[["0","1","0","1"],["0","1","0","1"],["0","1","0","1"],["0","1","0","1"],["0","1","0","1"],["0","1","0","1"]],[["0","0","1","1"],["1","0","0","1"],["0","0","1","1"],["0","1","0","1"],["1","0","0","1"],["0","1","0","1"]]], } Anyone know of an easy way to change the background depending on the level?? Thank you :)
You should use CSS. For each level, you can create a different CSS class. Example: .level1 { background-color: red; } .level2 { background-color: blue; }
I can think of a couple ways off the top of my head depending on the rest of your code. 1) When a level changes, set a class on the body. JS document.getElementsByTagName('body')[0].className = 'level-whatever'; CSS body.level-whatever { background: do-what-you-want } 2) Just change the background with JS. var body = document.getElementsByTagName('body')[0]; body.style.backgroundImage = 'url("whatever-url")';
I notice that your main.js, which has the following configuration: PipeGame.configure({ cols: 4, rows: 6, startX:0, StartY:0, lastX:3, lastY:5, godMode: true, autoStart: null }); Is called everytime you visit a different arcade.html#* page. You could potentially add another configuration setting: background: level*, And change something based on that. To be honest, this is a pretty broad question with a lot of different ways to accomplish the task at hand. Applying a CSS rules based on your level (like so): var currentLevel = parseInt(window.location.hash.substring(1)) || 1; if(currentLevel == 1){ $("body").addClass("last-level"); $("body").style(...); } // Use as a Case Statement or have an array of level backgrounds, etc Seems to be the consensus here.