Cannot read property '0' of undefined - javascript

I get "Cannot read property '0' of undefined" error. I couldn't find the issue. I think javascript file has a problem but I couldn't see. I wrote the script twice but still js file has a problem.
HTML File
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>FreeCodeCamp - Local Weather</title>
<script src="https://code.jquery.com/jquery-3.0.0.js"></script>
<script type="text/javascript" src="app.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<div id="main" class="text-center container">
<h1>FreeCodeCamp - Weather App</h1>
<div class="row" id="fade">
<div style="margin-top: 200px;">
<span id="city"></span>
<span id="country"></span>
<div id="weather"><img id="w-icon"><span id="temp"></span></div>
<span id="description"></span>
</div>
</div>
<div id="author">
<span> Created by Kaan Karaca</span><br>
<span>#GitHub </span><br>
<span>#FreeCodeCamp </span>
</div>
</div>
</body>
</html>
JavaScript File
$(document).ready(function () {
var cityId;
var city;
var unitsFormat = "metric";
var getWeatherInfo = function () {
$.getJSON("http://api.sypexgeo.net/json")
.done(function (locationData) {
cityId = locationData.city.id;
cityName = locationData.country.iso;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?", {
id: cityId,
units: unitsFormat,
APPID: '610ae7b6406da76bb34ad4bb95cc3673'
})
.done(function (weatherDate) {
$("#w-icon").attr("src", "http://openweathermap.org/img/w/" + weatherDate.weather[0].icon + ".png");
$("#temp").text(Math.round(weatherDate.main.temp) + "°C");
$("#city").text(weatherDate.name + ",");
$("#country").text(cityName);
$("#description").text(weatherDate.weather[0].description);
});
});
}
getWeatherInfo();
});

