I'm working on the freeCodeCamp "Show the local weather" project. I have almost everything working except I cannot seem to get the switch to toggle between Fahrenheit and Celsius to work properly. It's a very basic page for showing the weather and I want the user to be able to switch between Fahrenheit and Celsius by clicking on the tags and then the page will update with the new temperature. Currently, when I click on the 'C' tag it will display the correct temperature for a brief moment, but then quickly switch back to Fahrenheit. Any help would be greatly appreciated. Here is the link to the page: https://codepen.io/spencerj171/full/yzmmvR/
Thanks to everyone in advance!
HTML
<body>
<div class="container weather">
<div id="location"></div>
<div class="row">
<div class="col-lg-6">
<br><br>
<span class="ftemp" id="currentTemp"></span>
<span id="forc"> F | C</span>
<div>
<span id="icon"></span>
<span id="description"></span>
</div>
<span class="ftemp" id="lowTemp"></span>
<span class="ftemp" id="highTemp"></span>
<div id="humidity"></div>
</div>
<div class="col-lg-6">
<div id="map"></div>
</div>
</div>
</body>
CSS
body{
background-color: rgb(152, 157, 165);
color: black;
}
.switch{
border: none;
background-color: rgb(255, 255, 255);
text-decoration: none;
}
.weather{
text-align: center;
margin-top: 100px;
background-color: rgb(255, 255, 255);
border-radius: 5px;
padding: 50px 50px 50px 50px;
width: 50%;
height: auto;
position: relative;
}
#location{
font-size: 2em;
padding-bottom: .5em;
}
#currentTemp{
font-size: 1.5em;
display: inline-block;
}
#forc{
color: black;
display: inline-block;
font-size: 1em;
}
#icon{
width: 100%;
height: auto;
}
#description{
display: inline-block;
}
#lowTemp{
display: inline-block;
padding-right: 10px;
}
#highTemp{
display: inline-block;
}
#humidity{
}
#map{
width: 100%;;
height: 300px;
margin: auto;
}
a.switch{
text-decoration: none;
color: black;
}
a:hover{
color: rgb(0, 182, 255);
}
JavaScript
var url = "https://api.openweathermap.org/data/2.5/weather?q=cleveland&appid=d32fada3b37530ca403693700ae6c134";
var gurl = "https://maps.googleapis.com/maps/api/js?key=AIzaSyCrBes2R9nOEvbMHMoJ4oCTzSNGaOD6eQc&callback=initMap";
var degree = '<span id="forc"> F | C</span>';
var apiOpen = "d32fada3b37530ca403693700ae6c134";
var map;
var tempSwitch = false;
$(document).ready(function(){
getLocation();
});
//Get location of user
function getLocation(){
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
getWeather();
initMap();
});
} else{
alert("Please allow location services.")
}
}
//Retrieve weather
function getWeather(){
data = $.ajax({
type: "GET",
url: url,
dataType: 'jsonp',
success: function(json){
current = fahrenheit(json.main.temp);
low = fahrenheit(json.main.temp_min);
high = fahrenheit(json.main.temp_max);
$("#location").html("<div id='location'>" + json.name + " Weather</div>");
$("#currentTemp").html("<span class='ftemp' id='currentTemp'>" + current + "°" + "</span>");
$("#icon").html("<span id='icon'><img src='https://openweathermap.org/img/w/" + json.weather[0].icon + ".png'></span>");
$("#description").html("<span id='description'>" + json.weather[0].description.toUpperCase()) +"</span>";
$("#lowTemp").html("<span class='ftemp' id='lowTemp'>↓ " + low + "° " + "</span>");
$("#highTemp").html("<span class='ftemp' id='highTemp'>↑ " + high + "° " + "</span>");
$("#humidity").html("<div id='humidity'>Humidity: " + json.main.humidity + "%</div>");
}
});
switchTemp();
}
//Create Map
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 41.505493, lng: -81.681290},
zoom: 10
});
}
//Convert temperature
function fahrenheit(kel){
var f = Math.floor(9/5 * (kel - 273) + 32);
return f;
}
function fahr(c){
var fahr = Math.floor( c * 1.8 + 32);
return fahr;
}
function celsius(f){
var c = Math.floor((f - 32) * 5/9);
return c;
}
//Switch temperature
function switchTemp(){
$("#c").on("click", function(){
if(tempSwitch === false){
$("#currentTemp").html("<span id='currentTemp'>" + celsius(current) + "°" + "</span>");
$("#lowTemp").html("<span id='lowTemp'>↓ " + celsius(low) + "° " + "</span>");
$("#highTemp").html("<spanid='highTemp'>↑ " + celsius(high) + "° " + "</span>");
tempSwitch === true;
}
});
$("#f").on("click", function(){
if(tempSwitch === true){
$("#currentTemp").html("<span id='currentTemp'>" + fahr(current) + "°" + "</span>");
$("#lowTemp").html("<span id='lowTemp'>↓ " + fahr(low) + "° " + "</span>");
$("#highTemp").html("<spanid='highTemp'>↑ " + fahr(high) + "° " + "</span>");
tempSwitch === false;
}
});
}
There was 2 problems in your code:
You C and F is a link, so when you click it makes a page refress since you have nothing in href="". either use href="#" or e.preventDefault(); as in the example just below:
$("#f").on("click", function(e){
e.preventDefault();
});
You use === to set tempSwitch as in tempSwitch === false but you need to use only one = as in tempSwitch = false
DEMO
Related
I am trying to implement Lokesh Dhakar's "Color Thief" library.
The expected outcome is to display dominant color and color palette immediately after upload.
My assumption is that there is going something wrong in the following part of the code:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.getElementById('image_0');
img.src = URL.createObjectURL(this.files[0]); // set src to file url
extractColors(img.id);
}
});
});
When I end up at dcolor = colorThief.getColor(document.getElementById(image));, the "Uncaught TypeError" occurs.
See my effort below:
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>Based on "Color Thief" by Lokesh Dhakar</title>
<meta name="description" content="Get the dominant color or color palette from an image.">
<meta name="viewport" content="width=device-width,initial-scale=1">
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Karla%7CMontserrat:700">
<style>
element.style {
}
.image-section {
margin-bottom: 80px;
}
div {
display: block;
}
.image-wrap {
position: relative;
line-height: 1em;
min-height: 240px;
background-color: var(--hover-bg-color);
border-radius: var(--border-radius-xl);
}
.run-functions-button {
position: absolute;
top: 50%;
left: 10%;
width: 8rem;
height: 8rem;
margin-top: -4rem;
margin-left: -4rem;
border: none;
border-radius: 50%;
color: var(--link-color);
background-color: white;
border: 4px solid var(--link-color);
font-size: 2rem;
font-weight: var(--bold);
cursor: pointer;
text-transform: uppercase;
outline: none;
}
.no-touch-label {
display: inline;
}
.touch-label {
display: none;
}
.target-image {
border-radius: var(--border-radius-xl);
transition: border-radius 0.2s 0.3s;
}
.target-image {
display: block;
width: 20%;
border-radius: var(--border-radius-xl) var(--border-radius-xl) 0 0;
}
.dswatch {
width: 3rem;
height: 3rem;
}
.swatchp {
width: 3rem;
height: 3rem;
}
.dswatch {
display: inline-block;
background: #d3d3d3;
border-color: #000;
border-radius: 32px;
border-radius-large: 8px;
border-radius-xl: 12px;
}
.swatchp {
display: inline-block;
background: #d3d3d3;
border-color: #000;
border-radius: 32px;
border-radius-large: 8px;
border-radius-xl: 12px;
}
</style>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.umd.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/color-thief/2.3.0/color-thief.min.js"></script>
<script>
var dcolor;
var colorp;
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (this.files && this.files[0]) {
var img = document.getElementById('image_0');
img.src = URL.createObjectURL(this.files[0]); // set src to file url
extractColors(img.id);
}
});
});
function extractColors(image){
colorThief = new ColorThief();
dcolor = colorThief.getColor(document.getElementById(image)); // error!
document.getElementById('dswatch_0').style.backgroundColor = 'rgb(' + dcolor[0] + ',' + dcolor[1] + ',' + dcolor[2] + ')';
colorp = colorThief.getPalette(document.getElementById(image), 8);
document.getElementById('swatchp_0').style.backgroundColor = 'rgb(' + colorp[0][0] + ',' + colorp[0][1] + ',' + colorp[0][2] + ')';
document.getElementById('swatchp_1').style.backgroundColor = 'rgb(' + colorp[1][0] + ',' + colorp[1][1] + ',' + colorp[1][2] + ')';
document.getElementById('swatchp_2').style.backgroundColor = 'rgb(' + colorp[2][0] + ',' + colorp[2][1] + ',' + colorp[2][2] + ')';
document.getElementById('swatchp_3').style.backgroundColor = 'rgb(' + colorp[3][0] + ',' + colorp[3][1] + ',' + colorp[3][2] + ')';
document.getElementById('swatchp_4').style.backgroundColor = 'rgb(' + colorp[4][0] + ',' + colorp[4][1] + ',' + colorp[4][2] + ')';
document.getElementById('swatchp_5').style.backgroundColor = 'rgb(' + colorp[5][0] + ',' + colorp[5][1] + ',' + colorp[5][2] + ')';
document.getElementById('swatchp_6').style.backgroundColor = 'rgb(' + colorp[6][0] + ',' + colorp[6][1] + ',' + colorp[6][2] + ')';
document.getElementById('swatchp_7').style.backgroundColor = 'rgb(' + colorp[7][0] + ',' + colorp[7][1] + ',' + colorp[7][2] + ')';
}
</script>
<div class="image-section ">
<div class="image-wrap"><input type='file' /><br><img class="target-image" id="image_0" alt="image_0" src="#"></div>
<div class="swatches">
<h6>Dominant color:</h6>
<div class="dswatch" id="dswatch_0"></div>
<h6>Color palette:</h6>
<div class="swatchp" id="swatchp_0"></div>
<div class="swatchp" id="swatchp_1"></div>
<div class="swatchp" id="swatchp_2"></div>
<div class="swatchp" id="swatchp_3"></div>
<div class="swatchp" id="swatchp_4"></div>
<div class="swatchp" id="swatchp_5"></div>
<div class="swatchp" id="swatchp_6"></div>
<div class="swatchp" id="swatchp_7"></div>
</div>
</div>
</body>
</html>
I was able to come up with a solution to my problem. See hereafter for the code snippet that should replace window.addEventListener('load', function() { ... }:
window.addEventListener('load', function() {
document.querySelector('input[type="file"]').addEventListener('change', function() {
if (document.querySelector('input[type="file"]').files[0]) {
var img = document.getElementById('image_0');
img.id = document.getElementById('image_0').id;
var reader = new FileReader();
reader.readAsDataURL(document.querySelector('input[type="file"]').files[0]);
reader.onload = async function () {
await getResult();
function getResult(){
img.src = reader.result;
}
extractColors(img.id);
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
}
});
I cannot get it to just display one at a time. It has to do a full cycle before it displays just one paragraph. Pulling my hair out.
$(function(){
setInterval(function(){$('.forumFeed > :first-child').fadeOut(3000).next('p').delay(3000).fadeIn(1000).end().appendTo('.forumFeed');}, 5000);
});
https://codepen.io/capseaslug/pen/yqyBXB
Hide all but the first paragraph tag by default. Inside the setInterval hide the one that is showing and display the next one (controlled by an index variable).
To make the items fade in/out nicely you can fade in the next element after the visible one is finished hiding.
Added some variables at the top to play with the aesthetics / number of items looped through.
SO didn't have moment.js so I hard coded some string. Codepen for a working version.
var numberOfItems = 10;
var flipSpeed = 2000;
var fadeOutSpeed = 500;
var fadeInSpeed = 200;
(function(c){
var uniquename = 'rssfeed' // id of target div
var query = 'select * from rss(0,' + numberOfItems + ') where url = "https://forums.mankindreborn.com/f/-/index.rss"'; // RSS Target, 0,5 signifies number of entries to show
var numretries = 1; // increase this number (number of retries) if you're still having problems
//////// No Need To Edit Beyond Here Unless You Want To /////////
var counter = typeof c === 'number'? c : numretries;
var thisf = arguments.callee;
var head = document.getElementsByTagName('head')[0];
var s = document.createElement('script');
window["callback_" + uniquename + (--counter)] = function(r){
head.removeChild(s);
if(r && r.query && r.query.count === 0 && counter > 0){
return thisf(counter);
}
//r now contains the result of the YQL Query as a JSON
var feedmarkup = '';
var feed = r.query.results.item // get feed as array of entries
for (var i=0; i<feed.length; i++) {
feedmarkup += '<p><span class="firstrowwrap"><a href="' + feed[i].link + '">';
feedmarkup += feed[i].title + '</a> <span class="comments"> Replies: ';
feedmarkup += feed[i].comments + ' </span></span><span class="secondRow"> <i class="fas fa-feather-alt"></i> ' ;
feedmarkup += feed[i].creator + ' <span class="posttime"> Last Post: ';
//pubishdate since
publishDate = feed[i].pubDate;
var inDate = publishDate;
var publisheddate = new Date(inDate);
feedmarkup += 'moment.js is missing ' + '</span></span></p>';
//endpublishdate since
}
document.getElementById(uniquename).innerHTML = feedmarkup;
};
var baseurl = "https://query.yahooapis.com/v1/public/yql?q=";
s.src = baseurl + encodeURIComponent(query) + "&format=json&callback=callback_" + uniquename + counter;
head.append(s);
})();
$(function(){
var index = 0;
setInterval(function() {
$('#rssfeed>p:visible').fadeOut(fadeOutSpeed, ()=> {
$('#rssfeed>p').eq(index).fadeIn(fadeInSpeed);
});
index++;
if(index === $('#rssfeed>p').length){
index = 0;
}
}, flipSpeed);
});
#main-container {
padding:4em;
background: #333;
font-family: 'exo'
}
#rssfeed p:not(:first-child) {
display: none;
}
a{
font-weight:
500;
color: #68ddda;
}
a:hover{
color: #4ca7a4;
}
.firstrowwrap{
display: flex;
justify-content: space-between;
}
.secondRow{
display: block;
padding-top: 4px;
margin-bottom: -5px;
}
#rssfeed p{
background-color: #212121;
padding: 10px;
width: 400px;
margin-bottom: 2px;
color: #464646;
}
.comments{
height: 18px;
position: relative;
z-index: 1;
padding-left: 8px;
margin-left: 4px;
font-size: 12px;
}
.comments:after{
content: "";
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
background-color: #969696;
border-radius: 2px;
z-index: -1;
margin-left: 4px;
}
.posttime{
float: right;
font-size: 13px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container-fluid" id="main-container">
<div class="row">
<div class="col-md-12">
<div class="forumFeed" id="rssfeed"></div>
</div>
</div>
</div>
I have a function that is currently tied to a button. When clicking the button all the data I need works perfectly fine. However if I use Jquery to call that function on window load I am received undefined. From the searches I have done I think it has something to do with Async but that is over my head honestly. Here is what I have written:
var latitude;
var longitude;
var temperature;
var currentTemp;
function GetWeather() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", `https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`, true);
xhttp.onload = function (e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var response = JSON.parse(xhttp.responseText);
temperature = response.main.temp;
document.getElementById("city-text").innerHTML = "City: " + response.name;
document.getElementById("skies-text").innerHTML = "Skies: " + response.weather[0].main + " - " + response.weather[0].description;
document.getElementById("skies-icon").innerHTML = "<img src='" + response.weather[0].icon + "'>";
document.getElementById("temperature-text").innerHTML = "Temperature: " + temperature + "C";
document.getElementById("humidity-text").innerHTML = "Humidity: " + response.main.humidity;
} else {
console.error(xhttp.statusText);
}
}
};
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
};
navigator.geolocation.getCurrentPosition(function(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
});
$(function() {
GetWeather();
});
function TempConversion () {
return temperature === currentTemp ? currentTemp = temperature * 1.8 + 32 : currentTemp = temperature;
}
currentTemp = temperature;
* {
font-family: roboto;
}
ul {
list-style: none;
padding: 0;
}
.aligner {
display: flex;
align-items: center;
min-height: 95vh;
justify-content: center;
}
.main-container {
background-color: beige;
max-width: 50%;
flex: 1;
text-align: center;
}
.weather-info {
font-size: 1.5em;
font-weight: bold;
}
.weather-info li {
margin: 8px 0px;
}
#skies-icon {
margin: auto;
}
#weather-button {
font-size: 1em;
}
<!DOCTYPE html>
<html>
<head>
<link href="css/style.css" rel="stylesheet">
</head>
<body>
<div class="aligner">
<div class="main-container">
<h1>Weather in your area: </h1>
<div class="weather-info">
<ul>
<li id="skies-icon"></li>
<li id="temperature-text"></li>
<li id="city-text"></li>
<li id="skies-text"></li>
<li id="humidity-text"></li>
<li><button id="weather-button" onclick="GetWeather()">GET YOUR WEATHER</button></li>
</ul>
</div>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="javascript/script.js"></script>
</body>
</html>
Thank you in advanced for helping!
Your script worked fine for me. What I think is happening is that you are putting in bogus lat and long variables (need to do some input checking) this will return undefined for response.main and probably why you are getting undefined
I noticed the API will return response.error if there is one, so I suggest checking for that before you continue.
I would suggest adding some error handling like
if(response.error){
console.error(`OH NO! ${response.error}`);
return;
}
For example:
var temperature;
var currentTemp;
function GetWeather(latitude, longitude) {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", `https://fcc-weather-api.glitch.me/api/current?lat=${latitude}&lon=${longitude}`, true);
xhttp.onload = function(e) {
if (xhttp.readyState === 4) {
if (xhttp.status === 200) {
var response = JSON.parse(xhttp.responseText);
if (response.error) {
console.error(`OH NO! ${response.error}`);
return;
}
temperature = response.main.temp;
document.getElementById("city-text").innerHTML = "City: " + response.name;
document.getElementById("skies-text").innerHTML = "Skies: " + response.weather[0].main + " - " + response.weather[0].description;
document.getElementById("skies-icon").innerHTML = "<img src='" + response.weather[0].icon + "'>";
document.getElementById("temperature-text").innerHTML = "Temperature: " + temperature + "C";
document.getElementById("humidity-text").innerHTML = "Humidity: " + response.main.humidity;
} else {
console.error(xhttp.statusText);
}
}
};
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send();
};
$(function() {
navigator.geolocation.getCurrentPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
GetWeather(latitude, longitude);
});
});
function TempConversion() {
return temperature === currentTemp ? currentTemp = temperature * 1.8 + 32 : currentTemp = temperature;
}
currentTemp = temperature;
* {
font-family: roboto;
}
ul {
list-style: none;
padding: 0;
}
.aligner {
display: flex;
align-items: center;
min-height: 95vh;
justify-content: center;
}
.main-container {
background-color: beige;
max-width: 50%;
flex: 1;
text-align: center;
}
.weather-info {
font-size: 1.5em;
font-weight: bold;
}
.weather-info li {
margin: 8px 0px;
}
#skies-icon {
margin: auto;
}
#weather-button {
font-size: 1em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aligner">
<div class="main-container">
<h1>Weather in your area: </h1>
<div class="weather-info">
<ul>
<li id="skies-icon"></li>
<li id="temperature-text"></li>
<li id="city-text"></li>
<li id="skies-text"></li>
<li id="humidity-text"></li>
<li><button id="weather-button" onclick="GetWeather()">GET YOUR WEATHER</button></li>
</ul>
</div>
</div>
</div>
everyone. I am a jquery beginner and want to ask a few questions.
I am coding a simple math captcha for form submission test, I wanna generate a set of new random number each time when I press the "reset button".
But I when I google for the solution, most are trying to reload the page or reload the whole function, So I wanna ask if there is a way to do this.
And I would be very pleased if you guys can help me improving the codes as I think I am writing quite dummy. Thanks so much!!!
Please have a look at my code in fiddle :)
https://jsfiddle.net/v7bcjj1q/#&togetherjs=2nOVnkI34j
my code:
$(document).ready(function(){
$('button[type=submit]').attr('disabled','disabled');
var randomNum1;
var randomNum2;
//set the largeest number to display
var maxNum = 20;
var total;
randomNum1 = Math.ceil(Math.random()*maxNum);
randomNum2 = Math.ceil(Math.random()*maxNum);
total =randomNum1 + randomNum2;
$( "#question" ).prepend( randomNum1 + " + " + randomNum2 + "=" );
// When users input the value
$( "#ans" ).keyup(function() {
var input = $(this).val();
var slideSpeed = 200;
$('#message').hide();
if (input == total) {
$('button[type=submit]').removeAttr('disabled');
$('#success').slideDown(slideSpeed);
$('#fail').slideUp(slideSpeed);
}
else {
$('button[type=submit]').attr('disabled','disabled');
$('#fail').slideDown(slideSpeed);
$('#success').slideUp(slideSpeed);
}
});
// Wheen "reset button" click, generating new randomNum1 & randomNum2
});
For re-usability, a separate function can be used to generate the question
var total;
function getRandom(){return Math.ceil(Math.random()* 20);}
function createSum(){
var randomNum1 = getRandom(),
randomNum2 = getRandom();
total =randomNum1 + randomNum2;
$( "#question" ).text( randomNum1 + " + " + randomNum2 + "=" );
//in case of reset
$('#success, #fail').hide();
$('#message').show();
}
Inside the document load, the function can be called to initialize and subsequently attached to the click event
$(document).ready(function(){
$('button[type=submit]').attr('disabled','disabled');
//create initial sum
createSum();
// On "reset button" click, generate new random sum
$('button[type=reset]').click(createSum);
//....
One step further would be to set the visibility in a function that (re)checks the input on both keyup and reset.
Example fiddle
Just add an onClick event on the reset button
Inside you have to generate new numbers, total, clear question and clear input
$('button[type=submit]').attr('disabled', 'disabled');
var randomNum1;
var randomNum2;
//set the largeest number to display
var maxNum = 20;
var total;
randomNum1 = Math.ceil(Math.random() * maxNum);
randomNum2 = Math.ceil(Math.random() * maxNum);
total = randomNum1 + randomNum2;
$("#question").prepend(randomNum1 + " + " + randomNum2 + "=");
// When users input the value
$("#ans").keyup(function() {
var input = $(this).val();
var slideSpeed = 200;
$('#message').hide();
if (input == total) {
$('button[type=submit]').removeAttr('disabled');
$('#success').slideDown(slideSpeed);
$('#fail').slideUp(slideSpeed);
} else {
$('button[type=submit]').attr('disabled', 'disabled');
$('#fail').slideDown(slideSpeed);
$('#success').slideUp(slideSpeed);
}
});
// Wheen "reset button" click, generating new randomNum1 & randomNum2
$("#reset").on("click", function() {
randomNum1 = Math.ceil(Math.random() * maxNum);
randomNum2 = Math.ceil(Math.random() * maxNum);
total = randomNum1 + randomNum2;
$("#question").empty();
$("#ans").val('');
$("#question").prepend(randomNum1 + " + " + randomNum2 + "=");
});
* {
padding: 0;
margin: 0;
}
html,
body {
font-family: 'Open Sans';
font-weight: lighter;
font-size: 12px;
width: 100%;
height: 100%;
}
#success,
#fail {
display: none;
}
#message,
#success,
#fail {
margin-top: 10px;
margin-bottom: 10px;
}
.container {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
p {
display: inline;
margin-right: 5px;
}
input,
button {
font-family: 'Open Sans';
font-weight: lighter;
font-size: 12px;
}
input {
border: 1px solid #FFBBD7;
width: 30px;
height: 20px;
text-align: center;
}
button {
border: none;
border-radius: 1.5em;
color: #FFF;
background: #FFBBD7;
padding: 2.5px 10px;
width: 75px;
height: 30px;
cursor: pointer;
transition: background .5s ease-in-out;
}
button:hover:enabled {
background: #303030;
}
button:disabled {
opacity: .5;
cursor: default;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id="question"></p>
<input id="ans" type="text">
<div id="message">Please verify.</div>
<div id="success">Validation complete :)</div>
<div id="fail">Validation failed :(</div>
<button type="submit" value="submit">Submit</button>
<button type="reset" id="reset" value="reset">Reset</button>
You can do it like this, add this piece of code:
$('#reset').click(function(e){
randomNum1 = Math.ceil(Math.random()*maxNum);
randomNum2 = Math.ceil(Math.random()*maxNum);
total =randomNum1 + randomNum2;
$( "#question" ).html( randomNum1 + " + " + randomNum2 + "=" );
});
#reset is in this case your reset button. You should just give it that ID, or change the selection depending on what you like most.
On click, you'll reset the variables, and change the HTML from the question.
I did it by just duplicating the code, but you might want to create a single function for it, as you are using it multiple times.
We developing chat application in that I am showing image,audio and text in the content div.
we have header div,content div,footer div.In content div adding new data dynamically i want show in bottom every time. if want see previous data i want scroll down to see. how to do that using jquery
$(document)
.on(
"pagebeforeshow",
"#chat",
function() {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
onFileSystemSuccess, fail);
load = true;
$('#opchat').empty();
$("#preopchat").empty();
$("#opchat1").empty();
var checkData = storageChat.getItem("chatdata");
if (JSON.parse(checkData) != null
&& JSON.parse(checkData) != undefined) {
storeChatData = JSON.parse(checkData).slice();
if (storeChatData.length > 10) {
var sliceChatData = [];
sliceChatData = storeChatData.slice(Math.max(
storeChatData.length - 10, 1));
for (var i = 0; i < sliceChatData.length; i++) {
if (sliceChatData[i] != undefined) {
if (sliceChatData[i].startsWith("file:///")) {
var filepath = sliceChatData[i].split(",")
if (filepath[1] == 'image/jpeg') {
var storedChat = '<img class="popphoto" id="profImgDashBrd" style="height: 70px; width: 70px;" src=\''
+ sliceChatData[i]
+ '\' >';
previewData(storedChat);
} else if (filepath[1] == 'audio/mpeg') {
var storedChat = "<audio controls>"
+ "<source src='"
+ sliceChatData[i]
+ "' type='video/mp4'>"
+ "</audio>" + "<br>";
previewData(storedChat);
} else {
var filepath = storeChatData[i].split(",")
var storedChat ="<div class='right'>" + "<p>"
+ filepath[1] + "</p>" + "</div";
$("#opchat1").append(storedChat);
}
} else {
var storedChat ="<div class='left'>" + "<p>"
+ sliceChatData[i] + "</p>" + "</div>" + "<br>";
$("#opchat").append(storedChat);
}
}
}
} else {
for (var i = 0; i < storeChatData.length; i++) {
if (storeChatData[i] != undefined) {
if (storeChatData[i].startsWith("file:///")) {
var filepath = storeChatData[i].split(",")
if (filepath[1] == 'image/jpeg') {
var storedChat = '<img class="popphoto" style="height: 70px; width: 70px;" src=\''
+ filepath[0] + '\' >';
previewData(storedChat);
} else if (filepath[1] == 'audio/mpeg') {
var storedChat = "<audio controls>"
+ "<source src='"
+ filepath[0]
+ "' type='video/mp4'>"
+ "</audio>" + "<br>";
previewData(storedChat);
} else {
var filepath = storeChatData[i].split(",");
var storedChat ="<div class='right'>" + "<p>"
+ filepath[1] + "</p>" + "</div";
$("#opqicchat1").append(storedChat);
}
} else {
var storedChat ="<div class='left'>" + "<p>"
+ storeChatData[i] + "</p>" + "</div>" + "<br>"
$("#opqicchat").append(storedChat);
}
}
}
}
}
});
function onFileSystemSuccess(fileSystem) {
folderName = "QLM"
var directoryEntry = fileSystem.root;
directoryEntry.getDirectory(folderName, {
create : true,
exclusive : false
}, gotDirEntry, fail)
}
function gotDirEntry(dirEntry) {
dirEntry.getFile("newFile.txt", {
create : true,
exclusive : false
}, gotFileEntry, fail);
}
function gotFileEntry(fileEntry) {
return true;
}
function fail() {
alert("error code");
}
// Text ,audio and images Display in chat
function previewData(data) {
var storedChat ="<div class='right'>" + "<p>" + data + "</p>" + "</div>" + "<br>";
$("#opqicchat1").append(storedChat);
}
// Text enter and submit
$(document).on('click', '#btnchatsend', function() {
var txtareaId = "txtarchat";
var txtareaVal = $("#" + txtareaId).val();
if (txtareaVal != null && txtareaVal != undefined && txtareaVal != "") {
storeChatData.push("file:///" + "," + txtareaVal);
storageChat.setItem("chatdata", JSON.stringify(storeChatData));
previewData(txtareaVal)
}
$("#" + txtareaId).val("");
$(textarea).val("");
});
// record audio and store
function startRecord() {
navigator.device.capture.captureAudio(captureSuccess, captureError, {
limit : 1
});
}
function captureSuccess(e) {
var audiofile = e[0].localURL;
var audiofilePath = e[0].fullPath;
audioname = audiofile.substr(audiofile.lastIndexOf('/') + 1);
filename = Date.now().toString() + audioname;
window.resolveLocalFileSystemURL(audiofile, copyFilePath, fail);
}
function captureError(e) {
alert(JSON.stringify(e));
}
function playRecAudio(url) {
if (play == true)
audioRecord = new Media(url, onAudioSuccess, onAudioError);
if (play == true) {
audioRecord.play();
play = false;
} else {
audioRecord.pause();
play = true;
}
}
function onAudioSuccess() {
}
function onAudioError() {
}
// capture image from camera
function getCapImg(source) {
navigator.camera.getPicture(onSavedDocURISuccess, onFails, {
destinationType : navigator.camera.DestinationType.FILE_URI,
sourceType : source,
saveToPhotoAlbum : true
});
}
function imageGallery(source) {
navigator.camera.getPicture(onSavedDocURISuccess, onFail, {
quality : 30,
targetWidth : 600,
targetHeight : 600,
destinationType : destinationType.FILE_URI,
sourceType : source
});
}
function onSavedDocURISuccess(imageURI) {
filename = imageURI.substr(imageURI.lastIndexOf('/') + 1);
filename = Date.now().toString() + filename;
window.resolveLocalFileSystemURI(imageURI, copyFilePath, fail);
}
function copyFilePath(fileEntry) {
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory(folderName, {
create : true,
exclusive : false
}, function(dir) {
fileEntry.copyTo(dir, filename, onCopySuccess, fail);
}, fail);
}, fail);
}
function onCopySuccess(entry) {
entry
.file(function(file) {
storeChatData.push(entry.toURL() + "," + file.type);
storageChat.setItem("chatdata", JSON
.stringify(storeChatData));
var getimageData = storageQlmChat.getItem("chatdata");
var arrayformate = JSON.parse(getimageData);
$
.each(
arrayformate,
function(index, value) {
var imagepath = value.split(",")
if (index == arrayformate.length - 1) {
if (file.type == 'image/jpeg') {
var storedChat = '<img class="popphoto" style="height: 70px; width: 70px;" src=\''
+ imagepath[0] + '\' >';
previewData(storedChat);
} else if (file.type == 'audio/mpeg') {
var storedChat = "<audio controls>"
+ "<source src='"
+ imagepath[0]
+ "' type='video/mp4'>"
+ "</audio>" + "<br>";
previewData(storedChat);
}
}
});
});
}
function fail(error) {
alert("error" + error.code);
}
.left {
margin-top:10px;
position: relative;
background: aqua;
text-align: left;
min-width: 85%;
padding: 15px 10px;
border-radius: 6px;
border: 1px solid #ccc;
float: left;
left: 8%;
}
.left::before {
content: '';
position: absolute;
visibility: visible;
top: -1px;
left: -10px;
border: 10px solid transparent;
border-top: 10px solid #ccc;
}
.left::after {
content: '';
position: absolute;
visibility: visible;
top: 0px;
left: -8px;
border: 10px solid transparent;
border-top: 10px solid aqua;
clear: both;
}
.right {
position: relative;
background: white;
text-align: right;
min-width: 85%;
padding: 10px 15px;
border-radius: 6px;
border: 1px solid #ccc;
float: right;
right: 5%;
margin-top: 10px;
}
.right::before {
content: '';
position: absolute;
visibility: visible;
top: -1px;
right: -10px;
border: 10px solid transparent;
border-top: 10px solid #ccc;
}
.right::after {
content: '';
position: absolute;
visibility: visible;
top: 0px;
right: -8px;
border: 10px solid transparent;
border-top: 10px solid white;
clear: both;
}
<div class="headerDiv" data-role="header"
id="hdrIdchat" data-position="fixed" data-tap-toggle="false" data-transition="none">
<a class="ui-btn ui-icon-arrow-l ui-btn-icon-left" onClick="navBack()"></a>
<h1 id="lblHdrchat">Chat</h1>
<div data-tap-toggle="false" data-transition="none" style="border-top:1px solid white;width: 100%; text-align: center; display: inline-flex;">
<div style="width: 100%; padding: 10px;">
<img alt="" src="images/vo.png" onclick="startRecord()" style="height: 25px;">
</div>
<div style="width: 100%; padding: 10px">
<img alt="" src="images/imcht.png" onClick="imageGallery(pictureSource.PHOTOLIBRARY)" style="height: 25px;">
</div>
<div style="width: 100%; padding: 10px">
<img alt="" src="images/camcht.png" onclick="getCapImg(navigator.camera.PictureSourceType.CAMERA);" style="height: 25px;">
</div>
</div>
</div>
<div data-role="content">
<div onclick="preChatData()">
<p align="center"></p>
</div>
<div id="example">
<div id="preopqicchat"></div>
<div id="opqicchat" ></div>
<div id="opqicchat1" ></div>
</div>
</div>
<div data-role="footer" data-position="fixed" id="chatfooter"
style="background: transparent; border: none;" data-tap-toggle="false" data-transition="none">
<div style="display: inline-flex; width: 100%;">
<div style="width: 100%">
<textarea autofocus="autofocus" id="txtarchat"></textarea>
</div>
<div>
<button data-role="button" class="ui-btn ui-btn-b"
id="btnchatsend" style="width: 100% !Important;">SEND</button>
</div>
</div>
</div>
Actual Result
Expected Result
Have a look at this demo
header,
footer {
flex: 0 0 auto;
}
main grows in height with the content. The number '1' in the flex shorthand tells how much free space in the container is allocated to the element. In our case, main is given the free space. The auto part of the value is the default size of the flex element. We want auto for all flex children.
main {
flex: 1 0 auto;
...
}
The footer will always be beneath the content, no matter what.
Footer starts at bottom
Footer gets pushed down by content
http://codepen.io/antibland/pen/WwKRBx