Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 days ago.
Improve this question
I am trying to display the image from pokeapi but I get an error when I input the name. When I input the number I do get the pokemon image after clicking twice. But when I search for another pokemon I get a number of the previous pokemon. I would appreciate the help on the proper way to display the image. Thanks.
JS code is as follows:
document.querySelector("#search").addEventListener("click", getPokemon);
function getPokemon(e) {
const name = document.querySelector("#pokemonName").value;
fetch(`https://pokeapi.co/api/v2/pokemon/${name || id}`)
.then((res) => res.json())
.then((data) => {
console.log(data);
document.getElementById("data_id").innerHTML = data.id;
document.getElementById("data_name").innerHTML = data.name;
document.getElementById("data_type").innerHTML = data.types
.map((type) => type.type.name)
.join(", ");
document.getElementById("data_moves").innerHTML = data.moves
.map((move) => move.move.name)
.slice(0, 5)
.join(", ");
document.getElementById("search").addEventListener("click", getImage);
function getImage() {
const img = new Image();
img.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${name || id}.png`;
document.getElementById("image").appendChild(img);
}
})
.catch((err) => {
console.log("Error pokemon not found", err);
});
e.preventDefault();
}
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<!-- CSS -->
<link rel="stylesheet" href="style.css" />
<!-- BOOTSTRAP -->
<link
href="https://cdn.jsdelivr.net/npm/bootstrap#5.3.0-alpha1/dist/css/bootstrap.min.css"
rel="stylesheet"
integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD"
crossorigin="anonymous"
/>
<!-- Google fonts -->
<link rel="preconnect" href="https://fonts.googleapis.com" />
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
<link
href="https://fonts.googleapis.com/css2?family=Roboto+Mono&family=Unbounded&display=swap"
rel="stylesheet"
/>
<!-- cdnfonts -->
<link
href="https://fonts.cdnfonts.com/css/pokemon-solid"
rel="stylesheet"
/>
<title>Pokedex</title>
</head>
<body>
<div class="main-container">
<h1 class="heading">Pokemon</h1>
<form class="nameForm">
<input
type="text"
id="pokemonName"
name="pokemonName"
placeholder="Enter Pokemon Name"
/><br />
<button type="submit" class="sub-btn" id="search">Enter</button>
</form>
<div class="pokemonInfo container text-center">
<div id="image"></div>
<div class="row row-cols-2 gy-1">
<div class="pokemon-info-left dark-green col">Pokedex no.</div>
<div class="yellow col" id="data_id"></div>
<div class="w-100"></div>
<div class="pokemon-info-left light-green col">Name</div>
<div class="light col" id="data_name"></div>
<div class="w-100"></div>
<div class="pokemon-info-left dark-green col">Type</div>
<div class="yellow col" id="data_type"></div>
<div class="w-100"></div>
<div class="pokemon-info-left light-green col">Move</div>
<div class="light col data_moves" id="data_moves"></div>
</div>
</div>
</div>
<!-- Javascript -->
<script src="main.js"></script>
</body>
</html>
I tried a few ways cant seem to get it to work.
You can create a image tag inside of div#image and change its src attribute after you receive the response from the API. Here is how:
In you HTML code, add this:
<div id="image">
<img src="" alt="Pokemon Image" id="pokemon-image" />
</div>
In you JS code, remove these lines:
document.getElementById("search").addEventListener("click", getImage);
function getImage() {
const img = new Image();
img.src = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${name || id}.png`;
document.getElementById("image").appendChild(img);
}
and replace with these code:
const img_link = `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${data.id}.png`
document.getElementById("pokemon-image").setAttribute("src", img_link);
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed last month.
Improve this question
I was trying to create a crud app(local storage) from a Udemy course and ran into the following error in the code, the event Listener is to get the value in the input section once user hits submit;
following is the app.js
`
// ****** SELECT ITEMS **********
const alert = document.querySelector(".alert");
const form = document.querySelector(".grocery-form");
const grocery = document.getElementById(".grocery");
const submitBtn = document.querySelector(".submit-btn");
const container = document.querySelector(".grocery-container");
const list = document.querySelector(".grocery-list");
const clearBtn = document.querySelector(".clear-btn");
// edit option
let editElement;
let editFlag = false;
let edtiID = "";
// ****** EVENT LISTENERS **********
form.addEventListener("submit", addItem);
// ****** FUNCTIONS **********
function addItem(e) {
e.preventDefault();
const value = grocery.value;
const id = new Date().getTime().toString();
console.log(id);
}
`
following is the index.html
`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery Bud</title>
<!-- font-awesome -->
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css"
/>
<!-- styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<section class="section-center">
<!-- form -->
<form class="grocery-form">
<p class="alert"></p>
<h3>grocery bud</h3>
<div class="form-control">
<input type="text" id="grocery" placeholder="e.g. eggs" />
<button type="submit" class="submit-btn">submit</button>
</div>
</form>
<!-- list -->
<div class="grocery-container">
<div class="grocery-list"></div>
<button class="clear-btn">clear items</button>
</div>
</section>
<!-- javascript -->
<script src="app.js"></script>
</body>
</html>
`
I tried to listen to the submit event and capture the value in the input box in the form. But I got the error value is null, also tried to console log the 'grocery' element, got null instead
grocery is an ID not class, so document.getElementById needs a plain ID just like grocery not .grocery, this would be called class. Just read about Document.getElementById().
// ****** SELECT ITEMS **********
const alert = document.querySelector(".alert");
const form = document.querySelector(".grocery-form");
const grocery = document.getElementById("grocery");
const submitBtn = document.querySelector(".submit-btn");
const container = document.querySelector(".grocery-container");
const list = document.querySelector(".grocery-list");
const clearBtn = document.querySelector(".clear-btn");
// edit option
let editElement;
let editFlag = false;
let edtiID = "";
// ****** EVENT LISTENERS **********
form.addEventListener("submit", addItem);
// ****** FUNCTIONS **********
function addItem(e) {
e.preventDefault();
const value = grocery.value;
const id = new Date().getTime().toString();
console.log(id);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Grocery Bud</title>
<!-- font-awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css" />
<!-- styles -->
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<section class="section-center">
<!-- form -->
<form class="grocery-form">
<p class="alert"></p>
<h3>grocery bud</h3>
<div class="form-control">
<input type="text" id="grocery" placeholder="e.g. eggs" />
<button type="submit" class="submit-btn">submit</button>
</div>
</form>
<!-- list -->
<div class="grocery-container">
<div class="grocery-list"></div>
<button class="clear-btn">clear items</button>
</div>
</section>
</body>
</html>
Or as #Andy mentioned in comments, you can use Document.querySelector().
I'm currently working with news API and trying to populate different category (i.e sports, science, business etc) under different heading on the same page of the website, but failed to do so. Here I tried to use template literal, as first created a template literal in the api named category and initiated it using let. So there are two sections "Trending Blogs" and "You May Like" so here I wanna show two different category in the two different section respectively. Here I'm attaching the code in the following.
Here is the code in html
`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link rel="stylesheet" href="/styles/utils.css" />
<link rel="stylesheet" href="/styles/navbar.css" />
<link rel="stylesheet" href="/styles/body.css" />
<script
src="https://kit.fontawesome.com/e582ecfb98.js"
crossorigin="anonymous"
></script>
<title>Document</title>
</head>
<body>
<!-- <h1>This is a blog site</h1> -->
<!-- Navbar starts from here -->
<nav class="navigation max-width-0 m-auto">
<div class="middle">
<b> Blogsite</b>
</div>
<div class="left">
<ul>
<li><a class="header-elements" href="./index.html">Home</a></li>
<li><a class="header-elements" href="./about.html">About</a></li>
<li><a class="header-elements" href="./contact.html">Contact</a></li>
</ul>
</div>
<div class="right">
<input type="text" placeholder="Article Search" />
<button class="btn"><i class="fa fa-magnifying-glass"></i></button>
</div>
</nav>
<!-- Navbar ends -->
<!-- body starts -->
<div class="content max-width-1 m-auto">
<h1 class="land-heading">Welcome to Blogsite</h1>
<p class="intro">
Atameo allows travellers to capture their trips in a completely new way.
It records your route, adds your photos, videos and music and turns your
adventures into your personal travel profile. Have all your travel
experiences in one place and find out more about your travel style by
diving into your personal travel statistics: How far did you travel last
year? What’s the highest point you have been to? How much of the world
have you seen? Inspire others to go out and explore, while getting
inspired by some of the most daring journeys of our time. Explore.
Capture. Inspire.
</p>
<hr />
<h1 class="land-heading">Trending Blogs</h1>
<div class="blog-section" id="blog-section">
</div>
<h1 class="land-heading">You may like</h1>
<div class="blog-section" id="blog-section2">
</div>
<h1 class="land-heading">Categories</h1>
<div class="blog-section" id="category">
<div class="r1c1 block">
<a href=""
><img
class="img"
src="https://www.nomadicmatt.com/wp-content/uploads/2022/07/parisnm3.jpeg"
alt="img"
/>
<p class="blog-title">NM+ Weekly Update: Europe Edition</p></a
>
</div>
</div>
</div>
<!-- Body ends -->
<!-- Footer starts -->
<div class="footer m-auto">
<label for="">Feedback</label>
<input type="text" class="" placeholder="First Name" />
<input type="text" placeholder="e-mail" />
<button type="submit" class="btn btn-foot">Send Feedback</button>
</div>
<div class="m-auto copyright">
<p>copyright 2022 #md_arif</p>
</div>
<!-- Footer ends -->
<script src="./scripts/app.js"></script>
</body>
</html>
`
Here is the code of vanilla-js
console.log("Here we go");
let blogSection = document.getElementById("blog-section");
let blogSection2 = document.getElementById("blog-section2");
function generateCards(e) {
const newXHRRequest = new XMLHttpRequest();
// let source = 'the-times-of-india';
let apikey = '75da3b7678de41fcb76359935aabdc3d'
let category = '';
newXHRRequest.open(
"GET",
`https://newsapi.org/v2/top-headlines?country=in&category=${category}&pagesize=3&apiKey=${apikey}`,
true
);
newXHRRequest.getResponseHeader("content-type", "application/json");
newXHRRequest.onload = function () {
if (this.status === 200) {
let myCards = JSON.parse(this.responseText);
console.log(myCards);
let articles = myCards.articles;
// console.log(articles);
let itemsHtml = "";
articles.forEach((element) => {
// console.log(articles);
// category="sports";
console.log(element);
let items = `<div class="r1c1 block">
<a href="${element["url"]}" target="_blank"><img class="img" src=${element["urlToImage"]} alt="img">
<p class="blog-title">${element["title"]}</p></a>
</div>`;
itemsHtml += items;
});
blogSection.innerHTML = itemsHtml;
blogSection2.innerHTML = itemsHtml;
} else {
console.log("Some error occured");
}
};
newXHRRequest.send();
}
generateCards();
I have a partial view where I want to reload certain <div> tag based on successful response. I am using .filter to get specific tag but it is not working. Based on other stack-overflow articles and google, this should work but not in my case.
My objective is, out of AJAX response, extract specific div tag and reload the view.
AJAX:
$.ajax(
{
url: '/MyUrl',
success: function(response)
{
updateOrderStatusContent(response);
}
});
this.updateOrderStatusContent = function (markup) {
alert("markup " + markup); // This returns HTML.
var $response = $(markup); // Creating jQuery object from HTML response.
// Option-1 = Get text
var getSpecificText = $response.filter('#delivery-status-update').text();
alert(getSpecificText); // This is empty.
// Option-2 = Get HTML
var getSpecificHtml = $response.filter('#delivery-status-update').html(); // to get HTML
alert(getSpecificHtml); // This is empty.
// Option-3 = Here I tried output the content of #delivery-status-update in new <div> which is also not working.
$('#delivery-status-updated').html(jQuery(markup).find('#delivery-status-update').html());
};
markup output:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset='UTF-8' />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta content='IE=Edge' http-equiv='X-UA-Compatible' />
<script src="/Scripts/S2/console.js"></script>
<!--[if IE]> <script src="/Scripts/S2/html5.js"></script>
<script src="/Scripts/S2/json2.js"></script>
<![endif]-->
<title></title>
<link href="/Content/S2/menu.css" rel="stylesheet" />
<link href="/content/themes/stwo/jquery-ui.css" rel="stylesheet" />
<link rel="shortcut icon" type="image/x-png" href="/Branding/Snapfinger/favicon.png" />
<link rel="apple-touch-icon" href="/Branding/Snapfinger/touch-icon-iphone.png">
<link rel="apple-touch-icon" sizes="76x76" href="/Branding/Snapfinger/touch-icon-ipad.png">
<link rel="apple-touch-icon" sizes="120x120" href="/Branding/Snapfinger/touch-icon-iphone-retina.png">
<link rel="apple-touch-icon" sizes="152x152" href="/Branding/Snapfinger/touch-icon-ipad-retina.png">
<link rel="stylesheet" href="/Branding/Snapfinger/Snapfinger.css" />
<!--[if IE]><link rel="stylesheet" href="/Branding/Snapfinger/ie.css" /> <![endif]-->
</head>
<body>
<header class="header" id="header"> Skip to content
<div class="header-wrapper">
<div class="logo" id="logo" aria-label="Zaxby's logo" itemscope itemtype="https://schema.org/Organization" tabindex="0"> <img itemprop="logo" alt="Zaxby's logo" src="/api/content/image/119/7/200/200"></div>
<input type="hidden" id="restaurantId" value="9018" />
<input type="hidden" id="menuType" />
<input type="hidden" id="unitNumber" value="198" />
<input type="hidden" id="currentUtcTime" value="2018-04-24T19:27:29.2451514Z" />
<div class="restaurant-info">
<h1 class="title" id="title">Zaxby's</h1>
<meta itemprop="brand" content="Zaxby's" />
<meta itemprop="menu" content="https://local.kiofc.com/o/Restaurant/9018" /> <span itemprop="geo" itemscope itemtype="https://data-vocabulary.org/Geo"><meta itemprop="latitude" content="34.0756282" /><meta itemprop="longitude" content="-84.6527738" /> </span>
<div class="restaurant-name" itemprop="name">Zaxby's</div>
<div class="store-name" itemprop="name">ACWORTH_00198</div>
<ul id="restaurant-address" class="address" itemprop="address" itemscope itemtype="https://schema.org/PostalAddress">
<li class="street" itemprop="streetAddress" tabindex="0">3511 BAKER RD</li>
<li class="city" itemprop="addressLocality" tabindex="0">ACWORTH</li>
<li class="state" itemprop="addressRegion" tabindex="0">GA</li>
<li class="zip" itemprop="postalCode" tabindex="0">30101</li>
<li class="country" itemprop="addressCountry" tabindex="0">US</li>
</ul><a title="View location on google maps" class="map" itemprop="map" target="_blank" href="https://maps.google.com/maps?client=gme-snapfinger&channel=SnapfingerMobileViewMap&oi=map&q=3511+BAKER+RD,+ACWORTH,+GA+30101"> View Map </a>
<div class="phone" itemprop="telephone"> <a title="Call 678-574-0400" href="tel://678-574-0400">678-574-0400</a></div>
<input type="hidden" id="LocationDescription" value="ACWORTH - BAKER RD" />
</div>
</div>
</header>
<div class="page" id="delivery-status-bar">
<div class="content">
<section class="delivery-status" id="delivery-status-bar-section">
<div id="delivery-status-update">
<h3 class="summary-title">Delivery Status</h3>
<div id="order-id">
<h3 class="summary-title" tabindex="0">Order Confirmation : 97140987</h3></div>
<ol class="progress-tracker" data-progress-tracker-steps="4">
<li class="progress-tracker-done">Received</li>
<li class="progress-tracker-done">Kitchen</li>
<li class="progress-tracker-todo">In Transit</li>
<li class="progress-tracker-todo">Delivered</li>
</ol>
</div>
</section>
</div>
</div>
<footer class="footer" id="footer">
<div id="copyright-version">
<div id="copyright-info" tabindex="0"> © Copyright 2018 Tillster, Inc. All rights reserved.</div>
<div id="version-info" tabindex="0"> v 1.0.0.21003</div>
</div>
</footer>
<input id="concept-key" name="concept-key" type="hidden" value="Snapfinger" />
<input id="concept-id" name="concept-id" type="hidden" value="-1" />
<input id="is-vanity-url" name="is-vanity-url" type="hidden" value="False" />
<input id="is-on-premise" name="is-on-premise" type="hidden" value="False" />
<script src="/Scripts/jquery-1.9.1.js"></script>
<script src="/Scripts/jquery-ui-1.11.1.js"></script>
<script src="/Scripts/S2/modernizr2.7.1.js"></script>
<script src="/Scripts/S2/jquery.lazyload.min.js"></script>
<script src="/Scripts/jquery/getscriptonce/jquery.getscriptonce.js"></script>
<script src="/Scripts/handlebars.js"></script>
<script src="/Scripts/S2/utility.js"></script>
<script src="/Scripts/S2/loginRegister.js"></script>
<script src="/Scripts/S2/analytics.js"></script>
<script src="/Scripts/S2/orderStatus.js"></script>
<div id="dialog">
<p id="dialog-message"></p><img id="dialog-image" alt="dialog message" src="#" /></div>
<noscript>
<iframe src="//www.googletagmanager.com/ns.html?id=GTM-PC8WMW" height="0" width="0" style="display:none;visibility:hidden"></iframe>
</noscript>
<script>
(function(w, d, s, l, i) {
w[l] = w[l] || [];
w[l].push({
'gtm.start': new Date().getTime(),
event: 'gtm.js'
});
var f = d.getElementsByTagName(s)[0],
j = d.createElement(s),
dl = l != 'dataLayer' ? '&l=' + l : '';
j.async = true;
j.src =
'//www.googletagmanager.com/gtm.js?id=' + i + dl;
f.parentNode.insertBefore(j, f);
})(window, document, 'script', 'dataLayer', 'GTM-M84GGD');
</script>
<script type="text/javascript">
s$.analytics.getOrderLevelData("pageLoad")
</script>
</body>
</html>
What am I missing here? Do I need to create another partial view to achieve what I want?
Basically you need to use .find() instead of .filter().
var markup = '<!DOCTYPE html><html lang="en"><head> <title></title></head><body><header class="header" id="header"> </header><div class="page" id="delivery-status-bar"><div class="content"><section class="delivery-status" id="delivery-status-bar-section"><div id="delivery-status-update"><h3 class="summary-title">Delivery Status</h3><div id="order-id"><h3 class="summary-title" tabindex="0">Order Confirmation : 123</h3></div><ol class="progress-tracker" data-progress-tracker-steps="4"><li class="progress-tracker-done">Received</li><li class="progress-tracker-done">Kitchen</li><li class="progress-tracker-done">In Transit</li><li class="progress-tracker-todo">Delivered</li></ol></div></section></div></div><footer class="footer" id="footer"></footer></body></html>';
var $response = $(markup); // Creating jQuery object from HTML response.
var $delivery = $response.find('#delivery-status-update');
var getSpecificText = $delivery.text(); // to get text
var getSpecificHtml = $delivery.html(); // to get HTML
console.log(getSpecificText);
console.log(getSpecificHtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I want to add a spinner to show that the content is loading, when someone clicks on an icon. Basically when someone clicks the hyper-link, the page takes time to load and meanwhile I want to show a spinner/'loading image'. How to implement that?
Thanks in advance
My HTML:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" type="image/x-icon" href="images/fav-icon.png" />
<link href="css/style.css" rel="stylesheet" type="text/css" media="all" />
<meta name="keywords" content=" my webpage" />
</head>
<body>
<div class="content">
<div class="wrap">
<!--- start-top-grids---->
<div class="top-grids">
<div class="top-grid">
<div class="product-pic">
<img src="img/search_page.png" title="watch" />
</div>
Directory
</div>
<div class="top-grid">
<div class="product-pic">
<img src="img/news.png" title="shoe" />
</div>
News
</div>
<div class="top-grid">
<div class="product-pic">
<img src="img/payment.png" title="view pay" />
</div>
View Pay
</div>
<div class="clear"> </div>
<div class="clear"> </div>
<div class="clear"> </div>
<div class="clear"> </div>
</div>
</body>
</html>
You can try something like below:
1) Place "spinning wheel" image in one div.
2) Add "Loading..." text
When your page is loading set that div to display and once your page is loaded successfully set div to display: none.
<div id="progressIndicator" style="display: none;">
<div style="background-color: Transparent;" >
<img src="Images/indicator_mozilla_blu.gif" style="font-family: Tahoma; font-size: small; cursor: wait"
align="absMiddle" alt="" /> Loading...
</div>
</div>
UPDATE
When you are clicking on Image button do not directly call server side function. Instead call a client side function like "CallServerSideFunction()" and from that function call your server side function. You can try something like below:
In Javascript function:
function DisplayProgress() {
document.getElementById('progressIndicator').style.display = '';
}
function HideProgress() {
document.getElementById('progressIndicator').style.display = none;
}
function CallServerSideFunction() {
DisplayProgress();
document.getElementById("btnCallServerSideFunction").click();
HideProgress();
}
Let me know if this helps.
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';