5 day weather forecast on openweathermap not giving expected result - javascript

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

Related

js function stops acting

![Text](https://stackoverfl
var obj = {
count: 1
}
function elementSet()
{
if(obj.count=1){
document.getElementById("text").textContent = "graa";}
if(obj.count=2){
document.getElementById("text").textContent = "graa";}
if(obj.count=3){
document.getElementById("text").textContent = "graa";}
}
function back()
{
if(obj.count>1)
{
obj.count = obj.count -1;
document.getElementById("back").style.display = "block";
document.getElementById("page_num").textContent = obj.count;
}
}
function forth()
{
if(obj.count<3){
obj.count = obj.count +1;
document.getElementById("page_num").textContent = obj.count;
document.getElementById("forth").style.display = "block";
if (obj.count>3){
document.getElementById("forth").style.display = "none";}
}
}
.colx1 {
color: #e1992e;
/* height: 3px; */
font-size: 2.1ch;
margin-right: 80%;
inline-size: auto;
border-color: #e1992e;
border-radius: 11ch;
}
.colx2 {
color: #e1992e;
font-size: 2.1ch;
inline-size: auto;
margin-top: -3%;
margin-left: 80%;
border-color: #e1992e;
border-radius: 11ch;
}
.colabount
{
width: 170px;
}
.row {
display: inline;
}
.body
{
text-align: center;
max-height: 100%;
}
.button {
border-color: #e1992e;
}
.page_num
{
color: black;
size: 13ch;
text-align: center;
}
.text
{
color: blanchedalmond;
size: 12ch;
}
<!DOCTYPE html>
<html>
<head>
<title>films</title>
<link rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap#4.5.3/dist/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
</head>
<body class="body">
<div class="container external internal" id="content">
<h2 id="text" class="text" type="textContent"> its the f</h2>
<div class="row">
<button class="colx1" id="back" type="button" onclick="back(),elementSet()"><b>back</d></button>
<button class="colx2" id="forth" type="button" onclick="forth(),elementSet()"><b>forth</d></button>
</div>
<div class="page_num"><b id ="page_num">1</b></div>
</div>
</body>
</html>
ow.com/image.jpg)
i tried to create external obj that contain count its working.
the page content will change acording to the count number.
the proble starts when im calling 'elementSet' = {checking abount obj.count and
changing the page acordingly}
THE PROBLEM : when elementSet runs back() and forth() not working anymore!
your mistake is that:
in java script = is assignment. for example: let a = 0;
we assignment 0 to a. now a is 0.
and we have == and ===. these are use for comparison in logics and Condition. for example:
let a = 0;
a == 0 && console.log("yes");
there are some different between == and ===. you can read that in a link!

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

looking for why list does not display when adding task to the to do

