link in html is not working - javascript

I have the following code snippet that I am embedding into a Wix website.
// JavaScript
var countries = [
{ name: 'Thailand', link: 'www.google.com' },
{ name: 'Tanzania', link: '' },
{ name: 'Tunisia', link: '' },
{ name: 'Taiwan', link: '' },
];
var matchingCountries = [];
function updateCountry() {
var searchTerm = document.getElementById('countrySearchInput').value;
var resultsList = document.getElementById('countrySearchResults');
resultsList.innerHTML = '';
if(searchTerm.length === 0) return;
var matchingCountries = countries.filter(function(country) {
return country.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;
});
if(matchingCountries.length > 0) {
var fewerCountries = matchingCountries.splice(0, Math.min(matchingCountries.length, 5));
fewerCountries.forEach(function(country) {
resultsList.innerHTML += "<li><a href='" + country.link + "'>" + country.name + "</a></li>";
});
} else {
resultsList.innerHTML += "<li>No search results</li>";
}
}
function startSearch() {
document.getElementById('countrySearchResultsContainer').style.display = 'block';
}
function endSearch() {
document.getElementById('countrySearchResultsContainer').style.display = 'none';
}
/* CSS */
#country-search {
font-family: Helvetica;
}
*, *:before, *:after {
box-sizing: border-box;
}
#country-search {
width: 400px;
display: block;
}
#country-search .entry input {
width: 400px;
font-size: 24px;
padding: 12px;
border-radius: 10px;
border: 3px solid white;
background-color: rgba( 150, 150, 150, 0.1);
margin: 0;
}
#country-search .entry input:focus {
/*
border: 3px solid white;
outline: none;
*/
}
#countrySearchResultsContainer {
width: 100%;
border: 3px solid #eee;
border-radius: 5px;
display: none;
background-color: rgba(220,220,220,0.7);
}
#countrySearchResults {
margin: 0;
width: 100%;
padding: 0;
}
#countrySearchResults li {
font-size: 24px;
list-style-type: none;
padding: 12px;
}
#countrySearchResults li:hover {
background-color: #eee;
}
#countrySearchResults li:not(:last-child) {
padding-bottom: 10px;
}
#countrySearchResults li a {
text-decoration: none;
color: black;
}
#countrySearchResults li a:visited {
color: black;
}
#countrySearchInput {
color: white;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#countrySearchInput::-webkit-input-placeholder {
color: white;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#countrySearchInput::-moz-placeholder {
color: white;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#countrySearchInput::-ms-input-placeholder {
color: white;
text-align: center;
margin-left: auto;
margin-right: auto;
}
#countrySearchInput::-ms-placeholder {
color: white;
text-align: center;
margin-left: auto;
margin-right: auto;
}
<!-- HTML -->
<div id="country-search">
<div class="entry">
<input id="countrySearchInput" type="text" placeholder="Enter a country name" onkeyup="updateCountry()" onfocus="startSearch()" onblur="endSearch()" />
</div>
<div id="countrySearchResultsContainer">
<ul id="countrySearchResults">
</ul>
</div>
</div>
In this script, I am trying to type in Thailand, and when it appears as an option, I click it. However, when I do, the website: "www.google.com" does not pop up. What am I missing?

The URL that you have entered is incorrect. When referencing external websites you need to include the scheme. Change the link from www.google.com to http://www.google.com and you will be able to open the link when entering Thailand.

When you use www.google.com, the link will refer to a file or something in the folder the HTML files in in called www.google.com. If you want to use a weblink in your file, you should consider adding http:/ or https:/ before your link.
https:/www.google.com/

Related

can I use checkbox which is in div with Eventlistener?