Your code is too trusting that all these calls will work.
In my case, the json from http://api.sypexgeo.net/json correctly locates me, but http://api.openweathermap.org/data/2.5/weather?" has no clue about that city id. Therefore it passes back a json such as:
{
"cod": "404",
"message": "Error: Not found city"
}
This obviously lacks the array weather, so js throws an undefined.
The solution would be to get the specs from the weather api (and location, while you're at it) and check that the response code is good. (I guessed "200" is good. I never got the success case).
$(document).ready(function() {
var cityId;
var city;
var unitsFormat = "metric";
var getWeatherInfo = function() {
$.getJSON("http://api.sypexgeo.net/json")
.done(function(locationData) {
cityId = locationData.city.id;
cityName = locationData.country.iso;
$.getJSON("http://api.openweathermap.org/data/2.5/weather?", {
id: cityId,
units: unitsFormat,
APPID: '610ae7b6406da76bb34ad4bb95cc3673'
})
.done(function(weatherDate) {
if (weatherDate.cod != "200") {
console.log(weatherDate);
console.log("Couldn't find the weather!!!");
return;
}
$("#w-icon").attr("src", "http://openweathermap.org/img/w/" + weatherDate.weather[0].icon + ".png");
$("#temp").text(Math.round(weatherDate.main.temp) + "°C");
$("#city").text(weatherDate.name + ",");
$("#country").text(cityName);
$("#description").text(weatherDate.weather[0].description);
});
});
}
getWeatherInfo();
});
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>FreeCodeCamp - Local Weather</title>
<script src="//code.jquery.com/jquery-3.0.0.js"></script>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="style.css" />
</head>
<body>
<div id="main" class="text-center container">
<h1>FreeCodeCamp - Weather App</h1>
<div class="row" id="fade">
<div style="margin-top: 200px;">
<span id="city"></span>
<span id="country"></span>
<div id="weather">
<img id="w-icon"><span id="temp"></span>
</div>
<span id="description"></span>
</div>
</div>
<div id="author">
<span> Created by Kaan Karaca</span>
<br>
<span>#GitHub </span>
<br>
<span>#FreeCodeCamp </span>
</div>
</div>
</body>
</html>

Related

Javascript variable's value not changing

I am making a website and trying to change the value of active car variable which doesn't change even after click on the division the value of activecar remains as .blueimg only even after clicking on the divisions
What is incorrect?
actions.js file
var activecar=".blueimg";
$(".redimg").hide();
$(".greyimg").hide();
$(".silverimg").hide();
$(".red").click(function(){
hideshow(".redimg",activecar);
});
$(".blue").click(function(){
hideshow(".blueimg",activecar);
});
$(".grey").click(function(){
hideshow(".greyimg",activecar);
});
$(".silver").click(function(){
hideshow(".silverimg",activecar);
});
function hideshow(colour,activecar) {
console.log("before");
console.log(activecar);
$(activecar).hide();
$(colour).show();
activecar = colour;
console.log("After");
console.log(activecar);
}
This is my index.html file
<!doctype html>
<html lang="en">
<head>
<title>CollegeDunia</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<img src="./assets/blue.jpg" class="blueimg"/>
<img src="./assets/red.jpg" class="redimg"/>
<img src="./assets/grey.jpg" class="greyimg"/>
<img src="./assets/silver.jpg" class="silverimg"/>
<div>
<a class="blue">Blue</a>
</div>
<div >
<a class="grey"> Grey</a>
</div>
<div >
<a class="red">Red</a>
</div>
<div >
<a class="silver">Silver</a>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="actions.js"></script>
</body>
</html>
change function's parameter name. It has same name with your global variable.
function hideshow(colour, car) { //activecar changed to car

How can I change the html title of my main.hbs file from a partial.hbs?

I am trying to change my html title depending on the partial that I load for the body.
Parent html:
<!DOCTYPE html>
<html lang="en">
<head>
<title>
{{title}}
</title>
</head>
<body>
{{>body}}
</body>
</html>
Partial body.hbs file:
<h1 id="brick-mason">Brick Mason</h1>
<h3 id="what-is-a-brick-mason-">What is a brick mason?</h3>
<p>Brick masons use various stones, concrete and bricks to build walls, walkways, fences, and other structures.</p>
What can I change so that my partial can determine what the title on my main html page displays?
you can do it easily with JavaScript,
just add in the body.hbs :
<script> document.title = 'the title here ' </script>
What I ended up doing was including a second partial in the handlebars file and then splitting them out in the grunt file config.
gruntfile.js
file_context: function(src) {
var fileName = path.basename(src).split(".")[0];
var obj = glob.route[fileName];
var fileString = fs.readFileSync("./" + src, "utf8").split("<split />");
return {
partials: {
header: fileString[0] || "",
body: fileString[1] || "",
},
src: 'src/base.hbs',
dest: path.join('static', obj, 'index.html')
};
}
base.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/css/index.min.css" />
{{>header}}
</head>
<body>
<div id="nav_background"></div>
<div id="main">
<div id="nav_bar">
<div class="nav left_nav">
BlueCollarJobs101
</div>
<div class="nav right_nav">
States
Jobs
Contact Us
</div>
</div>
<div class="markdown-body">
{{>body}}
</div>
</div>
</body>
</html>
In your Partial.hbs body add the script to manipulate the tags
<h1 id="brick-mason">Brick Mason</h1>
<h3 id="what-is-a-brick-mason-">What is a brick mason?</h3>
<p>Brick masons use various stones, concrete and bricks to build walls, walkways, fences, and other structures.</p>
<script>
const title = document.querySelector('title');
title.innerHTML = 'Partial';
</script>

Angularjs fails to dynamic change image src

Hello i'm building an application where i want to dynamically change the source of an image in order to force reload it . The problem is that in order of this i only get a broken image on the browser. Instead , if a run the function manually by a button it runs perfect .
HTML document
<!DOCTYPE html>
<html lang="en" ng-app='cameraApp'>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Node JS Camera</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap-theme.min.css">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src='https://code.angularjs.org/1.4.4/angular-sanitize.min.js'></script>
<script src="cameraApp.js"></script>
</head>
<body>
<div class="container-fluid">
<div class="jumbotron">
<h1>Welcome to NodeJS Camera v1</h1>
</div>
<div ng-controller="HomeController">
<div class="cameraControl col-md-5">
<p>Here is the camera control</p>
<button class="btn btn-default" ng-click="getSnapshot()">Snapshot</button>
<button class="btn btn-info" ng-click="intervalFunction()">Start Feed</button>
</div>
<div class="lifeFeed col-md-7">
<p>Here is the live feed</p>
<p><button class="btn btn-default" ng-click="readSnapshot()">Snapshot Read</button></p>
<img width='600' height='600' ng-src="{{snapshot}}" alt="SnapShot taken">
</div>
</div>
</div>
</body>
</html>
cameraApp.js
var cameraApp = angular.module('cameraApp',[]);
cameraApp.controller('HomeController', function($scope,$http,$timeout) {
function updateImage() {
var img = 'snapshots/camera.jpg'+ '?decache=' + Math.random();
console.log('Snapshot Loaded');
$scope.snapshot = img;
};
$scope.readSnapshot = updateImage;
$scope.getSnapshot = function() {
$http.get('/api/getSnapshot')
.then(function(response) {
// this callback will be called asynchronously
// when the response is available
console.log('Snapshot captured');
$scope.readSnapshot();
}, function(response) {
console.log('Error in capturing...');
});
}
$scope.intervalFunction = function() {
$timeout(function() {
$scope.getSnapshot();
$scope.intervalFunction();
}, 2000);
};
// Kick off the interval
$scope.intervalFunction();
});
There are two solutions I've used for this in the past.
1) Use an ng-if/ng-show on your img tag. This will prevent the broken image from displaying.
<img ng-if='snapshot'>
2) Set a default image that will load and then be replaced once the other images load.
$scope.snapshot = 'snapshots/default.png';