Good day folks,
I am creating a to-do app, and so far when I enter the task in via the input the console shows my object firing but does not display it on the screen. Please look at my code and help me point out the issue, I have been debugging this for some time today.
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="css/to-doStylesheet.css">
<title>To-Do App</title>
</head>
<body>
<div class=container>
<div class= base>
<div class = screen>
<img src="images/WarGreymon_Render.png" alt="Wargreymon">
<div id ="speach-bubble"> What is on your
agenda for today?
</div>
<div class = "dateTime">
</div>
</div>
<div class = "nameInput" id = "inputContainer">
<form class ="form">
<input type="text" class ="userInput" placeholder="Add Agenda and press enter">
<input type="submit" value ="Add">
</form>
</div>
</div>
<ul class="list"></ul>
<script src="js/add-task.js"></script>
</body>
</html>
CSS
.form
{
margin-left: 400px;
}
.userInput
{
width: 394px;
height: 30px;
background-color: #B62626;
font-family: Digimon Basic;
color: #33D61A;
margin-left: -359px;
}
.userInput ::placeholder
{
color: #33D61A;
font-family: Digimon Basic;
}
.list:empty
{
display: none;
}
.list
{
list-style: none;
margin-bottom: 20px;
}
.input[type="checkbox"] {
display: none;
}
.tick {
width: 30px;
height: 30px;
border: 3px solid #333;
border-radius: 50%;
display: inline-flex;
justify-content: center;
align-items: center;
cursor: pointer;
}
.todo-item {
margin-bottom: 10px;
width: 100%;
display: flex;
align-items: center;
justify-content: space-between;
}
.todo-item span {
flex-grow: 1;
margin-left: 10px;
margin-right: 10px;
font-size: 22px;
}
JS
let tasks = [];
const currentdt = new Date()
function todo(text) {
const todo = {
text,
checked: false,
id: Date.now(),
timestamp: currentdt
};
tasks.push(todo);
console.log(tasks);
}
// Select the form element
const form = document.querySelector('.form');
// Add a submit event listener
form.addEventListener('submit', event => {
// prevent page refresh on form submission
event.preventDefault();
// select the text input
const input = document.querySelector('.userInput');
// Get the value of the input and remove whitespace
const text = input.value.trim();
if (text !== '') {
todo(text);
input.value = '';
input.focus();
}
});
//This function is to display new to do on the screen
function displaytasks(todo)
{
const list = document.querySelector('list');
const isChecked = todo.checked ? 'done': '';
const addedList = document.createElement("li");
addedList.setAttribute('class', `todo-item ${isChecked}`);
addedList.setAttribute('data-key', todo.timestamp);
addedList.innerHTML = `<input id="${todo.timestamp}" type="checkbox"/>
<label for="${todo.timestamp}" class="tick js-tick"></label>
<span>${todo.text}</span>
<button class="delete-todo js-delete-todo">
<img class = "delete" src="images/delete.png" alt="delete icon">
</button>`;
list.append(addedList);
}
So I am busy with the js file at the moment, I think it has to do something with the innerHTML, but I am not sure what exactly is wrong there, because when I look in the console on the HTML side I do not see the <ul class="list"></ul> firing at all to bring the new HTML elements.
Your help will be much appreciated
It looks like the code to display the todos is not being called, so I would recommend you add in a function call after reading in a new todo.
...
const text = input.value.trim();
if (text !== '') {
todo(text);
input.value = '';
input.focus();
displaytasks(tasks); // Show tasks after submission
}
});
//This function is to display new to do on the screen
function displaytasks(todo)
{
const list = document.querySelector('.list');
...

Ho can I get these images to appear in random spots on the page?

I am creating a collage app that has an dogAPI. When the breed is selected a dog image will appear. I want the image to appear in a random spot on the page but ideally not over the text and dropdown menu. This is what I have tried and here is my codepen. This is an app so it needs to also be responsive.
//Get a random number
let getRandomNum = (num) => {
return Math.floor(Math.random() * Math.floor(num));
}
//show image in a random location
let moveImg = () => {
let dogImgs = document.querySelector('.dogPic')
let w = window.innerWidth;
let h = window.innerHeight;
dogImgs.style.top = getRandomNum(w) + "px";
dogImgs.style.left = getRandomNum(h) + "px";
};
https://codepen.io/drxl/pen/VwbQZyK
Your moveImg function is flawed - it uses querySelector which will only select the first element. It should ideally accept an image as a parameter.
We can declare it like so:
let moveImg = (dogImgs) => {
let w = window.innerWidth;
let h = window.innerHeight;
dogImgs.style.top = getRandomNum(w) + "px";
dogImgs.style.left = getRandomNum(h) + "px";
};
Then, in your createImgs function, simply pass the constructed image as a parameter to moveImg.
// fetches dog breed list/shows error if applicable
async function start() {
try {
const response = await fetch("https://dog.ceo/api/breeds/list/all")
const data = await response.json()
breedList(data.message)
} catch (e) {
console.log("There was a problem fetching the breed list.")
alert("There was a problem fetching the breed list.")
}
}
//load breed list in dropdown menu
start()
function breedList(dogList) {
document.getElementById("breeds").innerHTML = `
<select onchange="loadByBreed(this.value)">
<option>Choose a dog breed</option>
${Object.keys(dogList).map(function (breed) {
return `<option>${breed}</option>`
}).join('')}
</select>
`
}
//load images
async function loadByBreed(breed) {
if (breed != "Choose a dog breed") {
const response = await fetch(`https://dog.ceo/api/breed/${breed}/images`)
const data = await response.json()
createImgs(data.message)
}
}
//show randomized images
function createImgs(images) {
let imageContainer = $(".slideshow");
let dogImgs = $('<img>');
dogImgs.attr("src", images[Math.floor(Math.random() * images.length)]);
dogImgs.addClass("dogPic")
imageContainer.append(dogImgs);
moveImg(dogImgs[0]);
}
//deletes pic if dbl tapped
$(document).on('dblclick', ".dogPic", function () {
$(this).remove();
})
//resets select menu when image has loaded
$("#breeds").on("change", "select", function () {
const value = this.value;
console.log(value);
let select = this
setTimeout(function () {
select.selectedIndex = 0;
}, 800)
});
//Get a random number
let getRandomNum = (num) => {
return Math.floor(Math.random() * Math.floor(num));
}
let moveImg = (dogImgs) => {
let w = window.innerWidth;
let h = window.innerHeight;
dogImgs.style.top = getRandomNum(w) + "px";
dogImgs.style.left = getRandomNum(h) + "px";
};
body {
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
background-color: rgb(26, 43, 38);
}
.header {
text-align: center;
color: white;
font-size: 1.75rem;
max-width: 80%;
margin-top: 3rem;
}
select {
font-size: 2rem;
margin-bottom: 4rem;
font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
text-transform: capitalize;
color: black;
background-color: rgb(255, 255, 255);
}
.main-container {
display: flex;
flex-direction: column;
align-items: center;
}
.slideshow {
overflow: hidden;
text-align: center;
}
img {
max-width: 40%;
margin-top: 25rem;
position: absolute;
left: 100px;
top: 100px;
}
.top_link_position {
display: block;
position: fixed;
bottom: 4%;
right: 3%;
z-index: 600;
}
.top_btn {
border: 1.5px solid white;
background: black;
padding: .5rem .5rem;
color: white;
font-weight: bolder;
text-transform: uppercase;
}
#media screen and (max-width: 425px) {
.header {
font-size: 1.25rem;
}
select {
font-size: 1.5rem;
}
}
<!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="https://use.fontawesome.com/releases/v5.15.3/css/all.css" integrity="sha384-SZXxX4whJ79/gErwcOYf+zWLeJdY/qpuqC4cAa9rOGUstPomtqpuNWT9wdPEn2fk" crossorigin="anonymous">
<!-- <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> -->
<link rel="stylesheet" href="styles.css">
<title>Dog Collage</title>
</head>
<body>
<!--Title and menu-->
<div class="main-container">
<div class="header">
<h1>Dog Collage!</h1>
<p>Select a dog and create your collage!</p>
<p>Double-tap to remove an image.</p>
<div id="breeds"></div>
</div>
</div>
<div class="slideshow" id="imgs">
</div>
<!-- Modal
<div id="my-modal" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="pokemonModalLabel"
aria-hidden="true">
<div class="modal-dialog modal-dialog-centered" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" aria-labelledby="pokemonModalLabel">Modal title</h5>
<button type="button" class="modal-close" id=".modal-close" data-dismiss="modal" aria-label="Close">X</button>
</div>
<div class="modal-body"></div>
</div>
</div>
</div> -->
<!--Top of Page Button-->
<div class="top_link_position">
<a class="back-to-top" href="#page_top" title="Top">
<button class="top_btn"><span class="icon"><i class="fas fa-chevron-up fa-2x"></i></span></button>
</a>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>
<script src="src/index.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>
</body>
</html>