"use strict";
const diaryInput = document.querySelector(".writing");
const titleInput = document.querySelector(".title");
const submitButton = document.querySelector(".dsubmit");
const indexList = document.querySelector(".womb");
const inputTime = document.querySelector(".clock");
const selectAll = document.querySelector(".select");
const unselectAll = document.querySelector(".unselect");
const deleteIndex = document.querySelector(".delete");
submitButton.addEventListener("click", transferDiary);
selectAll.addEventListener("click", selectAllindex);
unselectAll.addEventListener("click", unselectAllindex);
deleteIndex.addEventListener("click", deleteDiaryIndex);
let layout_no = 0;
function transferDiary(e) {
e.preventDefault();
const indexLayout = document.createElement("div");
indexLayout.classList.add("indexlayout");
indexLayout.id = "indexlayout-" + layout_no;
const diaryIndex = document.createElement("div");
diaryIndex.classList.add("invisible");
diaryIndex.innerText = diaryInput.value;
saveLocalDiary(diaryInput.value);
const diaryTitle = document.createElement("div");
diaryTitle.classList.add("index");
const m = new Array(
"JAN.",
"FEB.",
"MAR.",
"APR.",
"MAY",
"JUN.",
"JUL.",
"AUG",
"SEPT.",
"OCT.",
"NOV.",
"DEC."
);
const years = date.getFullYear();
const months = date.getMonth();
const d = new Array(
"Sun.",
"Mon.",
"Tues.",
"wed.",
"Thurs.",
"Fri.",
"Sat."
);
const days = date.getDay();
const today = date.getDate();
diaryTitle.innerHTML = `<input type='checkbox' name='indexchild' value='' class="indexchild" >${m[months]} ${today} ${years} ${d[days]} -${titleInput.value}</>`;
indexLayout.appendChild(diaryTitle);
diaryTitle.appendChild(diaryIndex);
indexList.appendChild(indexLayout);
const wayBackHome = document.getElementById("indexlayout-" + layout_no);
wayBackHome.addEventListener("click", bringBackIndex);
layout_no++;
}
function selectAllindex(e) {
e.preventDefault();
const checkboxes = document.querySelectorAll("input[type=checkbox]");
for (const cb of checkboxes) {
cb.checked = true;
}
}
function unselectAllindex(e) {
e.preventDefault();
const checkboxes = document.querySelectorAll("input[type=checkbox]");
for (const cb of checkboxes) {
cb.checked = false;
}
}
function deleteDiaryIndex(i) {
i.preventDefault();
const checkboxes = document.querySelectorAll("input[type=checkbox]");
for (let i = 0; i < checkboxes.length; i++) {
if (checkboxes[i].checked) {
removeDiv(checkboxes[i]);
removeLocalDiary(checkboxes[i]);
}
}
}
function removeDiv(d) {
console.log(d.parentElement.parentElement);
console.log(d.parentElement.parentElement[1]);
d.parentElement.parentElement.remove();
}
function bringBackIndex(e) {
e.preventDefault();
const bringEssence = e.target.getElementsByClassName("invisible");
diaryInput.value = bringEssence[0].innerHTML.replace(
/\s?(<br\s?\/?>)\s?/g,
"\r\n"
);
}
function saveLocalDiary(todo) {
//check ---- HEy Do I already have thing in localstorage?
let diary;
if (localStorage.getItem("diary") === null) {
diary = [];
} else {
diary = JSON.parse(localStorage.getItem("diary"));
}
diary.push(todo);
localStorage.setItem("diary", JSON.stringify(diary));
}
function removeLocalDiary(todo) {
let diary;
if (localStorage.getItem("diary") === null) {
diary = [];
} else {
diary = JSON.parse(localStorage.getItem("diary"));
}
const todoIndex = todo.children.innerText;
diary.splice(diary.indexOf(todoIndex), 1);
localStorage.setItem("diary", JSON.stringify(diary));
}
:root {
--page1-color: #20bf6b;
--page2-color: #f7b731;
--page3-color: #4b7bec;
--text-color: white;
}
html {
font-size: 62.5%;
/* 10px=1rem */
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: sans-serif;
}
.page3 {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: var(--page3-color);
width: 70%;
min-width: 600px;
box-shadow: 9px 9px 9px rgb(126, 124, 124),9px 9px 9px rgb(126, 124, 124);
}
.dlayout {
min-height: 90vh;
max-height: 90vh;
border: 1px solid var(--text-color);
display: flex;
}
.dtitle {
min-height: 10%;
border-bottom: 1px solid var(--text-color);
}
.dindex {
min-width: 10vw;
max-width: 15vw;
border-right: 1px solid var(--text-color);
display: flex;
flex-direction: column;
justify-content: space-between;
}
.diary {
min-width: 50vw;
display: flex;
flex-direction: column;
}
.submit {
display: flex;
flex-direction: row;
height: 10%;
border-bottom: 1px solid var(--text-color);
}
.submitime {
padding: 25px 0 0 15px;
color: var(--text-color);
min-width: 50%;
font-size: 3rem;
font-weight: 300;
}
.submitarea {
padding: 20px 0 0 0;
min-width: 40%;
color: var(--text-color);
font-size: 3rem;
letter-spacing: 3px;
font-weight: 300;
}
.title {
background-color: var(--page3-color);
border: 1px dashed var(--text-color);
font-size: 3rem;
outline: none;
height: 40px;
width: 200px;
letter-spacing: 3px;
font-weight: 300;
}
.dsubmit {
margin-top: 10px;
height: 30px;
width: 30px;
background-color: var(--page3-color);
border: none;
border-radius:50%;
cursor: pointer;
}
.dtitle {
color: var(--text-color);
text-align: center;
display: table;
font-size: 3rem;
font-weight: 300;
letter-spacing: 20px;
/* 자간 */
}
p {
display: table-cell;
vertical-align: middle;
}
.writing {
background-color: var(--page3-color);
border: none;
height: 90%;
color: var(--text-color);
font-size: 2.5rem;
letter-spacing: 3px;
font-weight: 100;
}
textarea::placeholder {
color: var(--text-color);
opacity: 0.5;
}
textarea{
resize: none;
}
.indexlayout {
color: var(--text-color);
text-align: center;
font-size: 1.5rem;
border: 1px solid var(--text-color);
margin:5px;
}
.invisible {
display:none ;
}
.womb{
overflow: scroll;
}
.selector{
color: var(--text-color);
width: 100%;
border:none;
border-top: 1px solid var(--text-color);
min-height: 5%;
background-color: var(--page3-color);
outline: none;
font-size: 3rem;
letter-spacing: 8px;
font-weight: 300;
}
.index{
word-break: break-all;
}
.indexchild{
}
.selector:hover{
color:var(--page3-color);
background-color: var(--text-color);
}
.dsubmit:hover{
box-shadow: -3px -3px 3px rgb(172, 172, 172), 3px 3px 3px rgb(237, 237, 237),;
transition: 0.3s;
}
.indexlayout:hover{
color:var(--page3-color);
background-color: var(--text-color);
}
<section class="page3">
<div class="dlayout">
<form id="indexo" name="indexi" class="dindex">
<div class="dtitle"><p>Diary</p></div>
<div class="womb"></div>
<div class="buttons">
<button class="selector select" value="selectall">Select All</button>
<button class="selector unselect" value="unselectall">Unselect All</button>
<button class="selector delete" value="delete">Delete</button>
</div>
</form>
<div class="diary">
<div class="submit">
<div class="submitime clock"></div>
<form class="submitarea">
Title: <input type="text" class="title" />
<button class="dsubmit"><img src="./arrow-circle-right-solid.svg" alt=""></button>
</form>
</div>
<textarea class="writing" placeholder=" shit something..."></textarea>
</div>
</div>
</section>
Hello, I am struggling code above. It is a quite simple diary, the right side has a textarea
tag so you can write your diary and also has a transfer button so you push it, left side is gonna have an index of what you wrote. and I also added a checkbox on the index so you can select/unselect/delete them all at once. if perfectly works fine until I added another function. I added Eventlistener(handler is click) on the index(div .indexlayout), when you click the index it is gonna bring back what you wrote into the textarea tag.
const wayBackHome = document.getElementById("indexlayout-" + layout_no);
wayBackHome.addEventListener("click", bringBackIndex);
It works also okay. so I was quite satisfied. However, a little while later, I found that checkboxes don't work ever since added a new function!!
to be specific, select/unselect All buttons still work and I can check checkboxes with those, but I cannot select checkboxes individually :/
I think it is because I added an event on div which is a parent of a checkbox.
But, not gonna lie, I had no idea how to solve this. I tried "wayBackHome.innerText" or even added event to other div but it didn't work. Could you tell me what I missed and How do I fix it please?
thx!

How to edite li items from separate input jQuery

