can someone take a look at this and tell me what I'm doing wrong?
I wanted to use these other techniques just as an exercise.
such as using element id / using a separate js file to recreate a clock application that shows the current date. However, it keeps showing up as blank:
"use strict";
var $ = function(id) { return document.getElementById(id); };
var padSingleDigit = function(num) {
return (num < 10) ? "0" + num : num;
};
// callback function for displaying clock time
var displayTime = function(now) {
$("hours").firstChild.nodeValue = now.hours;
$("minutes").firstChild.nodeValue = padSingleDigit(now.minutes);
$("seconds").firstChild.nodeValue = padSingleDigit(now.seconds);
$("ampm").firstChild.nodeValue = now.ampm;
// display date in "m/d/yyyy" format - correct for zero-based month
var date = (now.getMonth() + 1) + "/" + now.getDate() + "/" + now.getFullYear();
$("date").firstChild.nodeValue = date;
};
// onload event handler
window.onload = function() {
var clock = createClock(displayTime);
// start clock
clock.start();
};
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 450px;
border: 3px solid blue;
padding: 0 2em 1em;
}
h1 {
color: blue;
}
label {
float: left;
width: 11em;
text-align: right;
padding-bottom: .5em;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
fieldset {
margin-bottom: 1em;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Clock</title>
<link rel="stylesheet" href="clock.css">
<script src="clock.js"></script>
</head>
<body>
<main>
<h1>Digital clock</h1>
<fieldset>
<legend>Clock</legend>
<span id="date"> </span>:
<span id="minutes"> </span>:
<span id="seconds"> </span>
<span id="ampm"> </span>
</fieldset>
</main>
</body>
</html>
The problem is you are referencing an element that does not exist. There is no element with the id of "hours" in your code.
Related
I'm running my code in node.js I've seen that running code in node could play a part. But this was never a problem. It keeps saying my variable that points to my element 'document is not defined'. I don't know what I'm doing wrong, I'm linking it correctly but still confused I also tried putting my scripts on the bottom and top with defer.
let seconds = 00;
let tens = 00;
let appendTens = document.querySelector('#tens');
let appendSeconds = document.querySelector('#seconds');
let stop = document.querySelector('#button-stop');
let start = document.querySelector('#button-start');
let reset = document.querySelector('#button-reset');
let interval; //store timer values
// this function will run when start is clicked
const startTimer = () =>{
tens++
if(tens < 9){
appendTens.textContent = `0${tens}`
}
if(tens > 9){
appendTens.textContent = tens;
}
if(tens > 99){
seconds++
appendSeconds.textContent = `0${seconds}`;
tens = 0;
appendTens.textContent = "0" + 0;
}
if(seconds > 9){
appendSeconds.textContent = seconds;
}
};
start.onclick = function(){
interval = setinterval(startTimer)
}
<!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>Stopwatch</title>
<link rel="stylesheet" href="stopwatch.css">
</head>
<body>
<div class="wrapper">
<h1>Stopwatch</h1>
<h2>Vanilla JavaScript Stopwatch</h2>
<p><span id="seconds">00</span>:<span id="tens">00</span></p>
<button id="button-start">Start</button>
<button id="button-stop">Stop</button>
<button id="button-reset">Reset</button>
</div>
<script type="module" src="stopwatcj.js"></script>
</body>
</html>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-self: center;
background-color: rgb(248, 180, 55);
}
.wrapper {
margin-top: 10%;
text-align: center;
color: #fff;
}
.wrapper button {
background-color: rgb(248, 180, 55);
border: 1px solid white;
padding: 10px 20px;
color: #fff;
}
.wrapper button:hover {
cursor: pointer;
opacity: 30%;
}
document which is a part of Html DOM is not a part of nodejs. Since you might be using nodejs to compile your js code that's why you are getting this error. Please try to run this simply in browser.
I'm working on a portfolio project - which should use jquery - part of the task is to set and get text via localstorage - which I can do in Javascript but I breaks when attempting to refactor in jquery.
I found an elegantly simple javascript codepen, which has all the features I want. But when I refactor into jquery it loses funtionality - I can't save the text to local storage (I get null) and I can't copy the text to a different Div.
This is the 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">
<link rel="stylesheet" href="style.css">
<title>Local Test</title>
</head>
<body>
<div class="content-output"></div>
<textarea class="content-input" placeholder="Your text here"></textarea>
<button class="save-button">Save</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="./script.js"></script>
</body>
</html>
This is simple CSS from the JS code pen:
* {
font-size: 16px;
font-family: sans-serif;
}
body {
padding: 1rem;
font-family: sans-serif;
}
.content-output {
float: left;
box-sizing: border-box;
background: #f9f9f9;
padding: 0.5rem;
width: calc(50% - 1rem);
height: 10rem;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.2);
color: #202020;
}
.content-input {
float: left;
box-sizing: border-box;
margin-left: 2rem;
padding: 0.5rem;
width: calc(50% - 1rem);
height: 10rem;
border: 1px solid #505050;
resize: none;
}
.save-button {
/* -webkit-appearance: none; */
border: 0;
background: #0088ff;
padding: 0.5rem 1rem;
border-radius: 3px;
color: #fff;
margin-top: 1rem;
float: right;
cursor: pointer;
}
Here is the JS which works:
var input_textarea = document.querySelector(".content-input");
var output_div = document.querySelector(".content-output");
var save_button = document.querySelector(".save-button");
save_button.addEventListener("click", updateOutput);
output = localStorage.getItem("content");
input = localStorage.getItem("content");
console.log(output);
output_div.textContent = output;
function updateOutput() {
console.log("clicked button");
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
And here is the jquery which doesn't work:
var input_textarea = $(".content-input");
var output_div = $(".content-output");
var save_button = $(".save-button");
save_button.on("click", updateOutput);
output_div.textContent = localStorage.getItem("content");
input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
event.preventDefault();
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
I'm running out of ideas and searches - probably a typo but I cant find it . I've tried text() which was the advice 6 years ago. JSON.stringify and parse don't help because it's just a string.
I'm hoping someone has done some refactoring and spots the differences - I've even run this in the console but I can only add the text to localstorage manually: localstorage.setItem('content', 'help')
Thanks in advance
The problem is that you are trying to select a array, get the value of that array, and output to another array. I think jquery does that when you select a class, (because there could be more than one of them). Simple solution to this..
var input_textarea = $(".content-input")[0];
console.log(input_textarea)
var output_div = $(".content-output")[0];
var save_button = $(".save-button");
save_button.on("click", updateOutput);
output_div.textContent = localStorage.getItem("content");
input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
console.log('hello')
event.preventDefault();
localStorage.setItem("content", input_textarea.value);
output_div.textContent = input_textarea.value;
}
Found it: val() to set and text() to get.
var input_textarea = $(".content-input");
var output_div = $(".content-output");
var save_button = $(".save-button");
save_button.on("click", updateOutput);
// input_textarea.value = localStorage.getItem(("content"));
function updateOutput(event) {
event.preventDefault();
localStorage.setItem("content", input_textarea.val());
output_div.text(localStorage.getItem("content"));
}
this post helped: How to save the value of textarea to localstorage then display it in the same textarea
In JavaScript, I have created an object called annualPlan.
When someone submits the HTML form for a specific month, I want to be able to change the value in the object for a particular month.
For example, if someone submits August 21 and 200, I want pAug to be 500.
But if someone re-submits August 21 and 500, I want pAug to be 200.
The code snippet below was my attempt at doing this (actually it was more like attempt 100!).
What do you think?
var planMonth;
var planAmount;
//create a custom ID value with the current time of form submit
var today = new Date();
var FullDate = today.getDate() + "-" + (today.getMonth() + 1); //getMonth method starts from 0. Add 1 to get real month.
var time = today.getHours() + ":" + today.getMinutes();
var dateTime = FullDate + " " + time
var annualPlan = {
pJan: 0,
pFeb: 0,
pMarch: 0,
pApril: 0,
pJune: 0,
pJuly: 0,
pAugust: 0,
pSept: 0,
pOct: 0,
pNov: 0,
pDec: 0,
};
const addPlan = function(ev) {
ev.preventDefault();
let planUpdate = {
id: dateTime,
Month: document.getElementById("PlanMonth").value,
Amount: document.getElementById("PlanSave").value,
}
annualPlan.push(planUpdate);
document.querySelector("form").reset();
//console.log(annualPlan);
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("button").addEventListener("click", addPlan);
});
/* PAGE STRUCTURE START */
body {
padding-left: 150px;
padding-right: 150px;
font-family: Georgia, 'Times New Roman', Times, serif;
font-size: 18px;
}
#inputarea {
margin-top: 100px;
}
label {
display: inline-block;
padding-bottom: 8px;
font-size: 22px;
font-family: Georgia, 'Times New Roman', Times, serif;
}
input {
padding: 10px 20px;
font-size: 18px;
letter-spacing: 2px;
}
#formSection {
padding-top: 30px;
}
/* PAGE STRUCTURE END */
/* FONT STYLING START */
#inputarea h3 {
text-decoration: underline;
color: #334058;
font-size: 30px;
}
/* NAVIGATION AREA START */
* {
-webkit-transition-property: all;
transition-property: all;
-webkit-transition-duration: .2s;
transition-duration: .2s;
-moz-transition-timing-function: cubic-bezier(100, 50, 21, 6);
transition-timing-function: cubic-bezier(100, 50, 21, 6);
-moz-transition-property: all;
-moz-transition-timing-function: cubic-bezier(100, 50, 21, 6);
}
.style-1 {
text-align: center;
margin-top: 40px;
}
.btn {
color: #fff;
background: #3399cc;
padding: 20px 40px;
text-decoration: none;
letter-spacing: 2px;
text-transform: uppercase;
}
.btn:hover {
border: none;
background: rgba(0, 0, 0, 0.4);
background: #fff;
padding: 40px 40px;
color: #334058;
}
/* NAVIGATION AREA END */
<!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>Grow Your Wealth</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="icon" href="images/fav.ico">
</head>
<!-- Navigation Start -->
<nav class="style-1">
Home
App Page
</nav>
<!-- Navigation End -->
<section id="inputarea">
<h3 id="section-header">Plan Input Area</h3>
<form onsubmit=>
<div id="formSection">
<label for="PlanMonth">Month</label><br>
<input type="month" name="PlanMonth" id="PlanMonth" value="2021-08">
</div>
<div id="formSection">
<label for="PlanSave">Planned Saving for Month</label><br>
<input type="number" name="PlanSave" id="PlanSave" value="200"><br><br>
</div>
<div id="formSection">
</div>
<input type="submit" value="submit" id="button">
</form>
</section>
<!-- JS File -->
<script src="js/app.js"></script>
</body>
</html>
You would have to get the value of the month from the input and then find the corresponding month.
Example let's say you get the input date as 2021-08.
We will extract the 08 out of it which is the month.
Next according to your month names, 08 corresponds to pAugust.
However we will choose 8-1 which is 7 because indexing starts from 0,
Then we will get the existing value of that month using annualPlan[month] and then add the value of amount to it.
var planMonth;
var planAmount;
//create a custom ID value with the current time of form submit
var today = new Date();
var FullDate = today.getDate() + "-" + (today.getMonth() + 1); //getMonth method starts from 0. Add 1 to get real month.
var time = today.getHours() + ":" + today.getMinutes();
var dateTime = FullDate + " " + time
var annualPlan = {
pJan: 0,
pFeb: 0,
pMarch: 0,
pApril: 0,
pMay:0,
pJune: 0,
pJuly: 0,
pAugust: 0,
pSept: 0,
pOct: 0,
pNov: 0,
pDec: 0,
};
function findmonth(month){
// Get the month
month = month.split('-')[1]
// Geta all the months
let months = Object.getOwnPropertyNames(annualPlan)
// Return the month according to the object annualPlan
return months[parseInt(month)-1]
}
const addPlan = function(ev) {
ev.preventDefault();
let planUpdate = {
id: dateTime,
Month: document.getElementById("PlanMonth").value,
Amount: document.getElementById("PlanSave").value,
}
// Get the existing value of the month
let existingVal = annualPlan[findmonth(planUpdate.Month)];
// Add the new value and update it to the obj
annualPlan[findmonth(planUpdate.Month)] = parseInt(existingVal) + parseInt(planUpdate.Amount)
console.log(annualPlan)
document.querySelector("form").reset();
//console.log(annualPlan);
}
document.addEventListener('DOMContentLoaded', () => {
document.getElementById("button").addEventListener("click", addPlan);
});
<!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>Grow Your Wealth</title>
<link rel="icon" href="images/fav.ico">
</head>
<!-- Navigation Start -->
<nav class="style-1">
Home
App Page
</nav>
<!-- Navigation End -->
<section id="inputarea">
<h3 id="section-header">Plan Input Area</h3>
<form onsubmit=>
<div id="formSection">
<label for="PlanMonth">Month</label><br>
<input type="month" name="PlanMonth" id="PlanMonth" value="2021-08">
</div>
<div id="formSection">
<label for="PlanSave">Planned Saving for Month</label><br>
<input type="number" name="PlanSave" id="PlanSave" value="200"><br><br>
</div>
<div id="formSection">
</div>
<input type="submit" value="submit" id="button">
</form>
</section>
</body>
</html>
I'm not exactly sure what you're trying to do but a couple of things in this code doesn't look right, hopefully this helps you on your way.
<button onClick={doSomething}>My Button</button>
...
const data = {
// values here
}
const doSomething = () => {
data.example = // assign anything new here
}
I created a web page where the background of my page changes depending on the hour. I want the background image to always be the full width of the page, so I am trying to set it to be 100%, but it doesn't seem to be working. Is there some part of the code that's written incorrectly? Do I need to implement something else?
body {
margin-left: 5%;
margin-right: 5%;
}
#demo {
color: white;
}
#txt {
color: white;
float: left;
font-family: OpenSans;
font-size: 90px;
margin: 20px;
}
#weather {
color: white;
float: right;
font-family: OpenSans;
font-size: 40px;
margin: 20px;
}
<!DOCTYPE html>
<html>
<head>
<title>Blooming Time And Temperature</title>
<link href="css/format.css" rel="stylesheet"/>
<link href="https://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet">
<script>
function startTime() {
document.getElementById('txt').innerHTML =
moment().format("hh:mm A");
var t = setTimeout(startTime, 1000);
var hour = moment().hour()
}
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
function changeBackground(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(sequence/1.jpg) no-repeat').width('100%');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(sequence/2.jpg) no-repeat').width('100%');
}
else if(hour > 19 && hour < 21)
{
// It's noon
$('body').css('background', 'url(sequence/3.jpg) no-repeat').width('100%');
}
else
{
// It's night
$('body').css('background', 'url(sequence/4.jpg) no-repeat').width('100%');
}
}
changeBackground(); // invoke for the first time manually
setInterval(changeBackground, 1000 * 60 * 60);
});
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.simpleWeather/3.1.0/jquery.simpleWeather.min.js"></script>
<script>
$(document).ready(function() {
$.simpleWeather({
location: 'Brooklyn, NY',
woeid: '',
unit: 'f',
success: function(weather) {
html = '<p>'+weather.temp+'°'+weather.units.temp+'</p>';
html += '<div id="city">'+weather.city+', '+weather.region+'</div>';
$("#weather").html(html);
},
error: function(error) {
$("#weather").html('<p>'+error+'</p>');
}
});
});
</script>
</head>
<body onload="startTime()"">
<div id="txt"></div>
<div id="weather"></div>
</body>
</html>
You could try removing the margin attributes on the body tag in your CSS, and set background-size: cover on the body tag there. Then in your changeBackground function, you mightn't need the .width(100%); method, since the width shouldn't change when you swap out the background images?
If you are putting the background image on the body and you have this css property, it won't do.
body {
margin-left: 5%;
margin-right: 5%;
}
Make the property
body {
margin:0;
}
Working on a tip calculator with an animation on an h1 tag and a slideDown and slideUp on click on the h2 tags. Problem is, none of the animations are playing and the click event isn't working either.
Here is the HTML file
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Tip Calculator</title>
<link rel="shortcut icon" href="images/favicon.ico">
<link rel="stylesheet" href="midtermcss.css">
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script src="animationJS.js"></script>
</head>
<body>
<section id="faqs">
<h1>Tip facts</h1>
<h2>Things to know before you tip</h2>
<div>
<p>Tips Account for 44 Billion dollars of the Food Industry</p>
<p>7 States require servers to be paid minimum wage like everyone else</p>
<ul>
<li>Minnessota</li>
<li>Montana</li>
<li>Washington</li>
<li>Oregon</li>
<li>California</li>
<li>Nevada</li>
<li>Alaska</li>
</ul>
<p>Current Federal minimum tipped wage is $2.13 per hour can you live on that?</p>
<p>Charging with Credit/Debit cards tends to reduce the average tip</p>
</div>
</section>
<section id="js">
<h1 id="heading">Tip Calculator</h1>
<label for="billAmount">Total Amount Of Bill:</label>
<input type="text" id="billAmount"><br>
<label for="percentTip">Percent To Tip:</label>
<input type="text" id="percentTip"><br>
<label for="amountPeople">How Many People?:</label>
<input type="text" id="amountPeople"><br>
<label for="totalTip">Tip Total:</label>
<input type="text" id="totalTip"><br>
<label> </label>
<input type="button" id="calculate" value="Calculate"><br>
</section>
</body>
</html>
Here is the JS file.
$(document).ready(function() {
// runs when an h2 heading is clicked
$("#faqs h2").toggle(
function() {
$(this).toggleClass("minus");
$(this).next().slideDown(1000, "easeOutBounce");
},
function() {
$(this).toggleClass("minus");
$(this).next().slideUp(1000, "easeInBounce");
}
);
$("#faqs h1").animate({
fontSize: "400%",
opacity: 1,
left: "+=375"
}, 1000, "easeInExpo")
.animate({
fontSize: "175%",
left: "-=200"
}, 1000, "easeOutExpo");
$("#faqs h1").click(function() {
$(this).animate({
fontSize: "400%",
opacity: 1,
left: "+=375"
}, 2000, "easeInExpo")
.animate({
fontSize: "175%",
left: 0
}, 1000, "easeOutExpo");
});
});
var $ = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var billAmount = parseFloat($("billAmount").value);
var percentTip = parseFloat($("percentTip").value);
var amountPeople = parseInt($("amountPeople").value);
if (isNaN(billAmount) || billAmount <= 0) {
alert("Your bill can't be 0 or less.");
} else if (isNaN(percentTip) || percentTip <= 0) {
alert("The percentage should be a whole number.");
} else if (isNaN(amountPeople) || amountPeople <= 0) {
alert("You are 1 person never count yourself as less.");
} else {
var total = billAmount * (percentTip / 100) / amountPeople;
$("totalTip").value = total.toFixed(2);
}
}
window.onload = function() {
$("calculate").onclick = calculateClick;
$("billAmount").focus();
}
Last but not least the CSS file since the open and minus classes are listed in there
* {
margin: 0;
padding: 0;
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 500px;
border: 3px solid blue;
}
section {
padding: 0 1em .5em;
}
section.js {
padding: 0 1em .5em;
}
h1 {
text-align: center;
margin: .5em 0;
}
label {
float: left;
width: 10em;
text-align: right;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
#faqs h1 {
position: relative;
left: -168px;
font-size: 125%;
color: blue;
}
h2 {
font-size: 120%;
padding: .25em 0 .25em 25px;
cursor: pointer;
background: url(images/plus.png) no-repeat left center;
}
h2.minus {
background: url(images/minus.png) no-repeat left center;
}
div.open {
display: block;
}
ul {
padding-left: 45px;
}
li {
padding-bottom: .25em;
}
p {
padding-bottom: .25em;
padding-left: 25px;
}
I can't figure out for the life of me why the animations work in a separate test file but when I use them now in my tip calculator they don't. I'm using Murach's Javascript and Jquery book but this section has been terribly hard to understand.
Your issue is that you include jQuery but later on in the global scope you redefine the $:
var $ = function(id) {
return document.getElementById(id);
}
Fiddle: http://jsfiddle.net/AtheistP3ace/u0von3g7/
All I did was change the variable name holding that function and replace it in the areas you were using it. Specifically:
var getById = function(id) {
return document.getElementById(id);
}
var calculateClick = function() {
var billAmount = parseFloat(getById("billAmount").value);
var percentTip = parseFloat(getById("percentTip").value);
var amountPeople = parseInt(getById("amountPeople").value);
if (isNaN(billAmount) || billAmount <= 0) {
alert("Your bill can't be 0 or less.");
} else if (isNaN(percentTip) || percentTip <= 0) {
alert("The percentage should be a whole number.");
} else if (isNaN(amountPeople) || amountPeople <= 0) {
alert("You are 1 person never count yourself as less.");
} else {
var total = billAmount * (percentTip / 100) / amountPeople;
getById("totalTip").value = total.toFixed(2);
}
}
window.onload = function() {
getById("calculate").onclick = calculateClick;
getById("billAmount").focus();
}
$ is just shorthand for jQuery. When you include jQuery it creates two functions for you that both do the same thing. jQuery and $. If you set $ equal to something else you have effectively overwritten jQuery library included in your page and it will no longer operate as you would expect. All jQuery functionality begins with using $ or jQuery function. Once that returns a jQuery object to you, you can begin chaining and calling functions off those objects but to get a jQuery object you need to use the jQuery or $ function.
You mentioned in a comment above your teacher had you do that to fix something. I imagine it was because jQuery was not initially included so he just created the $ selector function to get you moving but I would hope he explained why he did that and how it can affect things later.