JavaScript is Not Working in any of my Browsers - javascript

I am just learning JavaScript and for some reason this simple (Example 1 from Chapter One) example is not working (Jon Duckett's JavaScript and Jquery book) in any of my browsers: FireFox, IE, and Chrome. I made sure JavaScript is turned on. I also put noscript tags in my index.html file to make sure I had JavaScript on. My jsFiddle works perfectly, but nothing in my browsers. Here is my jsFiddle with everything I have in my Atom editor. My links are correct because I copied the full path and then pasted it into the src. I then deleted all the C:\users....... until I got into the folder with all of the files to end up with what is in the jsFiddle.
html:
<!doctype html>
<html lang="en">
<head>
<meta charset="etf-8" />
<title>Greeting JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
<script src="scripts/greeting.js"></script>
</head>
<body>
<noscript>Your Browser Does Not Support JavaScript. Please Enable It.</noscript>
<section>
<div id="header">
<h1>Constructive & Co.</h1>
</div>
<h3 id="greeting"></h3>
<p>For all orders and inquiries please call <em>555-3344</em></p>
</section>
</body>
</html>
javascript:
var today = new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting = 'Good evening!';
} else if (hourNow > 12) {
greeting = 'Good afternoon!';
} else if (hourNow > 0) {
greeting = 'Good morning!';
} else {
greeting = 'Welcome!';
}
document.getElementById("greeting").innerHTML = greeting;
css:
#import url(http://fonts.googleapis.com/css?family=Open+Sans:800italic);
body {
font-family: "Courier New", Courier, monospace;
/*background: url("../images/constructive-backdrop.jpg") no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;*/
background: #a18957;
margin: 0px;
padding: 0px;
text-align: center;
}
section {
margin-top: 20px;
margin-left: 20px;
height: 500px;
width: 400px;
background: #eee;
border: 1px solid #292929;
}
#header {
height: 200px;
margin: 10px;
background: rgba(227, 192, 186, 0.78);
}
h1 {
margin: 0px;
position: relative;
top: 45%;
}
h3 {
height: 100px;
margin: 10px;
background: red;
}
p {
margin: 10px;
height: 100px;
}
Thank You

You want to add the script tag at the end of your html. The element greeting doesn't exist, when you are executing it.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Greeting JavaScript</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<noscript>Your Browser Does Not Support JavaScript. Please Enable It.</noscript>
<section>
<div id="header">
<h1>Constructive & Co.</h1>
</div>
<h3 id="greeting"></h3>
<p>For all orders and inquiries please call <em>555-3344</em></p>
</section>
<script src="scripts/greeting.js"></script>
</body>
</html>
Or you leave it in the head and wrap the script into
addEventListener("readystatechange", function () {
if (document.readyState === "interactive") {
var today = new Date();
var hourNow = today.getHours();
var greeting;
if (hourNow > 18) {
greeting = 'Good evening!';
} else if (hourNow > 12) {
greeting = 'Good afternoon!';
} else if (hourNow > 0) {
greeting = 'Good morning!';
} else {
greeting = 'Welcome!';
}
document.getElementById("greeting").innerHTML = greeting;
}
}, false);
It is wonderful you use document.getElementById, instead of document.write!

Related

How to add bg image to API weather project?