HTML/JS: appendTo doesnt work

I wanted to dynamically append a Table/List to HTML page. My code as follows:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>Lead Manager</title>
<link rel="stylesheet" href="themes/Bootstrap.css">
<link rel="stylesheet" href="themes/jquery.mobile.structure-1.2.0.min.css" />
<script src="themes/jquery-1.8.2.min.js"></script>
<script src="themes/jquery.mobile-1.2.0.min.js"></script>
</head>
<body id="body" name="body">
<div data-role="page" data-theme="a">
<div data-role="header" data-position="inline">
<h1>Lead Manager</h1>
</div>
<div data-role="content" data-theme="a">
<h2>List of Leads</h2>
</div>
</div>
</body>
<script>
$(document).ready(function(e) {
//var data = Android.getLeads();
var data = [{"status":"1","name":"1","campaign":"1","date":"1"},{"status":"2","name":"2","campaign":"2","date":"2"}];
var items = [];
var date;
var name;
var status;
//eval(" var x = " + data + " ; ");
//var y = JSON.stringify(x);
$.each(data, function(key,val){
items.push('<tr><td>' + val.date + '</tr></td>');
});
var text = $('<table/>', { html: items.join('')});
$('<table/>', {
html: items.join('')
}).appendTo('body');
});
</script>
</html>
The Items[] variable is getting filled with the tr and td values. However, the appendTo, doesnt work. The JSON as you can see doesnt require eval as its already in the format required.
Please can you help?
The issue was mainly because of the jquery.mobile script as it wasnt allowing dynamic addition of html code.

safari ReferenceError: Can't find variable changestyledisplayblock

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>The Goodies</title>
<link rel="stylesheet" href="core.css" type="text/css"/>
<meta name="generator" content="DocBook XSL Stylesheets V1.74.0"/>
<script type="text/javascript"> function changestyledisplayblock(id){ var ps = document.getElementsByTagName('p'); for (var i=0; i < ps.length; i++) { if (ps[i].id == id) { if ( ps[i].style.display == 'none' ) {ps[i].style.display = 'block';} else {ps[i].style.display = 'none';} } } } </script>
</head>
<body>
<div class="sect1" title="The Goodies">
<div class="sect2" title="Multimedia">
<div class="titlepage">
<div>
<div>
<h2 class="title">
<a id="multimedia">Multimedia</a>
</h2>
</div>
</div>
</div>
<p class="bubble speech" id="bubble-speech-0 " style="display:none;">*0 : My first one !</p>
<p class="bubble speech" id="bubble-speech-0 " style="display:none;">*0 : My second one !</p>
<p>text <a class="marker" href="javascript:changestyledisplayblock('bubble-speech-0 ')">*0 </a>next</p>
</div>
</div>
</body>
</html>
here my html, i have the error ReferenceError: Can't find variable changestyledisplayblock, i'm not seeing any error, please help ! if i change my html extension to xhtml i dont see the problem any more ??? any explanation ?
That '<' should be a less than sign. Or was that an error in pasting the code?
Also, I'd advise against calling javascript code in anchor tags.

Categories

Resources