So basically, I am having troubles with a button that is supposed to change a website to dark mode. I also have a night mode, which makes the website go dark according to being after sunset or before sunrise in the current place of the user, and this night mode works. So I know it must be a problem regarding my js...
I have already tried first adding lightMode and then removing darkMode, but it did not work either...
<button
type="button"
class="btn btn-outline-secondary"
id="buttonChangeMode"
>
<i class="far fa-moon"></i>
</button>
.lightMode .app {
border: 1px solid #0b0b35;
padding: 20px 15px;
max-width: 1000px;
max-height: 2500px;
margin: 30px auto;
border-radius: 10px;
background-color: white;
}
.darkMode .app {
border: 1px solid #0b0b35;
padding: 20px 15px;
max-width: 1000px;
max-height: 2500px;
margin: 30px auto;
border-radius: 10px;
background-color: rgb(7, 8, 14);
}
function changeMode() {
let mode = document.getElementById("body");
if (mode.classList.contains("lightMode")) {
mode.classList.add("darkMode").remove("lightMode");
} else if (mode.classList.contains("lightMode")) {
mode.classList.remove("darkMode").add("lightMode");
}
}
let buttonChangeMode = document.querySelector("#buttonChangeMode");
buttonChangeMode.addEventListener("click", changeMode);
In the console, the error presented is: "Uncaught TypeError: Cannot read property 'remove' of undefined
at HTMLButtonElement.changeMode"
.toggle() method of .classList is the easiest way. If you use id you only limit your code use class whenever possible. Details are commented in demo.
// Pass Event Object
function changeMode(event) {
// Event.target always points to what user clicked, hovered over, changed etc,
const clicked = event.target;
// Reference body.all
const all = document.querySelector('.all');
// If the clicked tag has .mode class...
if (clicked.matches('.mode')) {
// Toggle .fa-sun, .btn-outline-dark, ,btn-outline-light, and .fa-moon on button.mode
clicked.classList.toggle('fa-moon');
clicked.classList.toggle('btn-outline-dark');
clicked.classList.toggle('fa-sun');
clicked.classList.toggle('btn-outline-light');
// Toggle .darkMode and .lightMode on body.all
all.classList.toggle('darkMode');
all.classList.toggle('lightMode');
}
return false;
}
// Reference button.mode
const mode = document.querySelector(".mode");
// Register button.mode to the click event
mode.addEventListener("click", changeMode);
.lightMode .app {
border: 1px solid #0b0b35;
padding: 20px 15px;
max-width: 1000px;
max-height: 2500px;
margin: 30px auto;
border-radius: 10px;
background-color: white;
}
.darkMode .app {
border: 1px solid #0b0b35;
padding: 20px 15px;
max-width: 1000px;
max-height: 2500px;
margin: 30px auto;
border-radius: 10px;
background-color: rgb(7, 8, 14);
}
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet">
<link href="https://use.fontawesome.com/releases/v5.9.0/css/all.css" rel="stylesheet" crossorigin="anonymous">
</head>
<body class='all lightMode'>
<main class='app container'>
<section class='row'>
<article class='col-6'>
<button class="mode btn btn-outline-dark far fa-sun" type="button"></button>
</article>
<figure class='col-6'>
<img src='https://branditprintit.com/wp-content/uploads/2017/04/logo-degin-logo-design-design-art-free.png' style='width:80%'>
</figure>
</section>
</main>
</body>
</html>
You did not give a HTML snippet - If your HTML <body> tag does not have an ID as follows:
<html>
...
<body id="body">
...
you will get that error because the result of the let mode = document.getElementById("body"); statement will be undefined, because the getElementById() function is expecting an argument of a DOM element ID value.
See https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById
You should add / remove classes like that:
<script>
function changeMode() {
let mode = document.getElementsByTagName("body")[0]; // set a variable for body tag
if (mode.classList.contains("lightMode")) {
mode.classList.add("darkMode")
mode.classList.remove("lightMode");
}
else {
mode.classList.add("lightMode")
mode.classList.remove("darkMode");
}
}
let buttonChangeMode = document.querySelector("#buttonChangeMode");
buttonChangeMode.addEventListener("click", changeMode);
</script>
You can read more here
Related
I have a button that is filled by 1. I want that when I click button, a p tag fill by 1.
That's I want to edit a html tag with javascript.
<!DOCTYPE html>
<html>
<head>
<style>
body{
background: linear-gradient(to bottom, rgb(75,83,119), rgb(33,35,53));
}
#btn1{
background: linear-gradient(to bottom, rgb(49,87,255), rgb(78,39,255));
box-shadow: 5px 5px 10px black;
border: 0px;
border-radius: 5px;
font-size: medium;
width: 110px;
height: 40px;
text-align: center;
margin(200px,200px,200px,200px);
transition-duration: 0.1s;
}
#btn1:active{
box-shadow: 0px 0px 0px black;
transform: translateY(3px);
transition-duration: 0.1s;
}
.textfield{
width: 500px;
height: 200px;
background: bisque;
margin-left: 150px;
margin-top: 100px;
}
</style>
<script>
b1(){
//Do some code here
}
</script>
</head>
<body>
<button id="btn1" onclick="b1();">1</button>
<p class="textfield"></p>
</body>
</html>
please tell me how can write the 1 in the p tag with javascript.
Of course I also wanna be able to write 11 or 1111.
You can get the text content of the element by getting the element itself, in case inside the click function of button, you can pass this ( which refers to the element that fires the event which is the button ), and get it's textContent, and then get p element by class using const p = document.querySelector('.textfield'), and add the value of the button inside by p.textContent += buttonValue
<!DOCTYPE html>
<html>
<head>
<style>
body{
background: linear-gradient(to bottom, rgb(75,83,119), rgb(33,35,53));
}
#btn1{
background: linear-gradient(to bottom, rgb(49,87,255), rgb(78,39,255));
box-shadow: 5px 5px 10px black;
border: 0px;
border-radius: 5px;
font-size: medium;
width: 110px;
height: 40px;
text-align: center;
margin(200px,200px,200px,200px);
transition-duration: 0.1s;
}
#btn1:active{
box-shadow: 0px 0px 0px black;
transform: translateY(3px);
transition-duration: 0.1s;
}
.textfield{
width: 500px;
height: 200px;
background: bisque;
margin-left: 150px;
margin-top: 100px;
}
</style>
<script>
function b1(button){
const buttonValue = button.textContent;
const p = document.querySelector('.textfield');
p.textContent += buttonValue
}
</script>
</head>
<body>
<button id="btn1" onclick="b1(this);">1</button>
<p class="textfield"></p>
</body>
</html>
If i understood correctly you need to listen for clicks on the button element. When the button is clicked you can add a "1" to the end of the <p> Element. You could get this value from the button content, or could add it as a variable or, like i did on my example, you can define it on a data-value attribute.
// Get the elements from the page
const button = document.querySelector('.button');
const textfield = document.querySelector('.textfield');
// Listen to click on the button
button.addEventListener('click', () => {
// Get the current value inside the textfield element
const currentText = textfield.innerHTML;
// Add the "data-value" to the end of the current text
const newText = currentText + button.getAttribute('data-value');
// Replace the text on the p element with the new text
textfield.textContent = newText;
})
<button class="button" data-value="1">Click me</button>
<p class="textfield">Your p: </p>
I have a problem with my div when I write in the text area and hit save nothing is show up. I have a problem with my div when I write in the text area and hit save nothing is show up
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Go from idea to action in seconds with wesam to do list">
<title>wesam list to do</title>
<script>
function input() {
var name = document.getElementById("text").Value
document.getElementById("output").innerHTML = name;
}
</script>
<style>
#b {
background-color: red;
}
#output {
width: 100%;
height: 200px;
background-color: black;
color: black;
}
</style>
</head>
<body>
<form>
<h1> Add your tasks </h1>
<textarea id="text"></textarea>
<button onClick="input()" id=" b " type="button "> save</button>
<div id="output"></div>
</body>
Try this. There were a few issues with this code. I added comments to the changes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="Go from idea to action in seconds with wesam to do list">
<title>wesam list to do</title>
<script>
function input(event) {
//added preventDefault() to keep the page from reloading
event.preventDefault();
//changed Value to value - watch your case
var name = document.getElementById("text").value;
document.getElementById("output").innerHTML = name;
}
</script>
<style>
#b {
background-color: red;
}
#output {
width: 100%;
height: 200px;
background-color: black;
/*changed the text color from black to white so you can see when the output is added*/
color: white;
}
</style>
</head>
<body>
<form>
<h1> Add your tasks </h1>
<textarea id="text"></textarea>
<button onClick="input(event)" id="b" type="button"> save</button>
<div id="output"></div>
</form>
</body>
</html>
Cheers!
Your output element has both a black background, and black text, so you won't see anything change.
You were missing a </form> tag.
It looks like you're trying to create a list of tasks, and each time you add a new task, and click "save" it adds a new task under the proceeding ones.
Here's an updated example that uses more modern JS methods that you might find useful. Links to the relevant documentation are at the bottom of the post.
// First we cache all our elements
const task = document.querySelector('textarea');
const list = document.querySelector('ul');
const button = document.querySelector('button');
// Instead of inline JS we add an event listener to
// the cached button element.
button.addEventListener('click', handleClick, false);
// `focus` the cursor in the textarea
task.focus();
function handleClick() {
// We create a new list item
const item = `<li>${task.value}</li>`;
// We add that to the list
list.insertAdjacentHTML('beforeend', item);
// Reset the textarea value
task.value = '';
// And refocus on it so we don't have to
// manually click in it to write a new task
task.focus();
}
button { background-color: red; color: white; }
<form>
<h3>Add your tasks</h3>
<textarea></textarea>
<button type="button">Save task</button>
</form>
<ul></ul>
Addition documentation
querySelector
Template/string literals
insertAdjacentHTML
addEventListener
There are couple problem:
You didn't close the form tag in HTML
you write the first letter of value as capital in input function
And you may did not look but your button background color is not coming that is because there is spaces inside the id in HTML just remove those and you're good to go.
And make a paragraph inside the output div and give him the id of output and than stor that into a variable and do o.innerText o is you output paragraph = i.value i is your input
I have added some features to to your application if you want to copy it i do not mined -
// ES6 Syntax
const render = () =>{
// Getting the value from HTML DOM to inputEl variable
const inputEl = document.getElementById('text');
// Getting the output paragraph from HTML DOM and storig it into output
const outputEl = document.getElementById('output-text');
// Rendering the inputEL value into outputEl
outputEl.textContent = inputEl.value;
}
// ES5-- Syntax
function renderES(){
// Getting the value from HTML DOM to inputEl variable
const inputEl = document.getElementById('text');
// Getting the output paragraph from HTML DOM and storig it into output
const outputEl = document.getElementById('output-text');
// Rendering the inputEL value into outputEl
outputEl.textContent = inputEl.value;
}
#import url('https://fonts.googleapis.com/css2?family=Nunito&display=swap');
:root{
--primary-color: rgb(26, 26, 26);
--secondary-color: white;
--font-family: Nunito, sans-serif;
--box-shadow: rgb(0 0 0) 1px 1px 3px 0px inset, rgb(48 48 48 / 50%) -1px -1px 3px 1px inset;;
--all-transition:transform ease-in-out 0.3s 0s;
}
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
body{
font-family: var(--font-family);
}
.main-content{
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.container{
border-radius: 10px;
box-shadow: var(--box-shadow);
width: 85%;
height: 270px;
display: flex;
justify-content: space-between;
align-items: center;
background-color: var(--primary-color);
flex-direction: column;
}
.container>h1{
margin-top: 15px;
color: var(--secondary-color);
text-transform: uppercase;
}
form{
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
padding: 5px;
width: 100%;
height: 75%;
}
form>textarea{
width: 95%;
height: 30%;
background-color: var(--primary-color);
border: none;
border-radius: 10px;
box-shadow: var(--box-shadow);
padding: 15px;
color: var(--secondary-color);
}
#output{
width: 95%;
height: 40%;
background-color: var(--primary-color);
box-shadow: var(--box-shadow);
color: var(--secondary-color);
padding: 10px;
}
form>button{
background-color: var(--primary-color);
box-shadow: var(--box-shadow);
width: 95%;
height: 30px;
border-radius: 10px;
border: none;
font-weight: bold;
margin-bottom: 10px;
color:var(--secondary-color);
transition: var(--all-transition);
cursor: pointer;
}
/* NTH CHILD */
form>textarea::placeholder{
color: var(--secondary-color);
}
/* Animations */
form>button:hover{
transform: scale(1.02)
}
form>button:active{
border: 1px solid var(--secondary-color);
}
<!doctype HTML>
<html>
<head>
<title>codedamn HTML Playground</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/style.css" />
</head>
<body>
<div class="main-content">
<div class="container">
<h1> Add your tasks </h1>
<form>
<textarea id="text" placeholder="Enter you task here.."></textarea>
<div id="output">
<p id="output-text"></p>
</div>
<button
type="button"
id="addtask-btn"
onclick="render()">
Save
</button>
<form>
</div>
</div>
<script src="/script.js"></script>
</body>
</html>
It seems that you haven't ended the
<form>
tag
I tried creating simple popup leaving site consent.
demo: See demo on codepen
function exModal() {
const modalhtml=` <div class="modal-header">
🔗 You're Leaving Our Site!
<span class="close-modal">×</span>
</div>
<div class="modal-body">
This is a link to an external site. Click OK to continue to the content. Feel free to comeback again. Make Sure To Follow Instructions Properly.
<br/><br/>
<div class="show-link"></div>
</div>
<div class="modal-footer">
<button class="close-modal">Close</button>
<button class="confirm-modal">OK</>
</div> `;
const getlink = document.querySelector('.ex-link').getAttribute('data-href');
const extra=document.createElement('div');
extra.classList.add('modal-content');
extra.innerHTML=modalhtml;
document.body.appendChild(extra);
document.querySelector('.show-link').innerHTML='('+getlink+')';
const close=document.querySelectorAll('.close-modal');
document.querySelector('.confirm-modal').addEventListener('click', (e) => {
window.open(getlink, '_blank');
});
let i;
for (i = 0; i < close.length; i++) {
close[i].addEventListener('click', (e) => {
extra.remove();
});
}
}
Problem
How can I prevent the purple button from being clicked when the modal is open.
also I want to add function like when someone click ok button, It'll close the modal while opening link in other tab.
can I handle two event in with one event listener? (reference to (2) problem) then how?
A good reference will do the job. I tried googling but mostly those tutorial includes jquery or other script
Here's what I did:
I replaced
<a class="ex-link" data-href="https://www.techlegionbd.com" onclick="exModal()">Tech Legion BD</a>
with
<button class="ex-link" type="submit">Tech Legion BD</button>
in CSS I replaced
a.ex-link {
...
}
with
button.ex-link {
Finally I used a functional approach to rewrite the scrpt thus:
CSS
button.ex-link {
width: 150px;
display: block;
margin: 10px auto;
padding: 20px;
border: 1px solid white;
background-color: #6600d6;
color: white;
font-family: 'Martel Sans', sans-serif;
font-weight: 800;
text-align: center
}
.modal-content {
position: fixed;
top: 30%;
left: 50%;
margin-left: -190px;
max-width: 380px;
border: 2px dotted #008080;
}
.modal-header {
font-size: 20px;
padding: 15px;
border-bottom: 1px solid #cecece;
background: #edfdfe;
}
.modal-body {
padding: 20px;
text-align: center;
border-bottom: 1px solid #cecece;
}
.modal-footer {
padding: 10px;
background: #edfdfe;
}
.modal-footer>button {
padding: 6px 10px;
margin-left: 5px;
cursor: pointer;
width: 50px;
background: #75e4d5;
border: 1px solid #008080;
border-radius: 4px;
}
.modal-header>.close-modal {
position: absolute;
right: 0;
top: 0;
padding: 15px;
cursor: pointer;
}
HTML
<!-- <a class="ex-link" data-href="https://www.techlegionbd.com" onclick="exModal()">Tech Legion BD</a>-->
<button class="ex-link" type="submit">Tech Legion BD</button>
JAVASCRIPT
const openModalButton = document.querySelector("button");
const extra = document.createElement('div');
const getlink = "https://www.techlegionbd.com";
const modalhtml = ` <div class="modal-header">
🔗 You're Leaving Our Site!
<!-- <span class="close-modal">×</span>-->
</div>
<span class="close-modal" onclick="closeModal()">×</span>
</div>
<div class="modal-body">
This is a link to an external site. Click OK to continue to the content. Feel free to comeback again. Make Sure To Follow Instructions Properly.
<br /><br />
<div class="show-link"></div>
</div>
<div class="modal-footer">
<!--<button class="close-modal">Close</button>-->
<button class="close-modal" onclick="closeModal()">Close</button>
<button class="confirm-modal">OK</>
</div> `;
function openModal() {
//refewnce variables
extra.classList.add('modal-content');
extra.innerHTML = modalhtml;
document.body.appendChild(extra);
document.querySelector('.confirm-modal').addEventListener('click', (e) => {
window.open(getlink, '_blank');
});
}
openModalButton.addEventListener("click", () => { openModal() })
function closeModal() {
document.body.removeChild(extra);
}
I'm trying to code a Sudoku generator in JavaScript and I think I did it.
My problem is for visualizing the generated solution inside the input tags I use for the game.
I put this function on the property onload of the body of my html page:
function begin() {
var container=document.getElementById("container");
var div;
for(var i=0; i<9; i++) {
div=document.createElement("div");
div.id=i;
div.setAttribute("class", "square");
for(var j=0;j<9;j++) {
var square=document.createElement("input");
square.setAttribute("type", "text");
square.setAttribute("maxlength", "1");
if(i%2==0) {
square.setAttribute("class", "square1");
}
else {
square.setAttribute("class", "square2");
}
div.appendChild(square);
}
container.appendChild(div);
}
}
And it works perfectly fine, since it show 9 squares (the divs), each with 9 small squares inside(the inputs).
Now the last function is, to show the result is:
function showSudoku(sudoku, i) {
var container = document.getElementById("container");
var cells = container.getElementsByTagName("input");
for(var j=0; j<81; j++)
cells[j].value = sudoku[j];
}
but I get the error
Uncaught TypeError: Cannot read property 'getElementsByTagName' of null
For some reason the variable container is not initialized with the element identified with the id container. Can anyone help me?
[EDIT]
Here is the HTML code:
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="utf-8">
<title>Sudoku</title>
<style type="text/css">
body {
text-align: center;
}
#game {
width: 21.2em;
height: 21.15em;
margin: auto;
border: 2px solid #777777;
}
#container {
width: 21.2em;
height: 21.2;
margin: auto;
}
.square {
width: 6.94em;
height: 6.94em;
display: inline-block;
border: 1px solid #A9A9A9
}
.square1 {
height: 3em;
width: 3em;
background-color: white;
border: 1px dashed #CBCBCB;
color: black;
display: inline-block;
}
.square2 {
height: 3em;
width: 3em;
background-color: #DDDDDD;
border: 1px dashed #CBCBCB;
color: black;
display: inline-block;
}
input {
text-align: center;
}
</style>
<script type="text/javascript" src="sudoku.js">
</script>
</head>
<body onload="begin()">
<div id="levels">
<label><input type="radio">Easy</label>
<label><input type="radio">Medium</label>
<label><input type="radio">Hard</label>
</div>
<div id="buttons">
<button id="newgame" onclick="newGame()">NEW GAME</button>
<button id="solve">SOLVE</button>
</div>
<br>
<div id="game">
<div id="container">
</div>
</div>
<br>
<div id="time">
<input id="currentTime" type="text" readonly="readonly">
</div>
</body>
</html>
The buttons and the inputs radio are still unused.
hey you are messing with tagname since you would not specify which input type you are wanting to append in the javascript.
so you should have to go like this as follows:
var nodeLists = document.getElementsByTagName("input");
for(node in nodeLists){
if(nodeLists[node].getAttribute('type') == "text"){
//write code here as you want
}
else{
}
}
I have a table in a jsp and want to create a pop up window when clicking on a table. Included is a jsfiddle with code and an attempt to connect javascript with a specific row but have not had success creating a pop-up.
This fiddle is an example - code I have currently includes a java for loop creating each tr with specific info from a database.
<tr OnClick="display('test');">
<td><strong>showSpeed</strong></td>
<td>15</td>
<td>The speed of the show/reveal</td>
</tr>
<script>function display(test) {
//display a pop up?
}</script>
https://jsfiddle.net/y2y1w24L/1/
Thank you.
You can use JQuery UI to display a nice popup. This code was made merging your code with the example found here: http://jqueryui.com/dialog/
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<!--<link rel="stylesheet" href="/resources/demos/style.css">-->
</head>
<body>
<script>
function display(test) {
$("#dialog").dialog();
}
</script>
<table>
<tr onclick="display('test');">
<td><strong>showSpeed</strong></td>
<td>15</td>
<td>The speed of the show/reveal</td>
</tr>
</table>
<div id="dialog" title="Basic dialog" style="display:none">
<p>This is the default dialog which is useful for displaying information. The dialog window can be moved, resized and closed with the 'x' icon.</p>
</div>
</body>
</html>
That's one option. You can also take a look at bootstrap modals found here: http://getbootstrap.com/javascript/#modals
Inside your function "display", event.target will give you a reference to whatever the user clicked:
function display(test) {
alert(event.target.outerHTML);
}
https://jsfiddle.net/y2y1w24L/2/
You should be able to use that to display the appropriate popup.
May this help you
var PopUP=document.createElement("div");
PopUP.className="PopUP";
PopUP.innerHTML="<div id='mainDivBack' style='display:block;'><div id='PopUpDiv' style='display:block;'>"+" Welcome"+ "<input type='button' value='x' id='btnClose' style='display:block;' onclick='popClose();'/></div></div>";
document.body.appendChild(PopUP);
function popClose() {
document.getElementById("btnClose").style.display = 'none';
document.getElementById("PopUpDiv").style.display = 'none';
document.getElementById("mainDivBack").style.display = 'none';
}
function display(test) {
PopUP.innerHTML="<div id='mainDivBack' style='display:block;'><div id='PopUpDiv' style='display:block;'>"+test+ "<input type='button' value='x' id='btnClose' style='display:block;' onclick='popClose();'/></div></div>";
document.getElementById("btnClose").style.display = 'block';
document.getElementById("PopUpDiv").style.display = 'block';
document.getElementById("mainDivBack").style.display = 'block';
}
and CSS for this
#btnClose
{
background: none repeat scroll 0 0 #dd2904;
border: 1px solid #c13031;
color: white;
font-size: 18px;
font-weight: bold;
margin: 5px;
padding: 0 1px 4px;
position: absolute;
right: 10px;
top: 0;
}
#btnClose:hover
{
background: none repeat scroll 0 0 #ff4565;
}
#PopUpDiv
{
background: none repeat scroll 0 0 lightgray;
border: 1px solid gray;
border-radius: 8px;
box-shadow: 1px 1px 12px 3px white;
font-family: "Lucida Console" ,arial;
height: 70px;
padding: 35px;
position: absolute;
width: 300px;
}
#mainDivBack
{
background: radial-gradient(lightgray, transparent) repeat scroll 0 0 transparent;
height: 100%;
left: 0;
padding: 20% 25%;
position: fixed;
top: 0;
width: 100%;
}
.Grid
{
background-color: #fff;
border: 1px solid #525252;
border-collapse: collapse;
color: #474747;
float: left;
font-family: Calibri;
width: 99%;
}