Hello lately i've been working with APIs to get the hang of them through the usual weather app project BUT i'm pretty much still a beginner in javascript and i was wondering how to add a background image that matches the weather report of the city selected by the user.
I wanted to create many classes in css, each called like the weather (ex: .clear, .clouds,.rain etc...) and then use a classList.add() method to change it each time depending on the openWeatherMap data. I tried adding something like document.getElementsByTagName("body")[0].classList.add(weatherValue); inside the .then promise but it doesn't work. Can somebody help me? If there's a much simpler way i'd like to hear about it too :) Thank you so much
var button = document.querySelector(".button");
var inputValue = document.querySelector(".inputValue");
var cityName = document.querySelector(".name");
var weather = document.querySelector(".weather");
var desc = document.querySelector(".desc");
var temp = document.querySelector(".temp");
var humi = document.querySelector(".humi");
button.addEventListener("click", function() {
fetch("https://api.openweathermap.org/data/2.5/weather?q="+inputValue.value+"&appid={myapikey}")
.then(response => response.json())
.then(data => {
var nameValue = data['name'];
var weatherValue = data['weather'][0]['main'];
var tempValue = data['main']['temp'];
var descValue = data['weather'][0]['description'];
var humiValue = data['main']['humidity'];
cityName.innerHTML = nameValue;
weather.innerHTML = weatherValue; // this gives "clear" "clouds" etc to <p> element
desc.innerHTML = descValue;
temp.innerHTML = "Temperature: " + tempValue;
humi.innerHTML = "Humidity: " + humiValue;
})
.catch(err => alert("Wrong city name!"))
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Nunito", sans-serif;
background-repeat: no-repeat;
background-size: cover;
}
.input {
text-align: center;
margin: 100px 0;
}
input[type="text"] {
height: 50px;
width: 600px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
padding: 10px 10px;
}
input[type="submit"] {
height: 50px;
width: 100px;
background: #e7e7e7;
font-family: "Nunito", sans-serif;
font-weight: bold;
font-size: 20px;
border: none;
border-radius: 2px;
}
.display {
text-align: center;
}
.clear {
/* background image here */
}
.clouds {
/* another background image here */
}
<!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>Document</title>
<link rel="stylesheet" href="weather_app.css">
</head>
<body>
<div class="input">
<input type="text" class="inputValue" placeholder="Enter a city">
<input type="submit" value="Submit" class="button">
</div>
<div class="display">
<h1 class="name"></h1>
<p class="weather"></p>
<p class="desc"></p>
<p class="temp"></p>
<p class="humi"></p>
</div>
<script src= "weather_app.js"></script>
</body>
</html>
I did a project like this not long ago, https://github.com/Kroplewski-M/Weather-App , I used the openWeater API. I did this:
function setBackground(weather) {
if (weather == "Rain") {
background.src = "./resources/rainy-weather.jpg";
} else if (weather == "Snow") {
background.src = "./resources/snowy-weather.jpg";
} else if (weather == "Clear") {
background.src = "./resources/sunny-weather.jpg";
} else if (weather == "Clouds") {
background.src = "./resources/cloudy-weather.jpg";
}
}
The openWeather API returns what condition the weather is so you can just if statement on what the condition is and set the background accordingly

How to make the new messege display under the old messege? Chatbot javascript

I want build a chatbot where the users will write anything and the bot will also reply instantly. But I want to make my chatbot more like e chat application like I want to print the messege under the old messege and it will contunue. Right now if I click send button then the new messege appear in the old div. But I want to print under that old messege. And also I want to add a scroll function in my chatbot so that old messege can be seen by scrolling down and up. I try append() and several other way but can't do it.Plz run the code then you all will get an idea, how it works.Here's my code
index.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>Mecha Tausif</title>
<link rel="stylesheet" href="../css/bootstrap.min.css">
<link rel="stylesheet" href="../css/style.css">
</head>
<body>
<div class="box">
<div style="text-align: center;" class="top">
<h1> Mecha Tausif </h1>
</div>
<div>
<div>
<p id="display1">display</p>
<p style="font-size:12px ;" id="datedisp1">date</p>
</div>
<div style="text-align: right;">
<p id="display2"> bingo</p>
<p style="font-size:12px ;" id="datedisp2">date</p>
</div>
<div class="input">
<input type="text" id="userbox">
<button id="btn">Send</button>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.16.1/dist/umd/popper.min.js"
integrity="sha384-9/reFTGAW83EW2RDu2S0VKaIzap3H66lZH81PoYlFhbGU+6BZp6G7niu735Sk7lN"
crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"
integrity="sha384-B4gt1jrGC7Jh4AgTPSdUtOBvfO8shuf57BaghqFfPlYxofvL8/KUEfYiJOMMV+rV"
crossorigin="anonymous"></script>
<script type="module" src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.esm.js"></script>
<script nomodule src="https://unpkg.com/ionicons#5.5.2/dist/ionicons/ionicons.js"></script>
<script src="../js/script.js"></script>
</body>
</html>
`
style.css
body {
margin: 0;
padding: 0;
width: 100%;
height: 100vh;
background-color: rgb(146, 221, 221);
}
.box{
width: 300px;
height: 550px;
background-color:white;
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
.top{
width: 100%;
height: 80px;
background: rgb(4, 61, 61);
}
.top h1{
margin: 0;
font-size: 30px;
color: rgb(247, 240, 240);
text-align: center;
padding-top: 10px;
font-family: sans-serif
}
.input{
padding-top: 200px;
}
.input input{
width: 100%;
height: 60px;
padding-left: 30px;
font-family: monospace;
background: rgb(255, 253, 253);
}
`
script.js
let btn = document.getElementById('btn');
let display1 = document.getElementById('display1');
let display2 = document.getElementById('display2');
let dispdate1 = document.getElementById('datedisp1');
let dispdate2 = document.getElementById('datedisp2');
var chat = ['hello', 'how are you doing', 'what is your name', 'from where you are', 'do you love coffee', 'great', 'it is good to know you'];
btn.addEventListener('click', function () {
var randomchat = chat[Math.floor(Math.random() * chat.length)]
display1.innerHTML = randomchat;
let display = document.getElementById('userbox').value;
document.getElementById('display2').innerHTML = display;
document.getElementById('userbox').value = '';
function date() {
let today = new Date();
let hours = today.getHours();
let minutes = today.getMinutes();
let ampm = hours >= 12 ? 'pm' : 'am';
hours = hours % 12;
hours = hours ? hours : 12;
let date = today.getDate();
const month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
let nmonth = month[today.getMonth()];
let fullyear = today.getFullYear();
let current_date = `${hours}:${minutes} ${ampm}, ${date}th ${nmonth}, ${fullyear}`;
dispdate1.innerHTML=current_date;
dispdate2.innerHTML=current_date;
}
date();
})

5 day weather forecast on openweathermap not giving expected result

I'm trying to fetch a 5-day weather forecast by using JS Fetch API, though I'm passing cnt=5 as stated in the documentation, Still, I'm getting only current weather. Am I missing anything?
fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city+ '&appid=' + key+'&cnt=5')
I have done enough research and couldn't able to figure out where exactly I'm doing a mistake. Any help is appreciated.
const key = '**** Your API Key Here ****';
function weatherForecast(city) {
fetch('https://api.openweathermap.org/data/2.5/weather?q=' + city+ '&appid=' + key+'&cnt=5')
.then(function(resp) {
return resp.json()
})
.then(function(data) {
console.log('--->'+(JSON.stringify(data)));
drawWeather(data);
})
.catch(function() {
// catch any errors
});
}
function drawWeather( d ) {
var celcius = Math.round(parseFloat(d.main.temp)-273.15);
var fahrenheit = Math.round(((parseFloat(d.main.temp)-273.15)*1.8)+32);
var description = d.weather[0].description;
document.getElementById('description').innerHTML = description;
document.getElementById('temp').innerHTML = fahrenheit + '°';
document.getElementById('location').innerHTML = d.name+' '+d.sys.country;
}
//Event Listeners on button click
document.addEventListener("DOMContentLoaded", () => {
// Handling button click
document.querySelector(".button-search").addEventListener("click", () => {
const searchedCity = document.querySelector('.text-search');
console.log(searchedCity.value);
if(searchedCity.value){
weatherForecast(searchedCity.value);
}
})
});
body {
font-family: 'Montserrat', sans-serif;
font-weight: 400;
font-size: 1.3em;
height: 100vh;
}
h1 {
margin: 0 auto;
font-size: 2.2em;
text-align: center;
font-size: 10em;
}
.main-container,.search-component{
display: flex;
align-items: center;
justify-content: center;
margin: 2em;
}
.text-search{
width: 100%;
max-width: 280px;
padding: 10px 15px;
border: solid blueviolet;
color: #313131;
font-size: 20px;
font-weight: 300;
transition: 0.2s ease-out;
}
.button-search{
font-size: 32px;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Current Weather</title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:400,900" rel="stylesheet">
<link href="style.css" rel="stylesheet">
</head>
<body>
<div class="search-component">
<input type="text" autocomplete="off" class="text-search" placeholder="Type the City Name..." >
<input type="button" class="button-search" value="Search">
</div>
<div class="main-container">
<div>
<div id="description"></div>
<h1 id="temp"></h1>
<div id="location"></div>
</div>
<div>
<script src="main.js"></script>
</body>
</html>
Here is the JSON response I'm getting.
{
"coord":{"lon":-74.01,"lat":40.71},
"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],
"base":"stations",
"main":{
"temp":303.24,
"feels_like":306.4,
"temp_min":301.48,
"temp_max":304.82,
"pressure":1011,
"humidity":74
},
"visibility":10000,
"wind":{"speed":4.6,"deg":260},
"clouds":{"all":1},
"dt":1596415305,
"sys":{
"type":1,
"id":4610,
"country":"US",
"sunrise":1596362046,
"sunset":1596413419
}
"timezone":-14400,
"id":5128581,
"name":"New York",
"cod":200
}
For a 5-day weather forecast you need call /forecast instead of /weather endpoint.
Example:
https://api.openweathermap.org/data/2.5/forecast?q=New%20York&appid=<your-api-key>&cnt=5

Canvas - How to do background image moving

I want background image to keep moving from left to right.
Any idea how can I do that ? I tried to use code from stackoverflow, didnt work, I tried to google, didnt work.
This is my code. There is nothing about the moving background I am just placing it here because it might help. I´d like to know why any code never worked.
<!DOCTYPE html>
<html dir='ltr'>
<head>
<title>Temponary Rush</title>
<meta charset='UTF-8'>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
<script type='text/javascript' src='js/classes.js'></script>
<style>
body {
background-color: #232B2B;
background-image:url('../web/css/cave-background.png');
background-position:top;
background-repeat:no-repeat;
color:#FFFFFF;
}
#container{
flex-flow: row nowrap;
display: -webkit-flex;
-webkit-justify-content: space-around;
display: flex;
justify-content: space-around;
}
#container > div {
background: #5F85DB;
padding: 5px;
color: #fff;
font-weight: bold;
font-family: Tahoma;
border:5px inset #DC3D24;
background-color:#232B2B;
}
#container > .advert {
width:200px;
}
canvas {
background-image:url('imgs/backgrounds/cave-bcg.png');
background-position:center;
}
</style>
</head>
<body>
<div id='container'>
<div id='left' class='advert'>
levá strana
</div>
<div id='center'>
<canvas id="ctx" width="800" height="600"></canvas>
<script type='text/javascript'>
var ctx = document.getElementById("ctx").getContext("2d");
ctx.font = '30px Arial';
ctx.fillStyle = 'white';
var player = {
x: 10,
y: 549,
spdX: 1,
spdY: 51,
width:50,
height:50
};
var obstacles = [
];
var allowedJump = true;
document.onkeydown = function(event){
if (event.keyCode === 32 && allowedJump) {
for(i; i<10;i++){
setTimeout(function(){
player.y-= player.spdY/10;
},60);
}
setTimeout(function(){
allowedJump = true;
player.y+=player.spdY;
},600);
};
allowedJump = false;
};
setInterval(update,10);
function update(){
ctx.clearRect(0,0,800,600,45);
ctx.fillRect(player.x, player.y, player.width, player.height);
player.x += player.spdX;
for(i = 0; i < obstacles.length; i++) {
ctx.fillRect(obstacles[i][0], obstacles[i][1], obstacles[i][2], obstacles[i][3]);
var is_colliding = collision.testCollision(player,obstacles[i][0], obstacles[i][1],obstacles[i][2],obstacles[i][3]);
if(is_colliding) {
afterImpact.stun(2,player);
}
}
}
</script>
</div>
<div id='right' class='advert'>
pravá strana
</div>
</div>
</body>
</html>
I have the website on xampp server for now, later I will go to node.js server.
this is my file tree.
please remove this code from body
body {
background-color: #232B2B;
background-image:url('../web/css/cave-background.png');
background-position:top;
background-repeat:no-repeat;
color:#FFFFFF;
}
you can set the following div code inside the body tag
div{
background-color: #232B2B;
background-image:url('../web/css/cave-background.png');
background-position:top;
background-repeat:no-repeat;
}

