Background Width jQuery Specification Not Working - javascript

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;
}

Related

time shown is blank for javascript application

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.

How do I make a photo change between the days of the week?

I have a lot of code that I made so far but I can't get the load() function to work:
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Page resizer -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<!-- Date -->
<script>
var d = new Date();
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
document.getElementById("date").innerHTML = days[d.getDay()];
</script>
<!-- Gif changer -->
<script>
function changegif() {
var gif;
if (days = Sunday) {
gif = "/img/sunday.gif";
} else if (days = Monday) {
gif = "/img/monday.gif";
} else if (days = Tuesday) {
gif = "/img/tuesday.gif";
} else if (days = Wednesday) {
gif = "/img/wednesday.gif";
} else if (days = Thursday) {
gif = "/img/thursday.gif";
} else if (days = Friday) {
gif = "/img/friday.gif";
} else if (days = Saturday) {
gif = "/img/saturday.gif";
}
}
function load() {
document.getElementById('gif').src = changegif();
}
</script>
</head>
<body onload="load()">
<!-- More date stuff -->
<style>
.image {
position: relative;
width: 100%; /* for IE 6 */
}
h2 {
position: absolute;
top: 150px;
left: 0;
width: 100%;
}
h2 span {
color: white;
font: bold 24px/45px Helvetica, Sans-Serif;
letter-spacing: -1px;
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.7);
padding: 10px;
}
h1 {
position: absolute;
top: 200px;
left: 0;
width: 100%;
}
h1 span {
color: white;
font: bold 24px/45px Helvetica, Sans-Serif;
letter-spacing: -1px;
background: rgb(0, 0, 0); /* fallback color */
background: rgba(0, 0, 0, 0.7);
padding: 10px;
}
</style>
<div class="image">
<img src="#" id="gif">
<h2><span>Enjoy Your</span></h2>
<br>
<h1 id="date"><span></span></h1>
</div>
</body>
</html>
If anybody knows what I'm doing wrong please tell me. I have tried integrating the functions into a button but it still didn't work.
Remove all your own <script>s, then use this:
function load() {
var day = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"][new Date().getDay()];
document.getElementById("date").innerHTML = day;
document.getElementById('gif').src = "/img/" + day.toLowerCase() + ".gif";
}
To explain all the mistakes:
= assigns; it does not compare.
changegif doesn’t return anything, so document.getElementById('gif').src = changegif(); will always set it to undefined (assuming no other errors).
Sunday and others are undeclared variable names; they only work as strings: "Sunday".
days is not a single day, it’s the whole array, so comparing it to a single day won’t work.
changegif can be simplified to:
function changegif(){
return "/img/"
+ days[d.getDay()].toLowerCase()
+ ".gif";
}
Or use the answer by Chris G.

Background Image jQuery Isn't Working, What Am I Doing Wrong?

I am trying to create a site that has a background image that changes every hour. I want the background image to correspond with a certain time of day. For example, an image of closed flower bud would be the site background at 12AM and an image of a blooming flower bud would be the site background at 12PM.
I am pretty sure the way I am currently implementing this is the correct way, and on inspection I don't get any errors, but the background images are not showing up. What am I doing wrong? Is it the way I'm using the jQuery or another aspect of my code? Any help is greatly appreciated. Thanks in advance.
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() {
setInterval(function(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else
{
// It's night
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
}, 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>
Function that is provided to setInterval method will be invoked for the first time after time you provided (which is one hour). Change it to:
function changeBackground(){
var hour = new Date().getHours();
if(hour > 7 && hour <= 12)
{
// It's morning
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else if(hour > 12 && hour < 18)
{
// It's noon
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
else
{
// It's night
$('body').css('background', 'url(http://www.magic4walls.com/wp-content/uploads/2015/11/Macro-of-water-droplets-on-pink-lotus-flower-blooming-in-early-morning.jpg) no-repeat');
}
}
changeBackground(); // invoke for the first time manually
setInterval(changeBackground, 1000 * 60 * 60);

Animations not playing on load or on click in Javascript

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.

Unresponsive elements after button click

Background:
I started Javascript the other day and built this sketch pad:
http://frankpeelen.github.io/sketch-pad/
following alongside the instructions on:
http://www.theodinproject.com/web-development-101/javascript-and-jquery
Problem:
It's basically finished, and works fine except for when creating a new grid with the "New" button. All of a sudden the 'squares' stop responding to 'hover' events. I've searched, but have been unable to find any similar problems. Any ideas?
Code:
$(document).ready(function() {
var build = function(h, w) {
var height = h;
var width = w;
//Loop through height to create rows
for (i = 1; i <= height; i++) {
$("#sketchpadcontainer").append("<div class='row'></div>");
//Loop through width to create divs in each row
for (j = 1; j <= width; j++) {
$(".row:last-child").append("<div class='sqrcontainer'><div class='square'></div></div>");
}
}
};
//Build default 16x16 grid
build(16, 16);
$("button").click(function() {
var size = parseInt(prompt("How many squares per side would you like? Please enter a number."));
//In case the number entered > 50
if (size > 50) {
$(".row").remove();
build(50, 50);
alert("The number you entered was too large. The number 50 has been used instead.")
}
//In case a non-number is entered
else if (isNaN(size)) {
$(".row").remove();
build(16, 16);
alert("You didn't enter a number. The default of 16 has been used.")
}
//In case a number <= 50 is entered
else {
$(".row").remove();
build(size, size);
}
})
$(".square").hover(
//Mouse in
function () {
$(this).css("background-color", "blue");
},
//Mouse out
function () {} );
});
html, body, #sitecontainer {
height: 100%;
width: 100%;
margin: 0px;
}
#sketchpadcontainer {
}
button {
display: block;
margin: 0 auto;
margin-top: 2em;
margin-bottom: 1em;
}
#sketchpadcontainer {
}
.row {
text-align: center;
}
.sqrcontainer {
height: 1.5em;
width: 1.5em;
display: inline-block;
}
.square {
width: 1em;
height: 1em;
margin: .1em;
border-color: black;
border-style: solid;
border-radius: .1em;
}
<!DOCTYPE html>
<head>
<title>Sketch Pad</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="js/javascript.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div id="sitecontainer">
<div id="buttoncontainer">
<button type="button">New</button>
</div>
<div id="sketchpadcontainer">
</div>
</div>
</body>
You are deleting the divs before the build method. That means the hover listeners will be deleted to. You have to add them to the .sqare elements again.
Just move
$(".square").hover(
//Mouse in
function () {
$(this).css("background-color", "blue");
},
//Mouse out
function () {} );
inside your build method
change $(".square").hover(
to $(document).on("hover" ,".square", function(){ . . . })
Ur problem in $(".square").hover( - work after $(document).ready, but after u appending new rows - document ready dont triggering, and ur elements have not events, and trigger .on work on every elems on page, even on dynamically added.

Categories