i work with li and i have issues.
I have input field, which add dynamically values to list, after adding some values, i have function to edite, this value, but this func work not correct, after editing li, it's delete all classes and span button.
HTML:
<form class="qa-form">
<input type="text" class="qa-input" placeholder="Enter text">
<button class="qa-button" id="btn-add">+</button>
<button class="qa-button hidden" id="btn-save">Save</button>
</form>
<div class="item-list"></div>
CSS:
.qa-form {
position: relative;
display: table;
width: 100%;
}
.qa-input {
text-align: left;
width: 100%;
box-sizing: border-box;
background: #fff;
max-width: 100%;
padding: 0.7rem 115px 0.7rem 0.7rem;
border: 1px solid #cbcbce;
border-radius: 6px;
color: #3a3d4b;
}
.qa-button {
position: absolute;
background: #31353D;
padding: 0.6rem 1rem;
border: none;
color: #fff;
border-radius: 5px;
right: 4px;
transform: translateY(2.5px);
}
.list-view ul {
list-style: none;
margin: 0;
padding: 0;
}
.list-view li {
margin-top: 5px;
list-style: none;
cursor: pointer;
background: #efefef;
height: auto;
line-height: 40px;
color: #666;
border-radius: 5px;
padding: 10px;
}
.list-view li:nth-child(2n) {
background: #f7f7f7;
}
.completed {
text-decoration: line-through;
color: gray;
}
.slide {
display: none;
}
.list-view li span {
color: white;
height: 40px;
display: inline-block;
margin-right: 4px;
width: 0;
transition: all .5s;
text-align: center;
opacity: 0;
}
.delete-item {
float: right;
background-color: #dc3545;
}
.edite-item {
float: right;
background-color: #fe6d00;
}
.correct-answ {
float: left;
background-color: #28a745;
}
.list-view li:hover span {
width: 40px;
opacity: 1;
}
.hidden {
display: none;
}
.correct-answer-active {
background-color: rgba(42, 176, 49, 0.45);
}
JQUERY:
$(".item-list").append("<ul id='item-data' class='list-view col-12'></ul>")
$("#btn-add").click(function () {
var inputVal = $(".qa-input").val()
if (inputVal != "") {
$("#item-data").append("<li><span class='delete-item'><i class='fa fa-trash-o'></i></span> <span class='edite-item'><i class='fa fa-edit'></i></span><span class='correct-answ'><i class='fa fa-check-circle-o'></i></span>" + inputVal + "</li>");
$(".qa-input").val(null)
} else {
alert("Add answer to input field")
}
});
$(document).on("click", ".delete-item", function () {
$(this).parent().fadeOut(function () {
$(this).remove();
});
})
$(document).on("click", ".edite-item", function () {
var listValues = $(this).parent();
$("#btn-add").hide()
$("#btn-save").show();
$(".qa-input").val(listValues.text())
editeData(listValues)
});
function editeData(val) {
$("#btn-save").click(function () {
var inputValue = $(".qa-input").val()
if (val === inputValue) {
alert("You are not make changes")
} else {
val.text(inputValue)
$("#btn-add").show()
$("#btn-save").hide();
$(".qa-input").val(null)
}
});
}
$(document).on("click", ".correct-answ", function () {
$(this).parent().css("background-color", "rgba(42, 176, 49, 0.45)")
$(this).parent().attr('active', true);
});
So, i try to find mistake, during all day, and i can't
The main problem is that .text() will also alter your html as you already experienced.
You could replace val.text(inputValue) with $(val).contents().last()[0].textContent = inputValue;
There is also a problem with this line if (val === inputValue) { your val represents the <li> object, and inputValue is ofc the text from the input field, so those will never be the same.
Working demo
$(".item-list").append("<ul id='item-data' class='list-view col-12'></ul>")
$("#btn-add").click(function() {
var inputVal = $(".qa-input").val()
if (inputVal != "") {
$("#item-data").append("<li><span class='delete-item'><i class='fa fa-trash-o'></i></span> <span class='edite-item'><i class='fa fa-edit'></i></span><span class='correct-answ'><i class='fa fa-check-circle-o'></i></span><span class='val'>" + inputVal + "</span></li>");
$(".qa-input").val(null)
} else {
alert("Add answer to input field")
}
});
$(document).on("click", ".delete-item", function() {
$(this).parent().fadeOut(function() {
$(this).remove();
});
})
var edited = null
$(document).on("click", ".edite-item", function() {
var listValues = $(this).closest("li");
$("#btn-add").hide()
$("#btn-save").show();
$(".qa-input").val(listValues.find(".val").text())
edited = listValues
});
$("#btn-save").click(function() {
var pretext = edited.find(".val").text();
var inputValue = $(".qa-input").val()
if (pretext === inputValue) {
alert("You are not make changes")
} else {
edited.find(".val").text(inputValue)
$("#btn-add").show()
$("#btn-save").hide();
$(".qa-input").val("")
}
});
$(document).on("click", ".correct-answ", function() {
$(this).parent().css("background-color", "rgba(42, 176, 49, 0.45)")
$(this).parent().attr('active', true);
});
.qa-form {
position: relative;
display: table;
width: 100%;
margin-top: 50px;
}
.qa-input {
text-align: left;
width: 100%;
box-sizing: border-box;
background: #fff;
max-width: 100%;
padding: 0.7rem 115px 0.7rem 0.7rem;
border: 1px solid #cbcbce;
border-radius: 6px;
color: #3a3d4b;
}
.qa-button {
position: absolute;
background: #31353D;
padding: 0.6rem 1rem;
border: none;
color: #fff;
border-radius: 5px;
right: 4px;
transform: translateY(2.5px);
}
.list-view ul {
list-style: none;
margin: 0;
padding: 0;
}
.list-view li {
margin-top: 5px;
list-style: none;
cursor: pointer;
background: #efefef;
height: auto;
line-height: 40px;
color: #666;
border-radius: 5px;
padding: 10px;
}
.list-view li:nth-child(2n) {
background: #f7f7f7;
}
.completed {
text-decoration: line-through;
color: gray;
}
.slide {
display: none;
}
.list-view li span:not(.val) {
color: white;
height: 40px;
display: inline-block;
margin-right: 4px;
width: 0;
transition: all .5s;
text-align: center;
opacity: 0;
}
.delete-item {
float: right;
background-color: #dc3545;
}
.edite-item {
float: right;
background-color: #fe6d00;
}
.correct-answ {
float: left;
background-color: #28a745;
}
.list-view li:hover span {
width: 40px;
opacity: 1;
}
.hidden {
display: none;
}
.correct-answer-active {
background-color: rgba(42, 176, 49, 0.45);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="qa-form">
<input type="text" class="qa-input" placeholder="Enter text">
<button type="button" class="qa-button" id="btn-add">+</button>
<button type="button" class="qa-button hidden" id="btn-save">Save</button>
</form>
<div class="item-list"></div>

To Do List Delete Button within HTML <li> element

I am trying to get a delete button working on my To Do List project. I have tried a lot of different things but I am not having any luck. I believe the issue stems from the fact that I am trying to reference a button in an HTML li tag that is created by Javascript/jQuery when a user enters a new task in the To Do List. I probably am messing up the syntax relation between the two. Any help would be greatly appreciated. Thanks ahead of time.
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Project 4 - To Do List</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="page">
<h1 id="header"></h1>
<h2>To Do List <span id="counter"></span></h2>
<h3>"If you can dream it, you can do it" - Walt Disney</h3>
<div id="newItemButton"><button href="#" id="showForm">New Entry</button></div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Enter goal" />
<input type="submit" id="add" value="Submit"/>
</form>
<ul>
<!--<li id="one">Exercise</li>
<li id="two">Study</li>
<li id="three">Practice a New Language</li>
<li id="four">Work on Personal Project</li>-->
</ul>
</div>
<div class="about">
<a id="link" href="x">About</a>
</div>
<script src="jquery-1.11.0.js"></script>
<script src="javascript_jquery.js"></script>
</body>
<footer>
<div id="footer">To do List Icons made by <a id="link" href="http://www.freepik.com" title="Freepik">Freepik</a> from <a id="link" href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a id="link" href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a>
</div>
<div id="footer">Trash Icons made by <a id="link" href="https://www.flaticon.com/authors/dave-gandy" title="Dave Gandy">Dave Gandy</a> from <a id="link" href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a> is licensed by <a id="link" href="http://creativecommons.org/licenses/by/3.0/" title="Creative Commons BY 3.0" target="_blank">CC 3.0 BY</a></div>
</footer>
</html>
Here is the Javascript/jQuery. The focus of my issue is on the Delete function at the bottom and probably the .append part under "Check as Complete."
/*eslint-env jquery*/
/* eslint-env browser */
$(document).ready(function() {
// SETUP
var $list, $newItemForm, $newItemButton;
var item = ''; // item is an empty string
$list = $('ul'); // Cache the unordered list
$newItemForm = $('#newItemForm'); // Cache form to add new items
$newItemButton = $('#newItemButton'); // Cache button to show form
// ITEM COUNTER
function updateCount() { // Create function to update counter
var items = $('li[class!=complete]').length; // Number of items in list
$('#counter').text(items); // Added into counter circle
}
updateCount(); // Call the function
// SETUP FORM FOR NEW ITEMS
$newItemButton.show(); // Show the button
$newItemForm.hide(); // Hide the form
$('#showForm').on('click', function() { // When click on add item button
$newItemButton.hide(); // Hide the button
$newItemForm.show(); // Show the form
});
// ADDING A NEW LIST ITEM
$newItemForm.on('submit', function(e) { // When a new item is submitted
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
$list.append('<li>' + text + '</li>'); // Add item to end of the list
$('input:text').val(''); // Empty the text input
updateCount(); // Update the count
});
//Check as Complete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete !== true) {
item = $this.text(); // Get the text from the list item
$this.remove(); // Remove the list item
$list // Add back to end of list as complete
.append('<li class=\"complete\">' + item + '<button type="button" class="trashbutton" src="/images/icon-trash.png" alt="Trash Icon"></button>' + '</li>')
.hide().fadeIn(300); // Hide it so it can be faded in
complete = true;
}
updateCount();
});
/*//Check as Incomplete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
item = $this.text();
$this.remove();
$list
.append('<li>' + item + '</li>')
.hide().fadeIn(300);
}
updateCount();
});*/
// Delete
$list.on('click', 'li', function() {
var $this = $(this);
var readyToDelete = $this.hasClass('trashbutton');
if(readyToDelete === true) {
$this.animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$this.remove();
});
}
updateCount;
});
});
Here is the CSS just in case.
#import url(http://fonts.googleapis.com/css?family=Oswald);
body {
background-color: whitesmoke;
font-family: 'Oswald', 'Futura', sans-serif;
margin: 0;
padding: 0;
}
#page {
background-color: black;
margin: 0 auto 0 auto;
position: relative;
text-align: center;
}
/* Responsive page rules at bottom of style sheet */
h1 {
background-image: url('/images/icon.png');
background-repeat: no-repeat;
background-position: center center;
text-align: center;
text-indent: -1000%;
height: 75px;
line-height: 75px;
width: 117px;
margin: auto auto auto auto;
padding: 30px 10px 20px 10px;
}
h2 {
color: #fff;
font-size: 24px;
font-weight: normal;
text-align: center;
text-transform: uppercase;
letter-spacing: .3em;
display: inline-block;
margin: 0 0 23px 0;
}
h2 span {
background-color: #fff;
color: green;
font-size: 12px;
text-align: center;
letter-spacing: 0;
display: inline-block;
position: relative;
border-radius: 50%;
top: -5px;
height: 22px;
width: 26px;
padding: 4px 0 0 0;
}
h3 {
color: white;
}
ul {
border:none;
padding: 0;
margin: 0;
}
li {
background-color: yellowgreen;
color: black;
border-top: 1px solid grey;
border-bottom: 1px solid grey;
font-size: 24px;
letter-spacing: .05em;
list-style-type: none;
text-shadow: 1px 1px 1px grey;
text-align: left;
height: 50px;
padding-left: 1em;
padding-top: 10px;
padding-right: 1em;
}
/* unvisited link */
#link:link {
color: yellowgreen;
}
/* visited link */
#link:visited {
color: green;
}
/* mouse over link */
#link:hover {
color: darkseagreen;
}
/* selected link */
#link:active {
color: forestgreen;
}
.about {
text-align: center;
}
#footer {
background:none;
color: black;
text-align: center;
}
.complete {
background-color: #999;
color: white;
border-top: 1px solid #666;
border-bottom: 1px solid #b0b0b0;
text-shadow: 2px 2px 1px #333;
}
.trashbutton {
background-image: url('/images/icon-trash.png');
background-position: center;
background-repeat: no-repeat;
background-size: 12px 12px;
margin: auto !important;
position: relative;
top: 35%;
transform: translateY(-50%);
}
/* FORM STYLES */
form {
padding: 0 20px 20px 20px;
}
input[type='text'], input[type='password'], textarea {
background-color: whitesmoke;
color: black;
font-size: 24px;
width: 96%;
padding: 4px 6px;
border: 1px solid #999;
border-radius: 8px;}
input[type='submit'], a.add, button, a.show {
background-color: yellowgreen;
color: black;
border-radius: 8px;
border: none;
padding: 8px 10px;
margin-top: 10px;
font-family: 'Oswald', 'Futura', sans-serif;
font-size: 18px;
text-shadow: 1px 1px 1px grey;
text-decoration: none;
text-transform: uppercase;}
input[type='submit'], button {
float: right;
}
input[type='submit']:hover {
background-color: green;
color: #fff;
cursor: pointer;
}
/* form example */
#newItemButton {
padding: 10px 20px 75px 20px;
display: none;
}
#newItemForm {
padding-top: 20px;
}
#itemDescription {
width: 325px;
}
#newItemForm input[type='submit'] {
margin-top: 0;
text-align: center;
}
/* Attributes example */
#group {
margin: 10px;
border: 2px solid #fff;
}
/* Small screen:mobile */
#media only screen and (max-width: 500px) {
body {
background-color: #403c3b;
}
#page {
max-width: 480px;
}
}
#media only screen and (min-width: 501px) and (max-width: 767px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media only screen and (min-width: 768px) and (max-width: 959px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
/* Larger screens act like a demo for the app */
#media only screen and (min-width: 960px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
h1{
background-image: url('/images/icon.png');
background-size: 100px 100px;
}
}
Some screenshots of what works so far. You can see the tasks as incomplete in green, completed in grey, and the trash button shows up when the task is grey.
When app first loads
One incomplete task and one complete task. Notice trash button that does not work.
NOTE: I should mention that, while heavily altered, the HTML and JS code is derived from an example from Jon Duckett's Javascript and jQuery book. This is my first time ever working with jQuery and the purpose of this assignment is to learn the basics.
Here is how you can get it working:
Change $list.on('click', 'li', function() { to $list.on('click', 'li > button', function() { (your list items doesn't have 'trashbutton' class).
Update code you use to delete element since after clicking on a button you have to delete parent element (li), not the button itself.
Take a look at this in action:
$(document).ready(function() {
// SETUP
var $list, $newItemForm, $newItemButton;
var item = ''; // item is an empty string
$list = $('ul'); // Cache the unordered list
$newItemForm = $('#newItemForm'); // Cache form to add new items
$newItemButton = $('#newItemButton'); // Cache button to show form
// ITEM COUNTER
function updateCount() { // Create function to update counter
var items = $('li[class!=complete]').length; // Number of items in list
$('#counter').text(items); // Added into counter circle
}
updateCount(); // Call the function
// SETUP FORM FOR NEW ITEMS
$newItemButton.show(); // Show the button
$newItemForm.hide(); // Hide the form
$('#showForm').on('click', function() { // When click on add item button
$newItemButton.hide(); // Hide the button
$newItemForm.show(); // Show the form
});
// ADDING A NEW LIST ITEM
$newItemForm.on('submit', function(e) { // When a new item is submitted
e.preventDefault(); // Prevent form being submitted
var text = $('input:text').val(); // Get value of text input
$list.append('<li>' + text + '</li>'); // Add item to end of the list
$('input:text').val(''); // Empty the text input
updateCount(); // Update the count
});
//Check as Complete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete !== true) {
item = $this.text(); // Get the text from the list item
$this.remove(); // Remove the list item
$list // Add back to end of list as complete
.append('<li class=\"complete\">' + item + '<button type="button" class="trashbutton" src="/images/icon-trash.png" alt="Trash Icon"></button>' + '</li>')
.hide().fadeIn(300); // Hide it so it can be faded in
complete = true;
}
updateCount();
});
/*//Check as Incomplete
$list.on('click', 'li', function() {
var $this = $(this);
var complete = $this.hasClass('complete');
if (complete === true) {
item = $this.text();
$this.remove();
$list
.append('<li>' + item + '</li>')
.hide().fadeIn(300);
}
updateCount();
});*/
// Delete
$list.on('click', 'li > button', function() {
var $this = $(this);
var readyToDelete = $this.hasClass('trashbutton');
if(readyToDelete === true) {
$this.parent().animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$(this).remove();
});
}
updateCount;
});
});
#import url(http://fonts.googleapis.com/css?family=Oswald);
body {
background-color: whitesmoke;
font-family: 'Oswald', 'Futura', sans-serif;
margin: 0;
padding: 0;
}
#page {
background-color: black;
margin: 0 auto 0 auto;
position: relative;
text-align: center;
}
/* Responsive page rules at bottom of style sheet */
h1 {
background-image: url('/images/icon.png');
background-repeat: no-repeat;
background-position: center center;
text-align: center;
text-indent: -1000%;
height: 75px;
line-height: 75px;
width: 117px;
margin: auto auto auto auto;
padding: 30px 10px 20px 10px;
}
h2 {
color: #fff;
font-size: 24px;
font-weight: normal;
text-align: center;
text-transform: uppercase;
letter-spacing: .3em;
display: inline-block;
margin: 0 0 23px 0;
}
h2 span {
background-color: #fff;
color: green;
font-size: 12px;
text-align: center;
letter-spacing: 0;
display: inline-block;
position: relative;
border-radius: 50%;
top: -5px;
height: 22px;
width: 26px;
padding: 4px 0 0 0;
}
h3 {
color: white;
}
ul {
border:none;
padding: 0;
margin: 0;
}
li {
background-color: yellowgreen;
color: black;
border-top: 1px solid grey;
border-bottom: 1px solid grey;
font-size: 24px;
letter-spacing: .05em;
list-style-type: none;
text-shadow: 1px 1px 1px grey;
text-align: left;
height: 50px;
padding-left: 1em;
padding-top: 10px;
padding-right: 1em;
}
/* unvisited link */
#link:link {
color: yellowgreen;
}
/* visited link */
#link:visited {
color: green;
}
/* mouse over link */
#link:hover {
color: darkseagreen;
}
/* selected link */
#link:active {
color: forestgreen;
}
.about {
text-align: center;
}
#footer {
background:none;
color: black;
text-align: center;
}
.complete {
background-color: #999;
color: white;
border-top: 1px solid #666;
border-bottom: 1px solid #b0b0b0;
text-shadow: 2px 2px 1px #333;
}
.trashbutton {
background-image: url('/images/icon-trash.png');
background-position: center;
background-repeat: no-repeat;
background-size: 12px 12px;
margin: auto !important;
position: relative;
top: 35%;
transform: translateY(-50%);
}
/* FORM STYLES */
form {
padding: 0 20px 20px 20px;
}
input[type='text'], input[type='password'], textarea {
background-color: whitesmoke;
color: black;
font-size: 24px;
width: 96%;
padding: 4px 6px;
border: 1px solid #999;
border-radius: 8px;}
input[type='submit'], a.add, button, a.show {
background-color: yellowgreen;
color: black;
border-radius: 8px;
border: none;
padding: 8px 10px;
margin-top: 10px;
font-family: 'Oswald', 'Futura', sans-serif;
font-size: 18px;
text-shadow: 1px 1px 1px grey;
text-decoration: none;
text-transform: uppercase;}
input[type='submit'], button {
float: right;
}
input[type='submit']:hover {
background-color: green;
color: #fff;
cursor: pointer;
}
/* form example */
#newItemButton {
padding: 10px 20px 75px 20px;
display: none;
}
#newItemForm {
padding-top: 20px;
}
#itemDescription {
width: 325px;
}
#newItemForm input[type='submit'] {
margin-top: 0;
text-align: center;
}
/* Attributes example */
#group {
margin: 10px;
border: 2px solid #fff;
}
/* Small screen:mobile */
#media only screen and (max-width: 500px) {
body {
background-color: #403c3b;
}
#page {
max-width: 480px;
}
}
#media only screen and (min-width: 501px) and (max-width: 767px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media only screen and (min-width: 768px) and (max-width: 959px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
/* Larger screens act like a demo for the app */
#media only screen and (min-width: 960px) {
#page {
max-width: 480px;
margin: 20px auto 20px auto;
}
}
#media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
h1{
background-image: url('/images/icon.png');
background-size: 100px 100px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="page">
<h1 id="header"></h1>
<h2>To Do List <span id="counter"></span></h2>
<h3>"If you can dream it, you can do it" - Walt Disney</h3>
<div id="newItemButton"><button href="#" id="showForm">New Entry</button></div>
<form id="newItemForm">
<input type="text" id="itemDescription" placeholder="Enter goal" />
<input type="submit" id="add" value="Submit"/>
</form>
<ul>
<!--<li id="one">Exercise</li>
<li id="two">Study</li>
<li id="three">Practice a New Language</li>
<li id="four">Work on Personal Project</li>-->
</ul>
</div>
<div class="about">
<a id="link" href="x">About</a>
</div>
<script src="jquery-1.11.0.js"></script>
<script src="javascript_jquery.js"></script>
It would be easier for you to accomplish your task by giving the trashbutton class a click event to remove its parent li from the list. This can be accomplished with the following code.
// Delete
$('.trashbutton').click(function (e) {
e.preventDefault();
$(this).parent().animate({
opacity: 0.0,
paddingLeft: '+=180'
}, 500, 'swing', function() {
$(this).parent().remove();
});
}
updateCount();
})

