I want to display a background image in the background depending on the current weather condition.When I write the following lines in my javascript the code seems to fail:
if(ftemp>=0){
document.body.style.backgroundImage =
"url('https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb')";
}
I am getting the data(ftemp) from an API call and using the condition statement displaying the respective background image.
I tried running just this
document.body.style.backgroundImage =
"url('https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb')";
and the code runs.I believe that there is some problem with the if statement.
Here is the link to my work if it helps:
https://codepen.io/ryoko1/pen/eRvxKb?editors=0110
Thanks.
You are trying to use ftemp variable before getting the value from API. to solve this issue you can access ftemp variable inside getJSON.
Here is you working code: https://codepen.io/dineshu07/pen/ZyvpMP
$(document).ready(function() {
var lat, long, ftemp, ctemp;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
lat = position.coords.latitude;
long = position.coords.longitude;
var url ="https://cors-anywhere.herokuapp.com/https://api.darksky.net/forecast/ff2765ec67506dd69b7c42209bb40d7d/" +
lat +
"," +
long;
$.getJSON(url, function(data) {
var type = data.timezone;
ftemp = data.currently.temperature;
var icon = data.currently.summary;
$("#data").html(ftemp + " ℉");
$("#temp").html(type);
$("#time").html(icon);
if(ftemp>=0){
document.body.style.backgroundImage = "url('https://images.pexels.com/photos/412462/pexels-photo-412462.jpeg?w=940&h=650&auto=compress&cs=tinysrgb')";
}
}).catch(function(error) {
console.error(error);
});
});
}
$("#butt1").click(function() {
ctemp = ftemp - 32;
ctemp *= 0.5556;
ctemp = Math.round(ctemp * 100) / 100;
$("#data").html(ctemp + " ℃");
});
$("#butt2").click(function() {
ftemp = Math.round(ftemp * 100) / 100;
$("#data").html(ftemp + " ℉");
});
});
$("button").show();
p{
font-size:20px;
text-align:center;
}
h1{
text-align:center;
}
#dat{
position:absolute;
width:230px;
height:250px;
left:47%;
top:47%;
margin-left:-50px;
margin-top:-50px;
font-size:20px;
background-color:black;
border-style:solid;
color:white;
}
#temp{
text-align:center;
}
#time{
text-align:center;
}
#data{
text-align:center;
}
button{
float:left;
display:none;
text-align:center;
color:#FF4A4A;
background-color:
}
#butt1{
margin:5px;
}
#butt2{
margin:5px;
}
body{
background-size:cover;
background-repeat:no repeat;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h1><u>Weather App</u></h1>
<div id="dat">
<p id="data">
</p><br>
<p id="temp">
</p><br>
<p id="time">
</p>
<button id="butt1">imperial
</button>
<button id="butt2">metric
</button>
</div>
Your ftemp is undefined. If you need to check a variable value, try this
console.log(variable)
Related
I have a problem. I'm creating a divs from input form, but when I hover my mouse with .hover function, it works only on every second div element (first, third, 5th, 7th...). How do I solve that? What's wrong with JS function?
Thanks for answers.
JS:
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$(".drag").hover(function() {
$(this).toggleClass("mousehover")
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
})
HTML:
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
CSS:
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
The problem is that you are adding the hover event multiple times. It is better to do it only once, using $(document).on().
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
});
$(document).on("mouseenter mouseleave", ".drag", function() {
$(this).toggleClass("mousehover");
});
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
Here you go with a solution https://jsfiddle.net/wcu4w1mn/
$("#entryButton").click(function(){
event.preventDefault(); //stops refreshing
var query = $("#entry").val(); //string z inputa
if (query !== "") {
var trashButton = "<button class='trash'>DEL</button>"
var registry = "<div class='drag'>" + "<p>" + query + "</p>" + trashButton + "</div>"
$("#list").append(registry); //add div with query and ubbton
$("#list").sortable({
//axis: "y",
});
$(".drag").last().hover(function() {
$(this).toggleClass("mousehover")
});
$("#entry").val(""); //clear value
return false; //also stops refreshing
console.log(registry);
}
})
body {
font-size: 14px;
}
form {
float:right;
}
.container {
min-width:300px;
width:20%;
margin: 0 auto;
margin-top:5px;
}
.drag {
margin-top:5px;
background-color:lemonchiffon;
display:inline-flex;
width:100%;
}
.trash {
position:absolute;
margin-left:190px;
}
.mousehover {
opacity:0.5;
}
<link href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<div class="container">
<form>
<input type="text" id="entry">
<button id="entryButton">button</button>
</form>
<ul id="list">
</ul>
</div>
Only changed code
Add hover event to only last added element.
$(".drag").last().hover(function() {
$(this).toggleClass("mousehover")
});
Hope this will help you.
I want to create a card game using java script. Being a beginner at java script, I am finding great difficulty finding a suitable tutorial for what I am trying to do. When the 'start game' button is selected, I want the computer to produce a random card. I have tried many ways of doing this and have came to no avail. Here is my code.
<html>
<head>
<title> Christmas Assignment </title>
<link rel="stylesheet" type="text/css" href="xmasass_1.css">
<script type = "text/javascript">
function randomImg(){
var myimages= [];
myimages[1] = "cards/1.gif";
myimages[2] = "cards/2.gif";
myimages[3] = "cards/3.gif";
myimages[4] = "cards/4.gif";
myimages[5] = "cards/5.gif";
myimages[6] = "cards/6.gif";
myimages[7] = "cards/7.gif";
myimages[8] = "cards/8.gif";
myimages[9] = "cards/9.gif";
myimages[10] = "cards/10.gif";
myimages[11] = "cards/11.gif";
myimages[12] = "cards/12.gif";
myimages[13] = "cards/13.gif";
function oddTrivia(){
var randomImg = Math.floor(Math.random()*(oddtrivia.length));
document.getElementById('comp').InnerHTML=myimages[randomImg];
}
ar total = 0;
function randomImg(){
var x = Math.floor(Math.random()*13)+1;
document.getElementById('img1').src = 'die'+x+'.gif';
document.getElementById('img2').src = 'die'+y+'.gif';
document.getElementById('score').innerHTML = total;
}
var card1Image;
var card2Image;
var card3Image;
var card4Image;
var card5Image;
var card6Image;
function start(){
var button = document.getElementById("startButton");
button.addEventListener("click", pickCards, false);
card1Image = document.getElementById("1");
card2Image = document.getElementById("2");
card3Image = document.getElementById("3");
card4Image = document.getElementById("4");
card5Image = document.getElementById("5");
card6Image = document.getElementById("6");
}
function pickCards(){
setImage(card1Image);
setImage(card2Image);
setImage(card3Image);
setImage(card4Image);
setImage(card5Image);
setImage(card6Image);
}
function setImage(cardImg){
var cardValue = Math.floor(1 + Math.random() * 13);
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
}
window.addEventListener("load", start, false);
</script>
</head>
<body>
<div id = "settings">
<img src = "settings_img.png" width = "60" height = "60">
</div>
<div id = "bodydiv">
<h1> Card Game</h1>
<div id = "computer">
<img src = " cards/back.gif">
</div>
<div id = "comp" > Computer </div>
<div id ="arrow">
<img src ="arrow2.png" width = "100" height="100">
</div>
<div id = "player">
<img src = " cards/back.gif">
</div>
<div id = "play"> Player </div>
<div id = "kittens">
<button id = "startButton" onclick ="randomImg" > Start Game </button>
<div id = "buttons_1">
<button id ="higher"> Higher
</button>
<button id = "equal"> Equal
</button>
<button id = "lower"> Lower
</button>
</div>
<button id = "draw"> Draw your Card
</button>
<div id = "resetscore"> Reset Score
</div>
</div>
<div id = "score">
</div>
</div>
</body>
</html>
body {
background:#66ccff;
}
h1 {
text-align:center;
}
#settings {
float:right;
margin-top:10px;
}
#bodydiv {
width: 800px;
height:600px;
margin-left:200px;
margin-top:40px;
margin-bottom:60px;
background:#ffccff;
border-radius: 10px;
}
#computer {
border-radius: 10px;
position: absolute;
left:35%;
top:27%;
}
#player {
border-radius: 10px;
position: absolute;
left:55%;
top:27%;
}
#start_game {
width :120px;
height: 55px;
margin-left: 350px;
margin-top:50px;
background:white;
border:1px solid black;
}
#buttons_1 {
text-align: center;
margin-top:20px;
}
#higher {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#equal {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#lower {
width:140px;
height:50px;
font-size: 15px;
border-radius:10px;
font-weight:bold;
}
#draw {
width:160px;
height:30px;
margin-left:325px;
margin-top: 30px;
border:1px solid black;
background:#FFFFCC;
}
#resetscore {
text-align: center;
margin-top: 40px;
}
#arrow {
margin-left:370px;
margin-top:-130px;
}
#comp {
margin-top:240px;
margin-left:265px;
}
#play{
margin-top:10px;
margin-left:540px;
}
You code is kind of hard to read.
You forgot to close the "{" of your main function.
You are declaring "randomImg" again in the body of the "randomImg" function(use a different name).
You wrote
ar total = 0;
I think you meant to write:
var total = 0;
oddtrivia in the function "OddTrivia" is not defined.
y in the inner randomImg function is not defined.
Having poked a little bit at the code, here is a few things:
Problem no 1: randomImg()
It's hard to know your intentions, but you should likely begin with removing the start of your first function randomImg(){.
Because 1) It does not have an end and 2) If it actually spans everything then this line window.addEventListener("load", start, false); will not load on startup (since it does not get executed until randomImg() gets executed, and by then the page has already loaded.)
Problem no 2: Cannot set property 'src' of null"
Now when the first problem is out of the way, you should see "Uncaught TypeError: Cannot set property 'src' of null" if you look in your console. Yes, USE YOUR CONSOLE. Click on the error to show what causes it. Here it is:
cardImg.setAttribute("src", "C:Xmas Assignment/cards/" + cardValue + ".gif");
This means that cardImg is null. We backtrack the first call of setImage() and find that the variable card1Image is passed in. So that must mean that card1Image also is null. You can check it yourself by adding a console.log('card1Image', card1Image); in your code. Or you add a breakpoint at that point. (Use the sources-tab in chrome dev tools, click at the line-numbering to add a break point. Refresh the page and it will stop at the break point. Now you can mouse-over variables to see their values.)
Let's look at where 'card1Image' is set.
card1Image = document.getElementById("1");
So why is this returning null? Do we even have a id="1" element in the html? That could be the reason. (It is.)
There are more problems, but I'll stop there, but when you have fixed this part AND have no errors please ask again. Always check your errors and if you ask a question here you should provide errors. And when you can also be more specific with your questions.
What might someone else have done differently?
When it comes to playing cards, why not an array of objects?
var cards = [
{ src : 'cards/1.gif', value: 1 },
{ src : 'cards/2.gif', value: 2 },
{ src : 'cards/3.gif', value: 3 },
{ src : 'cards/4.gif', value: 4 }
]; // (You can of course use code to generate it.)
// Then a function to put cards in the player's hand.
var playerHand = _.sample(cards, 2);
console.log(playerHand);
Here I assume lodash, a lightweight library for when you don't want to re-invent the wheel.
I am currently trying to write a ''web application'' that has a simple text area inside, in which I want the letters of the text written to be pointed out.
For example, if I write:
''How old are you? I am 19 years old''
I need a code to tell me how many 'A's and 'Y's and 'D's (and all letters of the alphabet from 0-26) are used in this sentence when I press a button on a HTML/ CSS page.
Could you please tell me what I must write into my .JS file and what I should write into my .HTML file to do this with a click of a button when something is written in the ?
I hope my explanation was detailed enough. Thanks!
Edit (I'm very sorry for the problems I caused) - What I have done so far looks like this:
HTML:
<link rel="stylesheet" type="text/css" href="theme.css">
<meta charset="utf-8">
<script src="test.js" type="text/javascript"></script>
<div class='header'>
Al.Fa.Be
</div>
<div class='yaz'>
<textarea></textarea>
</div>
<div class='description'>
<a href='http://www.google.com'>Ara</a>
</div>
<div class='description2'>
<input id="clickMe" type="button" value="Hesapla" onclick="doFunction();" />
</div>
CSS:
body{
background:white;
}
selection{
background:#CCC;
}
#clickMe{
background:#CCC;
border:1px solid #333;
}
.header{
font-size:70px;
font-weight:bold;
font-family:Arial;
color:#333;
margin-left:580px;
padding-top:200px;
}
textarea{
width:1210px;
height:40px;
color:black;
margin-top:20px;
margin-left:100px;
padding-left:10px;
padding-top:10px;
font-size:18px;
font-family:Arial;
}
.description{
background:#f2f2f2;
padding:6px;
width:50px;
text-align:center;
border:1px solid #ddd;
font-family:Arial;
margin-left:620px;
margin-top:20px;
font-size:14px;
}
.description a{
color:#555;
text-decoration:none;
}
.description2{
background:#f2f2f2;
padding:6px;
width:60px;
text-align:center;
border:1px solid #ddd;
font-family:Arial;
margin-left:750px;
margin-top:-30px;
font-size:14px;
}
.description2 a{
color:#555;
text-decoration:none;
}
.yaz{
color:white;
}
Javascript:
// Input name. Count number of alphabets a-z
class program
{
public static void main(String[] args)
{
String name = args[0];
int count[] = new int[29];
int i,p;
int n = name.length();
name = name.toUpperCase();
char c;
for (i=0; i<29; i++)
{
count[i] = 0;
}
for (i=0; i<n; i++)
{
c = name.charAt(i);
p = (int) c;
count[p-65]++;
}
for (i=0; i<29 ; i++)
{
if (count[i] >0)
{
System.out.println((char)(i+65) + " occurs " + count[i] + " times");
}
}
}
}
PS: Please remember that I really suck at this and I need to know how to do this in a specific way.
This is how I would do it.
var count = {};
var msg = "Your message";
for(var i = 0; i < msg.length; i++) {
var c = msg[i];
c = c.toLowerCase();
if(typeof(count[c]) == "undefined") {
count[c]=1;
}
else {
count[c]++;
}
}
If you want, you can check for only letters like this:
if('a'.charCodeAt(0) <= c <= 'z'.charCodeAt(0))
//This is a small letter
Try this:
var str = "How old are you? I am 19 years old";
str = str.toLowerCase();// search is case sensitive
var counta = str.match(/a/g);
var countd = str.match(/d/g);
var county = str.match(/y/g);
alert("a:"+counta.length+" d:"+countd.length+" y:"+county.length);
Fiddle here:
Check out this article: http://davidwalsh.name/javascript-unique-letters-string.
It's just what are you looking for.
Edit:
HTML:
<link rel="stylesheet" type="text/css" href="theme.css">
<meta charset="utf-8">
<script src="test.js" type="text/javascript"></script>
<textarea rows="5" cols="10" id="str" value="Insert the string" />
<input type="button" value="Submit" id="button" />
JS:
document.getElementById('button').onclick = function() {
/* returns the size/length of an object */
Object.size = function(obj) {
var size = 0;
for(key in obj) {
if(obj.hasOwnProperty(key)) size++;
}
return size;
}
//initial vars
var str = document.getElementById('str').val;
var letters = new Object;
//loop, figure it out
for(x = 0, length = str.length; x < length; x++) {
var l = str.charAt(x)
letters[l] = (isNaN(letters[l]) ? 1 : letters[l] + 1);
}
//output count!
for(key in letters) {
console.log(key + ' :: ' + letters[key]);
}
console.log(Object.size(letters));
}
PS: your "javascript" doesn't look like javascript... It looks like java...
I would like to know how to resize a textbox to prevent text nearby it from overflowing.
I have 3 elements in a row, a label, a text box, and a button. the label however, can have words of varying lengths. if the word is too long it will move the text input too far to the side and the button will overflow onto the next line. to preserve the style of the page, I would prefer that the button stays on the same line as the other 2 elements.
I am trying to get the text box to shrink only as much as necessary to allow room for the other elements.
can I do this with JQuery?
Edit: here's the JFiddle thing:
http://jsfiddle.net/425ve/2/
and here's the main code:
<html>
<head>
<style>
body{
background-color:#000000;
color:#cccccc;
}
#chatbox{
width:100%;
height:85%;
border-style:solid;
border-color:#000000;
overflow:auto;
}
#mainchat{
width:82%;
float:left;
margin:0;
}
#sidebar{
float:left;
height:97%;
width:17%;
border-style:dashed;
border-width:1px;
border-color:#AAAAAA;
border-right:0;
border-top:0;
border-bottom:0;
overflow:auto;
}
#topbar{
border-style:dashed;
border-width:1px;
border-color:#AAAAAA;
border-left: 0;
border-top: 0;
float:left;
width:82%;
}
a{
color:#cccccc;
text-decoration:none;
}
a:hover{
color:#CCCCEE;
background-color:111122;
}
#topbarname{
float:right;
}
#message{
width: 90%;
background-color:#000000;
border-color:#CCCCCC;
border-style:solid;
border-width: 1px;
color:CCCCCC;
}
#submitbutton{
background-color:#000000;
border-color:#CCCCCC;
border-style:solid;
border-width: 1px;
color:#CCCCCC;
}
</style>
<script>
function getCookie(name) {
var dc = document.cookie;
var prefix = name + "=";
var begin = dc.indexOf("; " + prefix);
if (begin == -1) {
begin = dc.indexOf(prefix);
if (begin != 0) return null;
}
else
{
begin += 2;
var end = document.cookie.indexOf(";", begin);
if (end == -1) {
end = dc.length;
}
}
return unescape(dc.substring(begin + prefix.length, end));
}
function doSomething() {
var myCookie = getCookie("IceID");
if (myCookie == null) {
window.location="login.php"
}
else {
// do cookie exists stuff
}
}
doSomething();
</script>
</head>
<body>
<div id="topbar">
| Information | Logs | characters | Profile | Private logs | Messages | Logout |
</div>
<div id="mainchat">
<div id="chatbox">
<?php
include("getpost.php");
//improve this with AJAX!
?>
</div>
<div id="input">
<form id="inputchat">
<b id="name">
<?php
echo $_COOKIE['IceID'];
?>
</b>
<input type="text" name="message" id="message"></input>
<input type="submit" id="submitbutton" value="say"></input>
</form>
</div>
<div id="utools">
</div>
</div>
<div id="sidebar">
<div id="title">
A
</div>
<div id="list">
</div>
</div>
</body>
</html>
Edit:to clarify, the name doesn't actively change while the page is being used(only right before being displayed), but it will be different depending on who loads the page. their username fits into that label.
You don't need jQuery. jQuery could make it much simpler though. I prefer vanilla.
var left = document.getElementById('name')
var resizable = document.getElementById('message')
var right = document.getElementById('submitbutton')
realign()
window.addEventListener('resize', realign)
function realign() {
resizable.style.width = '0'
var extraWidth = getWidth(resizable) // Measure the border and padding on it's own.
resizable.style.width = getWidth(resizable.parentNode) - getWidth(left) - getWidth(right)
function getWidth(element) { // Superior to offsetWidth because it measures fractions of a pixel which is even more relevant when using the browser zoom feature.
var rect = element.getBoundingClientRect() // A accurate way to measure location on the screen.
return rect.right - rec.left // The accurate width.
}
}
The only adjustment you need would be to fix my typo(s) if I made any and then if you want to support older versions of IE, you need to use the alternative to addEventListener, Google it.
I am trying to append a new "app" to my "AppList" when a button is clicked.
JS
$(".appCreate" ).click(newApp);
function newApp() {
var facebookTemp = $("#facebook-template").html();
var appName = $(this).data("appName");
var appSize = $(this).data("appSize");
var appTemp = $(this).data("appTemp");
$("<div class=\"app" + appName + appSize + "\"></div>").html(appTemp).appendTo(".AppList");
};
HTML
<body>
<section id="AppBox">
<div class="AppList">
<!-- == Facebook == -->
<div id="facebook-template">
<div class="App facebook Size170x290">
<h1>Hello Test</h1>
</div>
</div>
</div>
</section>
<!-- == Settings == -->
<section id="dialog-settings" class="dialog" title="Settings">
<button data-appName="facebook" data-appSize="Size170x290" data-appTemp="facebookTemp" class="appCreate">
Facebook</button>
</section>
</body>
CSS
#facebook-template {
display: none;
}
.facebook {
background:linear-gradient(to bottom, #133783 0px, #102E6D 100%) repeat scroll 0 0 #133783;
}
.facebook { top:120px; left:0; }
#AppBox {
position:fixed;
top:0;
bottom:0;
left:0;
right:0;
margin:0;
}
.AppList {
position:absolute;
height:100%;
width:100%;
margin:0;
padding:0;
}
.App {
position:absolute;
display:block;
margin:5px;
padding:0;
box-shadow:0 0 5px 1px black;
color:#FFFFFF;
cursor:move;
}
.Size170x290 {height:170px;width:290px;}
Basically the thing isn't showing up and i don't know whats causing it.
You lost the context of your click handler.
This was an obvious first mistake:
$(".appCreate" ).click(newApp);
Second mistake is data names. Change to:
var appName = $(this).data("appname");
Notice the case. Convert all names to lower case.
I also added handlebars.js because of the conversation in the comments.
New working code:
$(".appCreate" ).click(newApp);
function newApp() {
var facebookTemp = $("#facebook-template").html();
var appName = $(this).data("appname");
var appSize = $(this).data("appsize");
var appTemp = $(this).data("apptemp");
var template = Handlebars.compile(facebookTemp);
var html = template({
app : appName,
facebook : appTemp,
size : appSize
});
$(".AppList").append(html);
};
Live DEMO && CODE.