Animated image (e.g. non-GIF) with JavaScript and CSS?

I had been trying to animate a .png file with JavaScript while following this method. This is the .png file that I want to animate. I want the animated logo to be right by "Cupquake," but the logo doesn't even show up, let alone animate. However, changing "span class=logoCquake" in HTML to a div class displays the logo, but it is below the text.
My JavaScript file:
var scrollUp = (function () {
var timerId;
return function (height, times, element) {
var i = 0;
timerId = setInterval(function () {
if (i > times)
i = 0;
element.style.backgroundPosition = "0px -" + i * height + 'px';
i++;
}, 100);
};
})();
scrollUp(130, 30, document.getElementByClass('logoCquake'))
My HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script src="../scripts/logoCquake.js" type="text/javascript"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="wrapper">
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<br>
<br>
<br>
<span class="ninja">Ninja</span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
CSS file:
#font-face
{
font-family: typo_semib;
src: url('fonts/typo_semib.ttf');
}
#font-face
{
font-family: typo_light;
src: url('fonts/typo_light.ttf');
}
.wrapper .header
{
height: 250px;
width: 100%;
background: -webkit-gradient(linear,left top,left bottom,color-stop(0%,#ffa200), color-stop(100%,#d25400));
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffa200',endColorstr='#d25400',GradientType=0);
background: -moz-linear-gradient(top,#ffa200,#d25400);
background-image: -o-linear-gradient(#ffa200,#d25400);
overflow: hidden;
}
.wrapper .header .topbar
{
height: 60px;
background-image: url(../imgz/head/hBarSBg.png);
background-repeat: repeat-x;
}
.wrapper .header .topbar .mCquake
{
height: 37px;
width: 278px;
background-image: url(../imgz/head/mCqRight.png);
background-repeat: no-repeat;
float: none;
float: right !important;
margin-right: 10px;
margin-top: 11.5px;
margin-bottom: 11.5px;
}
.wrapper .header .ninja
{
font-family: typo_semib;
font-size: 48px;
color: #303030;
margin-left: 55px;
}
.wrapper .header .cupquake
{
font-family: typo_light;
font-size: 48px;
color: #303030;
}
.wrapper .header .logoCquake
{
height: 112px;
width: 130px;
background-image: url(../imgz/logo/logoCquake.png);
background-repeat: no-repeat;
}
EDIT:
Tried again, but with the second method listed here, still nothing. These are my current HTML and JS codes:
JS:
function SpriteAnim (options) {
var timerId,
i = 0,
element = document.getElementByClass(options.elementClass);
element.style.width = options.width + "px";
element.style.height = options.height + "px";
element.style.backgroundRepeat = "no-repeat";
element.style.backgroundImage = "url(" + options.sprite + ")";
timerId = setInterval(function () {
if (i >= options.frames) {
i = 0;
}
element.style.backgroundPosition = "0px -" + i * options.height + "px";
i ++;
}, 100);
this.stopAnimation = function () {
clearInterval(timerId);
};
}
var cupcake = new SpriteAnim({
width: 130,
height: 112,
frames: 30,
sprite: "..\imgz\logo\logoCquake.png",
elementClass : "logoCquake"
});
HTML:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" href="../css/normalize.css" />
<link rel="stylesheet" href="../css/style.css" />
<script language="javascript" src="SpriteAnim.js">
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Cupquake - Home</title>
</head>
<body>
<div class="header">
<div class="topbar">
<div class="mCquake">
</div>
</div>
<span class="ninja">Ninja </span><span class="cupquake">Cupquake</span><span class="logoCquake"></span>
</div>
</div>
</body>
</html>
my code seems to work:
<!doctype html>
<style>
div{background:url(http://i1243.photobucket.com/albums/gg555/Nyanja/logoCquake.png);height:33px;width:39px}
</style>
<div id=anim></div>
<script>
var i=0;
setInterval(function(){i+=33.6;document.getElementById("anim").style.backgroundPosition="0px "+i+"px"},100)
</script>
I believe 'span' tag being an inline element it either needs a 'display: block' property or 'float: left', i tried your code and it worked for me after i added 'display: block' to the 'span' tag with class 'logoCquake'. Hope this helps you.
Note: if you use 'display: block' the span will move to new line and if you use 'float: left' the 'span' tag will move to the left of the text.

Categories

Resources