Add checkbox to price calculation

Currently my price output gets calculated based on the chosen quantity of an input field. I have been trying to add a checkbox to this calculation that, if checked, adds $5 to the total price. That being said, I haven't been very successful. In my understanding, there are two calculations going on:
I hit the increase/decrease button and it checks if the checkbox has been selected
I select the checkbox and it calculates the total price
This is the code I have so far:
function IncludePrice()
{
var IncludePrice=0;
var include = theForm.elements["include"];
if(include.checked==true)
{
IncludePrice=5;
}
return IncludePrice;
}
$(".incr-btn_mobile").on("click", function(e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
var cakePrice = newVal;
var includep = IncludePrice();
var divobj = document.getElementById($button.attr('data-target'));
divobj.style.display = 'block';
divobj.innerHTML = "= $" + (cakePrice) * 7.99 + (includep);
e.preventDefault();
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>
UPDATE:
I changed made some changes based on the feedback here, but this seems to break the increase/decrease field. Here is the code as is:
$(".incr-btn_mobile").on("click", function(e) {
var $button = $(this);
var oldValue = $button.parent().find('.quantity').val();
$button.parent().find('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
if ($button.data('action') == "increase") {
var newVal = parseFloat(oldValue) + 1;
} else {
// Don't allow decrementing below 1
if (oldValue > 1) {
var newVal = parseFloat(oldValue) - 1;
} else {
newVal = 1;
$button.addClass('inactive');
}
}
$button.parent().find('.quantity').val(newVal);
var cakePrice = newVal;
var includep = theForm.elements.include.checked * 5;
var divobj = document.getElementById($button.attr('data-target'));
divobj.style.display = 'block';
divobj.innerHTML = "= $" + (cakePrice) * 7.99 + (includep);
e.preventDefault();
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>
There you go my friend. I only change your js code. There is all the change I made:
Deleted your IncludePrice function since you could do it in only one row. And do never user function name for a variable. It could possibly break your code.
All switched for jQuery use instead of half jQuery and native JS.
Created a function for checkbox onclick to change the prince dynamicly.
I changed the names of your variables to make them more specific.
Added some comments to make the code clearer.
var _EXTRAVAL = 5;
$(".incr-btn_mobile").on("click", function(e) {
// Prevent default action
e.preventDefault();
// Set variable for the method
var button = $(this);
var labelNb = button.parent().find('.quantity');
var labelPrice = $("#" + button.attr('data-target'));
var currentNb = button.parent().find('.quantity').val();
var newNb = 0;
// Remove 'inactive' class
$('.incr-btn_mobile[data-action="decrease"]').removeClass('inactive');
// Increase or decrease
if (button.attr('data-action') == "increase") {
newNb = parseFloat(currentNb) + 1;
} else {
// Don't allow decrementing below 1
if (currentNb > 1) {
newNb = parseFloat(currentNb) - 1;
} else {
newNb = 1;
button.addClass('inactive');
}
}
var isExtra = $("#include").prop('checked') ? _EXTRAVAL : 0;
$(labelNb).val(newNb);
$(labelPrice).css('display', 'block').html("= $" + String((((newNb) * 7.99) + (isExtra)).toFixed(2)));
});
$("#include").on('click', function(){
// Set variable for method
var checkbox = $(this);
var labelPrice = $("#" + $(".incr-btn_mobile").attr('data-target'));
var labelPriceFloat = parseFloat(labelPrice.html().substring(4));
// If checkbox is check, increse price
if (checkbox.prop('checked')) {
labelPrice.html("= $" + String((labelPriceFloat + _EXTRAVAL).toFixed(2)));
} else {
labelPrice.html("= $" + String((labelPriceFloat - _EXTRAVAL).toFixed(2)));
}
});
.bg {
width: 100%;
}
.column {
float: left;
width: 50%;
padding: 10px;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
.count-input_mobile {
position: relative;
max-width: 1000%;
max-width: 400px;
margin-top: 10px;
text-align: center;
}
.count-input_mobile input {
width: 100%;
height: 42px;
border: 1px solid #000
border-radius: 2px;
background: none;
text-align: center;
}
.count-input_mobile input:focus {
outline: none;
}
.count-input_mobile .incr-btn_mobile {
display: block;
position: absolute;
width: 30px;
height: 30px;
font-size: 26px;
font-weight: 300;
text-align: center;
line-height: 30px;
top: 50%;
right: 0;
margin-top: -15px;
text-decoration:none;
}
.count-input_mobile .incr-btn_mobile:first-child {
right: auto;
left: 0;
top: 46%;
}
.count-input_mobile.count-input-sm {
max-width: 125px;
}
.count-input_mobile.count-input-sm input {
height: 36px;
}
.count-input_mobile.count-input-lg {
max-width: 200px;
}
.count-input_mobile.count-input-lg input {
height: 70px;
border-radius: 3px;
}
.button_mobile {
border: 1px solid #000;
border-radius: 2px;
background: none;
padding: 10.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.sum_output {
background: none;
padding: 9.5px;
width:100%;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
margin-top:10px;
}
.accordion_img {
width:200%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<div class="count-input_mobile space-bottom">
<a class="incr-btn_mobile" data-action="decrease" data-target="cleanse_drop_1" href="#">–</a>
<input class="quantity" id="ShowButton_value_1" type="text" name="quantity" value="1"/>
<a class="incr-btn_mobile" data-action="increase" data-target="cleanse_drop_1" href="#">+</a>
</div>
<label for='include' class="inlinelabel">Include Extra? ($5)</label>
<input type="checkbox" id="include" name='include' data-target="cleanse_drop_1" />
<div id="cleanse_drop_1" class="sum_output">= $7.99</div>

How do I get a Country's info to appear from dropdown menu in Local Weather app?

I'm creating a Local Weather app and I created an dropdown menu in which you click on a location and the information such as City, Country, and temperature appears. However, I was unable to make the information appear every time I click on a location.
Here's my code.
As you can see, I was able to load the current location and temperature. What I did was to list global variables and call them in function getLocation() and run the info in function getWeather(). For the dropdown Menu, I made an array called mainCities and append the cities to dropdown menu in function testMenu(). In this function, I added onclick=testWeather('place'). For this one, I created another function called function testWeather(cityLocation) in which I again listed info for global variables and tried to run it again in function getWeather() but it's not working. What did I miss?
You can see my code in action at: http://codepen.io/kikibres/pen/EZMJZw
$(document).ready(function() {
var currentLat;
var currentLong;
var currentCity;
var currentRegion;
var currentCountry;
var mainCities = {
'San_Francisco': {
'region': 'California',
'country': "United States",
'lat': 37.7749300,
'lon': -122.4194200
},
'St._Louis': {
'region': 'Missouri',
'country': "United States",
'lat': 38.6272700,
'lon': -90.1978900
},
'Miami': {
'region': 'Florida',
'country': "United States",
'lat': 25.7742700,
'lon': -80.1936600
},
'Tokyo': {
'region': 'Tokyo',
'country': "Japan",
'lat': 35.689500,
'lon': 139.6917100
}
};
function testMenu() {
for (var place in mainCities) {
var city = place.replace(/_/g, ' ');
$('#testMenu').append("<li onclick=testWeather('" + place + "');><a href='#'>" + city + "</a></li>");
}
};
function testWeather(cityLocation) {
currentLat = testLocation[cityLocation].lat;
currentLong = testLocation[cityLocation].lon;
currentRegion = testLocation[cityLocation].region;
currentCity = testLocation[cityLocation];
currentCountry = testLocation[cityLocation].country;
getWeather();
};
function getLocation() {
$.getJSON('http://ip-api.com/json/?callback=?', function(data) {
currentRegion = data.regionName;
currentCity = data.city;
currentCountry = data.country;
currentLat = data.lat;
currentLong = data.lon;
//$("#cityname").text(currentCity);
getWeather();
});
};
function getWeather() {
$("#cityname").text(currentCity);
$("#state").text(currentRegion);
$("#country").text(currentCountry);
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + currentLat + '&lon=' + currentLong + '&units=imperial&APPID=e656b9ee098cf2341fcfdb365b96b4a8', function(json) {
var showfahrenheit = true;
var tempfahrenheit = Math.round(json.main.temp);
var temcelcius = Math.round((tempfahrenheit - 32) * 5/9);
$("#temp").html(tempfahrenheit);
$('#unit-switch').on('click', function() {
if (showfahrenheit === false) {
$("#temp").html(tempfahrenheit);
showfahrenheit = true;
} else {
$("#temp").html(temcelcius);
showfahrenheit = false;
}
$("#unit-toggle").toggleClass("toggle");
//$('#temp').toggleClass('toggle');
});
});
};
$(".cityarea").html(getLocation);
testMenu();
});
#import url('https://fonts.googleapis.com/css?family=Roboto:300,400');
body {
position: relative;
}
html,body{
height:100%;
}
.wrapper {
width: 100%;
height: 100%;
position: relative;
}
.container {
position: relative;
display: block;
margin: 0 auto;
width: 60%;
}
.header h1 {
text-align: center;
font-family: 'Roboto', sans-serif;
font-weight: normal;
margin: 0 0 10px 0;
}
.weatherbox {
text-align: center;
}
.cityarea h2 {
color: #000000;
font-family: 'Roboto', sans-serif;
font-weight: normal;
font-size: 2em;
margin: 0;
}
.countryarea {
position: relative;
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
margin: 0 auto;
}
.countryarea h3 {
margin: 0 0 10px 0;
font-family: 'Roboto', sans-serif;
font-weight: normal;
}
.countryarea h3:first-child {
margin-right: 8px;
}
.dropdown {
position: relative;
display: inline-block;
font-size: 16px;
color: #FFF;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #777;
white-space: nowrap;
text-transform: uppercase;
}
input[type=checkbox]{
display: none;
}
label{
box-sizing: border-box;
display: inline-block;
width: 100%;
background-color: #57A0D4;
padding: 10px 20px;
cursor: pointer;
text-align: center;
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
border-radius: 5px;
font-size: 20px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
label .fa-globe {
margin-right: 10px;
}
/* The ul will have display:none by default */
ul{
position: absolute;
list-style: none;
text-align: left;
width: 100%;
min-width: 160px;
z-index: 1;
padding: 5px 0;
margin: 2px 0 0;
font-size: 14px;
text-align: left;
box-shadow: 0px 1px 1px rgba(0, 0, 0, 0.2);
display: none;
background-color: #fff;
border: 1px solid #ccc;
border: 1px solid rgba(0,0,0,.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0,0,0,.175);
box-shadow: 0 6px 12px rgba(0,0,0,.175);
}
ul li{
/*padding: 15px;*/
background-color: #fff;
color: #4FB9A7;
margin-bottom: 1px;
cursor: pointer;
}
ul li a {
padding: 8px 20px;
color: inherit;
text-decoration: none;
display: block;
}
ul li a:hover{
background-color: #4FB9A7;
color: #FFF;
}
input[type=checkbox]:checked ~ label {
background-color: #3D88BD;
}
input[type=checkbox]:checked ~ ul {
display: block;
}
ul .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.temperaturearea span#temp {
position: relative;
color: #000000;
font-size: 80px;
}
.temperaturearea #temp:after {
content: '';
position: absolute;
height: 10px;
width: 10px;
top: 16px;
right: -17px;
border: 3px solid #000000;
border-radius: 50%;
}
.weather > span {
position: relative;
font-size: 1.2rem;
}
.weather > span:before {
content: '';
position: absolute;
left: -10px;
top: 0px;
height: 3px;
width: 3px;
border: 2px solid #000;
border-radius: 50%;
}
.main-toggle span {
margin: 0 0 0 16px;
}
.main-toggle span:last-child {
margin-left: 11px;
}
.weather button {
background: #6bbf6b;
border: none;
border-radius: 30px;
outline: none;
width: 45px;
height: 20px;
margin: 5px 5px 0;
cursor: pointer;
position: relative;
transition: background .2s;
}
.weather button:active {
background: #67b567;
}
.weather #unit-toggle {
position: absolute;
display: inline-block;
left: -8px;
top: 2px;
width: 15px;
height: 15px;
background: #fff;
border-radius: 50%;
transition: left .2s;
}
#unit-toggle.toggle {
left: 16px;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
<div class="container">
<div class="header"><h1>Local Weather</h1></div>
<div class="weatherbox">
<div class="cityarea">
<h2 id="cityname"></h2>
</div>
<div class="countryarea">
<h3 id="state"></h3>
<h3 id="country"></h3>
</div>
<div class="dropdownlocation">
<div class="dropdown">
<input type="checkbox" id="checkbox-toggle">
<label for="checkbox-toggle"><i class="fa fa-globe" aria-hidden="true"></i><i class="fa fa-caret-down" aria-hidden="true"></i></label>
<ul id="testMenu">
<li>Current Location</li>
<li class="divider"></li>
<li class="dropdown-header">Main Cities</li>
</ul>
</div>
</div>
<div class="temperaturearea">
<div>
<span id="wicon"></span>
</div>
<div id="wdescription"></div>
<span id="temp"></span>
<div class="weather main-toggle"> <!-- Begin Unit Switch -->
<span>F</span>
<button id="unit-switch"><span id="unit-toggle"></span></button>
<span>C</span>
</div>
</div>
</div>
</div>
</div>
There are couple of issues with the code, since you have defined all your functions and variable inside document.ready you can't access any of those functions and variable outside document.ready. That's why when you call 'testWeather' on onclick li, it throws an 'testWeather' is not defined. To solve this(you should make your variables and function global) you should define all you variable outside the document.ready. Just keep only below two lines of code inside document.ready.
$(".cityarea").html(getLocation);
testMenu();
But this will just solve 'testWeather' is not defined issue, and there is onre more issue in your code, inside testWeatherfunction there, you are using one property called testLocation, which is not defined, so you will get a JavaScript error here. You have saved your test locations in mainCities variable so you should use mainCities instead of testLocation. These two changes will make your app works without any error. Here is corrected JavaScript code. There is one more minor error your code, the way you are reading current city is not right.
$(document).ready(function () {
$(".cityarea").html(getLocation);
testMenu();
});
var currentLat;
var currentLong;
var currentCity;
var currentRegion;
var currentCountry;
var mainCities = {
'San_Francisco': {
'region': 'California',
'country': "United States",
'lat': 37.7749300,
'lon': -122.4194200
},
'St._Louis': {
'region': 'Missouri',
'country': "United States",
'lat': 38.6272700,
'lon': -90.1978900
},
'Miami': {
'region': 'Florida',
'country': "United States",
'lat': 25.7742700,
'lon': -80.1936600
},
'Tokyo': {
'region': 'Tokyo',
'country': "Japan",
'lat': 35.689500,
'lon': 139.6917100
}
};
function testMenu() {
for (var place in mainCities) {
var city = place.replace(/_/g, ' ');
$('#testMenu').append("<li onclick=testWeather('" + place + "');><a href='#'>" + city + "</a></li>");
}
};
function testWeather(cityLocation) {
currentLat = mainCities[cityLocation].lat;
currentLong = mainCities[cityLocation].lon;
currentRegion = mainCities[cityLocation].region;
currentCity = mainCities[cityLocation];
currentCountry = mainCities[cityLocation].country;
getWeather();
};
function getLocation() {
$.getJSON('http://ip-api.com/json/?callback=?', function (data) {
currentRegion = data.regionName;
currentCity = data.city;
currentCountry = data.country;
currentLat = data.lat;
currentLong = data.lon;
//$("#cityname").text(currentCity);
getWeather();
});
};
function getWeather() {
$("#cityname").text(currentCity);
$("#state").text(currentRegion);
$("#country").text(currentCountry);
$.getJSON('http://api.openweathermap.org/data/2.5/weather?lat=' + currentLat + '&lon=' + currentLong + '&units=imperial&APPID=e656b9ee098cf2341fcfdb365b96b4a8', function (json) {
var showfahrenheit = true;
var tempfahrenheit = Math.round(json.main.temp);
var temcelcius = Math.round((tempfahrenheit - 32) * 5 / 9);
$("#temp").html(tempfahrenheit);
$('#unit-switch').on('click', function () {
if (showfahrenheit === false) {
$("#temp").html(tempfahrenheit);
showfahrenheit = true;
} else {
$("#temp").html(temcelcius);
showfahrenheit = false;
}
$("#unit-toggle").toggleClass("toggle");
//$('#temp').toggleClass('toggle');
});
});
};

Categories

Resources