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');
})
Related
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 last month.
Improve this question
I was trying to create a crud app(local storage) from a Udemy course and ran into the following error in the code, the event Listener is to get the value in the input section once user hits submit;
following is the app.js
`
// ****** SELECT ITEMS **********
const alert = document.querySelector(".alert");
const form = document.querySelector(".grocery-form");
const grocery = document.getElementById(".grocery");
const submitBtn = document.querySelector(".submit-btn");
const container = document.querySelector(".grocery-container");
const list = document.querySelector(".grocery-list");
const clearBtn = document.querySelector(".clear-btn");
// edit option
let editElement;
let editFlag = false;
let edtiID = "";
// ****** EVENT LISTENERS **********
form.addEventListener("submit", addItem);
// ****** FUNCTIONS **********
function addItem(e) {
e.preventDefault();
const value = grocery.value;
const id = new Date().getTime().toString();
console.log(id);
}
`
following is the index.html
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery Bud</title>
<!-- font-awesome -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
/>
<!-- styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<section class="section-center">
<!-- form -->
<form class="grocery-form">
<p class="alert"></p>
<h3>grocery bud</h3>
<div class="form-control">
<input type="text" id="grocery" placeholder="e.g. eggs" />
<button type="submit" class="submit-btn">submit</button>
</div>
</form>
<!-- list -->
<div class="grocery-container">
<div class="grocery-list"></div>
<button class="clear-btn">clear items</button>
</div>
</section>
<!-- javascript -->
<script src="app.js"></script>
</body>
</html>
`
I tried to listen to the submit event and capture the value in the input box in the form. But I got the error value is null, also tried to console log the 'grocery' element, got null instead
grocery is an ID not class, so document.getElementById needs a plain ID just like grocery not .grocery, this would be called class. Just read about Document.getElementById().
// ****** SELECT ITEMS **********
const alert = document.querySelector(".alert");
const form = document.querySelector(".grocery-form");
const grocery = document.getElementById("grocery");
const submitBtn = document.querySelector(".submit-btn");
const container = document.querySelector(".grocery-container");
const list = document.querySelector(".grocery-list");
const clearBtn = document.querySelector(".clear-btn");
// edit option
let editElement;
let editFlag = false;
let edtiID = "";
// ****** EVENT LISTENERS **********
form.addEventListener("submit", addItem);
// ****** FUNCTIONS **********
function addItem(e) {
e.preventDefault();
const value = grocery.value;
const id = new Date().getTime().toString();
console.log(id);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery Bud</title>
<!-- font-awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<!-- styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<section class="section-center">
<!-- form -->
<form class="grocery-form">
<p class="alert"></p>
<h3>grocery bud</h3>
<div class="form-control">
<input type="text" id="grocery" placeholder="e.g. eggs" />
<button type="submit" class="submit-btn">submit</button>
</div>
</form>
<!-- list -->
<div class="grocery-container">
<div class="grocery-list"></div>
<button class="clear-btn">clear items</button>
</div>
</section>
</body>
</html>
Or as #Andy mentioned in comments, you can use Document.querySelector().
I am building a very basic magic 8 ball type 'game' using vanilla javascript. I have a text field (for a user question) and a submit button underneath. At present, I have it working fine with a event listener for the submit button but am trying to also get the same result if a user was to click enter.
I saw on w3s that you can trigger a button click upon enter, as below...
// Get the input field
var input = document.getElementById("myInput");
// Execute a function when the user presses a key on the keyboard
input.addEventListener("keypress", function(event) {
// If the user presses the "Enter" key on the keyboard
if (event.key === "Enter") {
// Cancel the default action, if needed
event.preventDefault();
// Trigger the button element with a click
document.getElementById("myBtn").click();
}
});
...but I can't seem to translate that into my own project. HTML and JS for my project below; I am trying not to use nested functions at the moment just to help with my understanding (as advised by my course mentor).
JavaScript
let question = document.querySelector('#userQuestion');
let button = document.querySelector('#shakeButton');
let answer = document.querySelector('#answer');
let options = [
'It is certain.',
'Signs point to yes.',
'Concentrate and ask again.',
'My sources say no.',
]
// Generate a random number
function generateAnswer() {
let index = Math.floor(Math.random() * 4);
let message = options[index];
answer.textContent = message;
answer.style.fontSize = '18px';
setTimeout(timeOut, 3000);
};
// Timeout function
function timeOut() {
answer.textContent = '8';
answer.style.fontSize = '120px';
};
// Enter button trigers click event
function enterButton (event) {
if (event.key === "Enter") {
event.preventDefault();
button.click();
}
};
//Event listener for button click
button.addEventListener('click', generateAnswer);
question.addEventListener("keypress", enterButton);
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">
<meta name="description" content="Magic 8 Ball, ask it anything and it will answer.">
<!-- Stylesheet & Font Awesome Links -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin><link href="https://fonts.googleapis.com/css2?family=Orbitron:wght#800&family=Press+Start+2P&display=swap" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css">
<link rel="stylesheet" href="assets/css/style.css" type="text/css">
<!-- Stylesheet & Font Awesome Links End -->
<title>Magic 8 Ball</title>
</head>
<body>
<nav class="navbar">
<div class="container-fluid">
<a class="navbar-brand ms-auto" href="#">dc games</a>
</div>
</nav>
<!-- Header -->
<header class="heading">
<h1>The Magic 8 Ball</h1>
<p>Shake the Magic 8 Ball and it will answer your question.</p>
</header>
<!-- Header End-->
<!-- Magic 8 Ball -->
<div class="ball-black">
<div class="ball-white">
<p id="answer">8</p>
</div>
</div>
<!-- Magic 8 Ball End -->
<!-- User Question -->
<div class="user-input">
<input type="text" class="form-control mb-2 mr-sm-2" id="inlineFormInputName2 userQuestion" placeholder="What is your question?" required>
<button type="button" class="btn" id="shakeButton">Shake!</button>
</div>
<!-- User Question -->
<!-- Footer -->
<footer>
<div class="copyright fixed-bottom">
<p>Copyright © dc games 2022</p>
</div>
</footer>
<!-- Footer End -->
<!-- JavaScript Links -->
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
<script type="text/javascript" src="assets/js/script.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script>
<!-- JavaScript Links End -->
</body>
</html>
You cannot have multiple Ids on a single DOMElement. If you remove inlineFormInputName2 from the id of the user question, your code will work.
You can only have multiple identifiers for a class.
classes are used for formatting with css and Ids to specifically identify an element.
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'
})
})
}
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.
For some reason my eventHandling code stopped working.
I was working on some functions to handle the indexedDB stuff, when i went back to work on the interface, i noticed that the eventHandlers only worked at app creation, even when i didnt performed any action on them, they just go off.
Heres my default.js
(function () {
"use strict";
WinJS.Binding.optimizeBindingReferences = true;
var app = WinJS.Application;
var activation = Windows.ApplicationModel.Activation;
var _swAlarm;
app.onactivated = function (args) {
if (args.detail.kind === activation.ActivationKind.launch) {
if (args.detail.previousExecutionState !== activation.ApplicationExecutionState.terminated) {
} else {
}
args.setPromise(WinJS.UI.processAll());
}
};
app.oncheckpoint = function (args) {
};
function testSelection(value) {
console.log("from event listner "+value)
}
function getDomElements() {
_swAlarm = document.getElementById("swAlarm");
}
function registerHandlers() {
_swAlarm.addEventListener("onchange", console.log("ola"));
}
app.onready = function () {
getDomElements();
registerHandlers();
}
app.start();
And this is my default.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>MyApp</title>
<!-- WinJS references -->
<link href="//Microsoft.WinJS.1.0/css/ui-dark.css" rel="stylesheet" />
<script src="//Microsoft.WinJS.1.0/js/base.js"></script>
<script src="//Microsoft.WinJS.1.0/js/ui.js"></script>
<!-- my references -->
<link href="/css/default.css" rel="stylesheet" />
<script src="/js/default.js"></script>
<script src="/js/database.js"></script>
<!-- jquery references -->
<script src="js/jquery-1.8.2-win8-1.0.js"></script>
<script src="js/visualize.jQuery.js"></script>
<script type="text/javascript"> jQuery.isUnsafe = true;</script>
<link href="/css/default.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="content">
<div id="settings">
<h2 id="lAlarm">Alarm</h2>
<div id="swAlarm" data-win-control="WinJS.UI.ToggleSwitch" ></div>
<input id="iMaxval" type="number">
<input id="iMinval" type="number">
<button id="bSave">Save</button>
</div>
<div id="graph">
<h2 id="hGraph" class="graph">Graph</h2>
</div>
<div id="stats">
<h2 id="hStats" class="stats">Stats</h2>
</div>
</div>
</body>
</html>
When you run this code:
_swAlarm.addEventListener("onchange", console.log("ola"));
you are:
running console.log("ola")
affecting the result as a callback for the event onchange of _swAlarm.
This is wrong on many levels.
console.log("ola") does not return a call back. I think I understand what you meant, and the correct code could be: function() { console.log("ola"); }
When using addEventListener you have to use dom lexique with event denomination. In your case, onchange needs to be instead change. If you had to affect this event directly in html, you indeed would have to use onchange="console.log("ola");". But not with addEventListener.
The final result is:
_swAlarm.addEventListener("change", function() { console.log("ola"); }, false);
As for why was it working on app creation, I think it is simply because on app creation console.log("ola") was called right away at event affectation, but since no event was actually affected later on you would not get any result for the onchange event.
On a side note, and since I guess you're sort of migrating from "old" syntaxis (onchange... etc.) to the addEventListener api, I'll add an important difference between the 2 modes: when an event is executed the old way, this referers to window. But affecting the callback through addEventListener makes the domElement itself (_swAlarm in your case) be the target of this during the callback execution.