How to disable previous button on today's date? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I just want to disable the previous button on today's date.
The previous Button should be disabled when it comes to today's date.
Please help me to disable previous dates in the calender so that the user can only select the start date from today's date and onwards.
I am using moment.js for my Datepicker. Thank you!
This is output
var currDate = "";
function DateHelper(date) {
if (date === undefined) {
date = new Date();
}
// Require MomentJS: https://momentjs.com
return {
today: function today() {
return moment(date).format('ll');
},
nextDay: function nextDay() {
return moment(date).add(1, 'day').format('ll');
},
prevDay: function prevDay() {
return moment(date).subtract(1, 'day').format('ll');
},
toString: function toString() {
return moment(date).format('ll');
} };
}
// Save/Load LocalStorage
function save(data) {
localStorage["DiaryData"] = JSON.stringify(data);
}
function loadOrDefault(defaultObject) {
if (localStorage["DiaryData"] !== undefined) {
return JSON.parse(localStorage["DiaryData"]);
} else {
return defaultObject;
}
}
// Load data or setup default data
var allData = loadOrDefault({
"2017-05-11": "Hello World.",
"2017-05-31": "Hello World Again.",
"2017-06-01": "Tomorrow is another day~" });
// todo: render day
function setDiaryPage(pDate)
{
currDate = pDate;
$(".date").text(currDate);
$("#diaryContent").val(getDiaryContent(currDate));
}
function getDiaryContent(pDate)
{
return allData[DateHelper(pDate).toString()];
}
// todo: init
setDiaryPage(DateHelper().today());
// handling date choosing UI
$("#today").click(function () {
setDiaryPage(DateHelper().today());
});
$("#prevdate").click(function () {
setDiaryPage(DateHelper(currDate).prevDay());
});
$("#nextdate").click(function () {
setDiaryPage(DateHelper(currDate).nextDay());
});
$('#diaryContent').bind('input propertychange', function () {
onTextChange();
});
// handling content changes
function onTextChange() {
allData[DateHelper(currDate).toString()] = $("#diaryContent").val();
save(allData);
}
* {box-sizing: border-box}
.page {
width: 100%;
max-width: 400px;
margin: 0 auto;
}
.date {
background: #555;
color: #fff;
padding: 1em;
font-weight: 700;
text-align: center;
}
.prev-button{text-transform: uppercase;
background-color: red !important;
font-weight: 800;
border-radius: 0px;
background-color: red !important;
border-radius: 0px;
border: none;
width: 100%;
padding: 1em;
color: white;}
.row.no-gutters {
margin-right: 0;
margin-left: 0;
}
.row.no-gutters > [class^="col-"],
.row.no-gutters > [class*=" col-"] {
padding-right: 0;
padding-left: 0;
}
<!DOCTYPE html>
<html lang="en" >
<head>
<meta charset="UTF-8">
<title>Testing Date</title>
<!-- 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">
</head>
<body>
<div class="row no-gutters">
<div class="col-lg-4 col-xs-4"> <button class="prev-button" style="" id="prevdate" href="#prev-date" onclick="myFunction()">previous date</a></div>
<div class="col-lg-4 col-xs-4"> <div class="date"></div></div>
<div class="col-lg-4 col-xs-4"> <button class="prev-button" id="nextdate" href="#next-date">Next date</button></div>
<!-- <div class="col-lg-3"> <button class="prev-button" id="today" href="#today">Today</button></div> -->
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js'></script>
</body>
</html>
Please Try This
var currDate = "";
function DateHelper(date) {
if (date === undefined) {
date = new Date();
}
// Require MomentJS: https://momentjs.com
return {
today: function today() {
return moment(date).format('ll');
},
nextDay: function nextDay() {
return moment(date).add(1, 'day').format('ll');
},
prevDay: function prevDay() {
return moment(date).subtract(1, 'day').format('ll');
},
toString: function toString() {
return moment(date).format('ll');
}
};
}
// Save/Load LocalStorage
function save(data) {
localStorage["DiaryData"] = JSON.stringify(data);
}
function loadOrDefault(defaultObject) {
if (localStorage["DiaryData"] !== undefined) {
return JSON.parse(localStorage["DiaryData"]);
} else {
return defaultObject;
}
}
// Load data or setup default data
var allData = loadOrDefault({
"2017-05-11": "Hello World.",
"2017-05-31": "Hello World Again.",
"2017-06-01": "Tomorrow is another day~"
});
// todo: render day
function setDiaryPage(pDate) {
currDate = pDate;
$(".date").text(currDate);
$("#diaryContent").val(getDiaryContent(currDate));
}
function getDiaryContent(pDate) {
return allData[DateHelper(pDate).toString()];
}
// todo: init
setDiaryPage(DateHelper().today());
// handling date choosing UI
$("#today").click(function() {
setDiaryPage(DateHelper().today());
});
$("#prevdate").click(function() {
setDiaryPage(DateHelper(currDate).prevDay());
if (DateHelper().today() == $('.date').text()) {
$("#prevdate").addClass('hide');
} else {
$("#prevdate").removeClass('hide');
}
});
$("#nextdate").click(function() {
setDiaryPage(DateHelper(currDate).nextDay());
if (DateHelper().today() == $('.date').text()) {
$("#prevdate").addClass('hide');
} else {
$("#prevdate").removeClass('hide');
}
});
$('#diaryContent').bind('input propertychange', function() {
onTextChange();
});
// handling content changes
function onTextChange() {
allData[DateHelper(currDate).toString()] = $("#diaryContent").val();
save(allData);
}
if (DateHelper().today() == $('.date').text()) {
$("#prevdate").addClass('hide');
}
* {
box-sizing: border-box
}
.page {
width: 100%;
max-width: 400px;
margin: 0 auto;
}
.date {
background: #555;
color: #fff;
padding: 1em;
font-weight: 700;
text-align: center;
}
.prev-button {
text-transform: uppercase;
background-color: red !important;
font-weight: 800;
border-radius: 0px;
background-color: red !important;
border-radius: 0px;
border: none;
width: 100%;
padding: 1em;
color: white;
}
.row.no-gutters {
margin-right: 0;
margin-left: 0;
}
.row.no-gutters>[class^="col-"],
.row.no-gutters>[class*=" col-"] {
padding-right: 0;
padding-left: 0;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Testing Date</title>
<!-- 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">
</head>
<body>
<div class="row no-gutters">
<div class="col-lg-4 col-xs-4"> <button class="prev-button" style="" id="prevdate" href="#prev-date" onclick="myFunction()">previous date</a></div>
<div class="col-lg-4 col-xs-4"> <div class="date"></div></div>
<div class="col-lg-4 col-xs-4"> <button class="prev-button" id="nextdate" href="#next-date">Next date</button></div>
<!-- <div class="col-lg-3"> <button class="prev-button" id="today" href="#today">Today</button></div> -->
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js'></script>
<script src='https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js'></script>
</body>
</html>

Categories

Resources