New to JS. Im trying to get my color button and other buttons working, where on clicking the color button, the grid blocks will be colored in black after mouseover. I'm trying to add eventlisteners in the play function to change the backgroundcolor of gridSquare, but can't because of the scope. How would i go about doing this?
JS
const colorBtn = document.getElementById('color')
const eraseBtn = document.getElementById('erase')
const clearBtn = document.getElementById('clear')
const gridCont = document.getElementById('grid')
let currentMode = ''
// creates grid on pageload
function makeGrid() {
for (i=0; i<1600; i++) {
let gridSquare = document.createElement('div')
gridCont.appendChild(gridSquare)
gridSquare.classList.add('gridSquare')
}
}
window.onload = makeGrid()
//
colorBtn.addEventListener('click', () => {
currentMode = 'color'
})
eraseBtn.addEventListener('click', () => {
currentMode = 'erase'
})
clearBtn.addEventListener('click', () => {
currentMode === 'clear'
})
function play() {
if (currentMode === 'color') {
}
}
window.onload = play()
HTML
<!DOCTYPE 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.0">
<title>scribblyscrabblydoo</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="titlebox">
<h1>sribblyscrabblydoo</h1>
<p>Draw or something idk bro</p>
</div>
<div class="mainbod">
<div class="options">
<div class="buttons">
<h2>Options</h2>
</div>
<div class="buttons">
<button id="color">Color</button>
</div>
<div class="buttons">
<button id="erase">Erase</button></div>
<div class="buttons">
<button id="clear">Clear</button>
</div>
<div class="buttons">
<button id="github">Duskope Github</button>
</div>
</div>
<div id="grid"></div>
</div>
</body>
<script type="text/javascript" src = "index.js"></script>
</html>
https://duskope.github.io/scribblyscrabblydoo/
To solve the background color issue, its actually just a typo.
Change your play function to this
Fyi, you're gonna run into another issue of it making EVERYTHING black. So add some conditionals.
function play() {
document.querySelectorAll('.gridSquare').forEach((item) => {
addEventListener('mouseover', (e) => {
e.target.style.backgroundColor = 'black'
})
})
}
Related
New to JS. For my etch-a-sketch project i cant seem to set a style on my grid divs when the color mode is active and the mouse goes over them. Been trying to fuck around with the scopes but im still getting used to it. TypeError e.target.style.backgroundColor is not a function.
const colorBtn = document.getElementById('color')
const shadeBtn = document.getElementById('shade')
const eraseBtn = document.getElementById('erase')
const clearBtn = document.getElementById('clear')
const gridCont = document.getElementById('grid')
let currentMode = ''
let gridSquare = document.createElement('div')
// creates grid on pageload
function makeGrid() {
for (i=0; i<200; i++) {
gridSquare
gridCont.appendChild(gridSquare)
gridSquare.classList.add('gridSquare')
}
}
window.onload = makeGrid()
//
colorBtn.addEventListener('click', () => {
currentMode = 'color'
})
shadeBtn.addEventListener('click', () => {
currentMode = 'shade'
})
eraseBtn.addEventListener('click', () => {
currentMode = 'erase'
})
clearBtn.addEventListener('click', () => {
gridSquare.style.backgroundColor('white')
})
function play() {
if ( currentMode === 'color' || currentMode === '') {
gridSquare.addEventListener('mouseover', (e) => {
e.target.style.backgroundColor('#050505')
})
}
}
window.onload = play()
<!DOCTYPE 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.0">
<title>scribblyscrabblydoo</title>
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<div class="titlebox">
<h1>sribblyscrabblydoo</h1>
<p>Draw or something idk bro</p>
</div>
<div class="mainbod">
<div class="options">
<div class="buttons">
<h2>Options</h2>
</div>
<div class="buttons">
<button id="color">Color</button>
</div>
<div class="buttons">
<button id="shade">Shade</button>
</div>
<div class="buttons">
<button id="erase">Erase</button></div>
<div class="buttons">
<button id="clear">Clear</button>
</div>
<div class="buttons">
<button id="github">Duskope Github</button>
</div>
</div>
<div id="grid"></div>
</div>
</body>
<script type="text/javascript" src = "index.js"></script>
</html>
blah blah blah too much code not enough details to post
Because it's not a function.
You should use:
e.target.style.backgroundColor = '#050505'
The error description is telling you the exact issue, you are calling backgroundColor as a function when it is a property.
I fetch data, make it an object and print it's properties. I then need to update sensor.value - if readonly is false - with the press of a button, making it go from true to false and viceversa. How can I do it?
index.html
<head>
<link rel="stylesheet" href="style.css" />
<meta charset="UTF-8" />
<meta name="viewport"
content="width=device-width, initial-scale=1.0" />
<title>Sensors</title>
</head>
<body>
<h1>Sensors</h1>
<div class="container" id="container"> </div>
<script src="sensor.js"></script>
<script src="script.js"></script>
</body>
script.js
const container = document.getElementById("container");
// api url
const api_url =
"https://hf3xzw.deta.dev/";
// Defining async function
fetch(api_url)
.then((r) => r.json()) // (1)
.then((body) => {
for (let index = 0; index < 8; index++) {
const sensor = JSONToSensor(body["sensors"][index]);
let newCard = document.createElement("div");
newCard.classList.add("card");
newCard.innerHTML = `<br>
<h2><span style="font-weight: normal;">Description: </span>${sensor.description}</h2>
<h2><span style="font-weight: normal;">ID: </span>${sensor.id}</h2>
<h2><span style="font-weight: normal;">Lat: </span>${sensor.lat}</h2>
<h2><span style="font-weight: normal;">Lng: </span>${sensor.lng}</h2>
<h2><span style="font-weight: normal;">Place: </span>${sensor.place}</h2>
<h2><span style="font-weight: normal;">Read Only: </span>${sensor.readonly}</h2>
<h2><span style="font-weight: normal;">State Code: </span>${sensor.state_code}</h2>
<h2><span style="font-weight: normal;">Value: </span>${sensor.value}</h2>
`;
container.appendChild(newCard);
}
});
Edit: forgot to rewrite the attempts I made to make it work.
First attempt
<button type="button" onclick="document.getElementById('container').innerHTML = 'Hey There'">Try it</button>
Second attempt
if (sensor.readonly == false) {
let btn = document.createElement("button");
btn.innerHTML = "Change value";
btn.onclick = function () {
change();
}
container.appendChild(btn);
}
function change() {
if (sensor.value == true)
sensor.value == false;
else
sensor.value == true;
container.appendChild(newCard);
}
I've seen something similar to this and tried to implement but I don't really understand what I'm doing
i started an app todoslist , after creating first code simply of adding new todos in DOM
now my task is this :
addtodo :
// grab todo value
// pu tit in the array
// tell the draw method to redraw the todos
drawtodo :
grab the array
for each text add a todo entry in the documen
the array
my html code
<!DOCTYPE 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.0">
<link rel="stylesheet" type="text/css" href="style.css">
<title>TodoList</title>
</head>
<body>
<div class="todolist_box">
<h3> To Do List </h3>
<div class="input">
<input type="text" id ="inp" placeholder="Add new Task">
<button onclick="newTodo()" ><i> enter </i></button>
<button onclick="newTodo()" ><i> save </i></button>
<button onclick="drawtodo()" ><i> load </i></button>
</div>
<ul id="myUL">
</ul>
</div>
<script src="script.js" type="application/javascript"></script>
</body>
</html>
and this is my javascript code
function newElement() {
// this code doesn't work, but it gives you an idea
const li = document.createElement("li")
const newEntry = document.getElementById("inp").value
const u = document.createTextNode(newEntry)
li.appendChild(u)
document.getElementById("myUL").appendChild(li)
document.getElementById("inp").value = "Nothing"
// something like thi
let todos = []
function newTodo() {
let inpvalue = document.getElementById('inp').value
todos.push(inpvalue)
// trigger draw event
}
function drawtodo() {
for (var i = todos.length - 1; i >= 0; i--) {
let li = document.createElement('li')
let newlist = li.appendChild(document.createTextNode(todos[i]))
inpvalue.appendChild(newlist)
}
}
document.onload = function() {
// this will excute when the document loads
}
}
Try using Javascript event listener instead of onclick attribute in html.
HTML:
<button id="load" ><i> load </i></button> // Removed onclick attribute
JS:
document.getElementById("load").addEventListener("click", drawtodo, false);
same with enter and save buttons, when click triggers the newTodo function.
Can someone please help me out with why my event handler on lines 36-37 of my code and why that is not working?
Here is my event handler here that is giving me problems which can also be found in my code below. I'm a rookie trying to learn this stuff. I think once I can get this figured out I can figure out how to use the event bubbling. Appreciate the help in advance!
$('.done-item').on('click', () => {
console.log('This task is completed');
})
JS and Jquery
//jQuery DOM Variables
$(() => {
const $inputBox = $('#input-box');
const $addButton = $('#submit');
const $things2Do = $('#to-do-list');
const $done = $('#completed');
// Functions
const toDoFunction = () => {
const $newToDo = $('<h3>').addClass('to-do-item').text($inputBox.val());
const $completedButton = $('<button>').addClass('done-item').text('COMPLETED');
$newToDo.append($completedButton);
$things2Do.append($newToDo);
resetInputBoxFunction();
}
const resetInputBoxFunction = () => {
$inputBox.val('');
}
const completedFunction = () => {
}
//Event Handlers
$addButton.on('click', toDoFunction); // add To Do item by clicking on ADD button
$($inputBox).keypress(() => { //Event handler to add To Do's when enter button is pressed
if(event.key === 'Enter'){
toDoFunction();
}
})
**//THIS EVENT HANDLER IS NOT WORKING. WHY???**
$('.done-item').on('click', () => {
console.log('This task is completed');
})
}) // end of the onload jQuery function
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>To Do App</title>
<!-- CSS stylesheet -->
<link rel="stylesheet" href="main.css">
<!-- remember, jQuery must come first -->
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
<!-- now your code -->
<script src="app.js" charset="utf-8"></script>
</head>
<body>
<div id="container">
<h1>What to Do</h1>
<div id="input-container">
<!-- input and input button -->
<label for="input-box"></label>
<input type="text" name="" value="" id="input-box">
<button type="button" name="button" id="submit">ADD</button>
</div>
<!-- Container for both lists -->
<div id="lists">
<!-- left list, things added should have a class of `to-do-item` to get the css -->
<div id="to-do-list">
<h2>Things to Do</h2>
</div>
<!-- right list, things added should have a class of `completed` -->
<div id="completed">
<h2>Things That are Done</h2>
</div>
</div>
</div>
</body>
</html>
This is how it will work:
$(document).on('click', '.done-item', () => {
console.log('This task is completed');
})
i have multiple tags, which is set as editable (contentEditable="true"). is there any way to store contents in divs before load and paste the same after reload or any alternative way to do this?. I am very new in the programming field
<div contentEditable="true" id="main" key="main" class="main" >
<div contentEditable="true" id="div1" onfocusout="myFunction()"><p>sample para</p></div>
<div contentEditable="true" id="div2" onfocusout="myFunction()"><p>sample para</p></div>
</div >
window.onload = function()
{
var a = sessionStorage.getItem('main');
//alert(a);
document.getElementById("main").value = a;
}
window.onbeforeunload = function() {
sessionStorage.setItem("main", $('#main').val());
}
I tried this, but it is only for forms with known input field
My body html looks like
<body>
<div>Math in TeX notation</div>
<div contentEditable="true" id="main" key="main" class="main" >
<div contentEditable="true" id="div1" onfocusout="myFunction()"><p>sample para</p></div>
<div contentEditable="true" id="div2" onfocusout="myFunction()"><p>sample para</p></div>
</div>
</body>
You can save any data to session storage and use it later with JavaScript:
window.onload = function () {
const content = sessionStorage.getItem('main');
if (content) {
document.getElementById("main").innerHTML = content;
}
}
window.onbeforeunload = function () {
sessionStorage.setItem("main", document.getElementById("main").innerHTML);
}
I hacked this together, it works for me (using Firefox), i tested it:
<!DOCTYPE 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>Document</title>
</head>
<body>
<div id="memo-pad">
<pre id="memo" contenteditable="true" onkeyup="storeUserMemo(this.id);"></pre>
</div>
<script>
function storeUserMemo(id) {
let memo = document.getElementById("memo").innerHTML;
localStorage.setItem("userMemo", memo);
}
function getUserMemo() {
let memo;
if (localStorage.getItem("userMemo")) {
memo = localStorage.getItem("userMemo");
} else {
memo = "Please write something here!";
}
document.getElementById("memo").innerHTML = memo;
}
function clearLocal() {
localStorage.clear();
document.getElementById("memo").innerHTML = "Please write something here!";
}
getUserMemo();
let memo = document.getElementById("memo");
memo.addEventListener("input", function () {
console.log("Wer ändert hier sein Memo?")
});
</script>
</body>
</html>
Whatever you put in there survives the page reload now.