Javascript code for simple slide show page is not working - javascript

Here is an example from the book "DOM Scripting: Web Design with JavaScript and the Document Object Model." I don't know why it's not working. When I click on the list, the pictures should be changed in the placeholder. But now they only open in the window.
Thank you!
window.onload = prepareGallery;
function prepareGallery() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {
return showPic(this) ? false : true;
}
}
}
function showPic(whichpic) {
if (!document.getElementById("placeholder")) return false;
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
if (placeholder.nodeNae != "IMG") return false;
placeholder.setAttribute("src", source);
if (document.getElementById("description")) {
var text = whichpic.getAttribute("title") ? whichpic.getAttribute("title") : "";
if (description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = text;
}
}
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Gallery</title>
</head>
<body>
<h1>Snapshots</h1>
<ul id="imagegallery">
<li>Flower</li>
<li>Building</li>
<li>Cold Day</li>
<li>Sunset</li>
</ul>
<p id="description">Choose an Image.</p>
<img src="images/placeholder.png" alt="my image gallery" id="placeholder" style="border: 2px solid #eaeaea">
</body>
</html>

So I looked up the ebook. didn't want to buy it to answer a question, but I took a look at the source code and couldn't find what chapter you'd be on to be using just this code. from what it looks like it, I can only guess you're on chapter 6, so take a look at the example JS script for that chapter, it works fine. also, you have a syntax error on line 38 of your code "documnet" should probably be document. Would have made this a comment but couldn't.

The issue is if (placeholder.nodeNae != "IMG") return false; nodeNae should be nodeName. Not sure why the snippet wasn't throwing an error.
window.onload = prepareGallery;
function prepareGallery() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsByTagName("a");
for (var i = 0; i < links.length; i++) {
links[i].onclick = function() {
return showPic(this) ? false : true;
}
}
}
function showPic(whichpic) {
if (!document.getElementById("placeholder")) return false;
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
if (placeholder.nodeName != "IMG") return false;
placeholder.setAttribute("src", source);
if (document.getElementById("description")) {
var text = whichpic.getAttribute("title") ? whichpic.getAttribute("title") : "";
if (description.firstChild.nodeType == 3) {
description.firstChild.nodeValue = text;
}
}
return true;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Image Gallery</title>
</head>
<body>
<h1>Snapshots</h1>
<ul id="imagegallery">
<li>Flower</li>
<li>Building</li>
<li>Cold Day</li>
<li>Sunset</li>
</ul>
<p id="description">Choose an Image.</p>
<img src="images/placeholder.png" alt="my image gallery" id="placeholder" style="border: 2px solid #eaeaea">
</body>
</html>
This code seems pretty outdated so I'm going to write a newer one.
const is a block scoped variable that cannot have the value altered and cannot be redeclared. Docs
.querySelector and .querySelectorAll return either a DOM object or a NodeList of matching nodes respectively. Docs
Since gallery_images is a NodeList that means we can iterate over it with .forEach. In the forEach I am using an Arrow Function as shorthand for assigning the event listener to the a element.
.forEach(image => image.addEventListener('click', showImage)) is the same as .forEach(function() { this.addEventListener('click', showImage); }.
If anything is confusing I can try and clarify it some more. I've linked to the docs for additional information.
const gallery = document.querySelector('#imagegallery');
const gallery_images = document.querySelectorAll('#imagegallery a');
const placeholder = document.querySelector('#placeholder');
gallery_images.forEach(image => image.addEventListener('click', showImage));
function showImage(event) {
event.preventDefault(); // Stop the link from opening
const source = this.href;
const title = this.title;
placeholder.src = source;
placeholder.alt = title;
}
<h1>Snapshots</h1>
<ul id="imagegallery">
<li>Flower</li>
<li>Building</li>
<li>Cold Day</li>
<li>Sunset</li>
</ul>
<p id="description">Choose an Image.</p>
<img src="images/placeholder.png" alt="my image gallery" id="placeholder" style="border: 2px solid #eaeaea">

Related

Chrome not reloading object tag after linking to nonexistent file

I have the following index.html. The objective of the javascript below is to reload the #obj element's data tag, so that it can display multiple images. However, it is possible that one of the images I link the buttons to doesn't exist (in this case, #2).
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
What I expect to happen in the following script is this:
The user presses button1, sees apple
User presses button2, sees nothing
User presses button1, sees apple
However, the third step in that doesn't happen - when I try to reload the object's data after linking to a nonexistent file, it stays blank.
As far as I've been able to gather, this happens in Chrome, and for me works in Safari. I must use the object tag, or some other method that allows for interactive SVG.
One solution you could possibily do is to remove and add the node itself to force a hard reset
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data", "https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
var clone = object.cloneNode();
var parent = object.parentNode;
parent.removeChild(object);
parent.appendChild(clone);
} else {
object.setAttribute("data", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
Try changing the tag to an <img> and setting the "src" attribute.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("src","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg")
}
else {
object.setAttribute("src", "file/that/doesnt/exist")
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<img id="obj" style='width: 100px'></img>
</body>
</html>
I provide a sample which helps you to solve your problem by making a fake request to that URL.
Chrome does it to inform. Even if you handle onerror correctly with correct error handling with try-catch and every trick with a void or ( ) that is told to prevent error - you can not fix it. It is out of Javascript control.
function updateObject(evt) {
var id = evt.currentTarget.id;
var object = document.getElementById("obj");
if (id == "1") {
object.setAttribute("data","https://upload.wikimedia.org/wikipedia/commons/f/fa/Apple_logo_black.svg");
}
else {
var request;
if(window.XMLHttpRequest)
request = new XMLHttpRequest();
else
request = new ActiveXObject("Microsoft.XMLHTTP");
request.open('GET', 'file/that/doesnt/exist', false);
request.send();
// the object request will be actually modified
if (request.status === 404) {
alert("The file you are trying to reach is not available.");
}
else
{
object.setAttribute("data", "file/that/doesnt/exist");
}
}
}
for (var i = 0; i < document.getElementsByTagName("button").length; i++) {
document.getElementsByTagName("button")[i].addEventListener("click", updateObject, false);
}
<!DOCTYPE html>
<html>
<head>
<title>Home</title>
<meta name='viewport' content='width=device-width, initial-scale=1.0'>
</head>
<body>
<button id="1">button1</button>
<button id="2">button2</button>
<object id="obj" style='width: 100px'></object>
</body>
</html>
But notice that it will only work on the same origin. For another host, you will have to use a server-side language to do that, which you will have to figure it out by yourself.

SessionStorage.getitem not working when loading page

I am having an issue trying to use storagesession. I have gotten it to work, but as soon as I insert some ifthen logic, it breaks. Below is the working code. The bottom code is when I update the window.onload function that makes it break. Does anybody know why its breaking and how I can fix this? I am using only html/javascript and no server is being used. Thanks so much!
<!DOCTYPE html>
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="container">
<ul class="vertical-nav">
<li>Fruit
<ul class="sub-menu">
<li>Apple</li>
<li>Grape</li>
</ul>
</li>
</ul>
<div id="ShowDept">
</div>
</div>
</body>
<script>
window.onload = function() {
var x = sessionStorage.getItem("Dept");
document.getElementById("ShowDept").innerHTML = x;
}
function ChangeToApple() {
sessionStorage.Dept = "Apple";
}
function ChangeToGrape() {
sessionStorage.Dept = "Grape";
}
</script>
window.onload = function() {
var x = sessionStorage.getItem("Dept");
if (x = "Apple") {
} else if (x = "Grape") {
}
document.getElementById("ShowDept").innerHTML = x;
}
var x = sessionStorage.getItem("Dept");
if (x = "Apple") {
} else if (x = "Grape") {
}
document.getElementById("ShowDept").innerHTML = x;
x = "Apple" means "Assign the string 'Apple' to the variable x. It does not check if x equals "Apple"; use x === "Apple" for that. Because you're doing an assignment in your if statement, you're going to always see Apple in your HTML.
instead of
sessionStorage.Dept = "Apple";
try
sessionStorage.setItem("Dept", "Grape");

element is getting variable without declared

I am having a JavaScript code that is having a value in #message but i have not defined anywhere.
Does $("#message").html(result); is something inbuilt in Javascript?
I apologize if it is very basic and stupid question.
It is linked to my another question "
https://stackoverflow.com/questions/41745209/save-javascript-value-when-converting-speech-to-text-via-webkitspeechrecognition#
Complete Code
<!DOCTYPE html>
<html>
<head>
<script src="Content/SpeechScript.js"></script>
<title>Login Screen</title>
<meta charset="utf-8" />
</head>
<body >
<div id="results">
<span id="final_span" class="final"></span>
<span id="interim_span" class="interim"></span>
</div>
<script type="text/javascript">
function Typer(callback) {
speak('Welcome ,Please Speak your CPR Number');
var srcText = 'WelcomeToDanske,PleaseSpeakyourCPR Numberwhat';
var i = 0;
debugger;
var result = srcText[i];
var interval = setInterval(function () {
if (i == srcText.length - 1) {
clearInterval(interval);
callback();
return;
}
i++;
result += srcText[i].replace("\n", "<br />");
$("#message").html(result);
debugger;
document.getElementById('user').innerHTML = result;
// var parent = document.getElementById('parentDiv');
// var text = document.createTextNode('the text');
// var child = document.getElementById('parent');
// child.parentNode.insertBefore(text, child);
// var div = document.getElementById('childDiv');
//var parent = document.getElementById('parentDiv');
//var sibling = document.getElementById('childDiv');
////var text = document.createTextNode('new text');
// //parent.insertBefore(result, sibling);
},
100);
return true;
}
function playBGM() {
startDictation(event);
}
Typer(function () {
playBGM();
});
// say a message
function speak(text, callback) {
var u = new SpeechSynthesisUtterance();
u.text = text;
u.lang = 'en-US';
u.onend = function () {
if (callback) {
callback();
}
};
u.onerror = function (e) {
if (callback) {
callback(e);
}
};
speechSynthesis.speak(u);
}
</script>
</div>
<div id="clockDisplay">
<span id="id1">Welcome:</span>
<table width="100%" border="1"><tr><td width="50%"> Username : </td><td><div id="message"></div></td></tr></table>
</body>
</html>
$("#message").html(result); is something inbuilt in Javascript?
No.
$ is a variable that is no part of the JavaScript spec, nor is it part of the common extensions to JS provided by browsers in webpages. It is commonly used by libraries such as PrototypeJS and jQuery. This particular case looks like jQuery, but you aren't including that library in your page.
Fist off, remember to include jQuery as script in your html document or $ will not be defined.
#message Refers to an element in your html document with the tag of id="message"
To get an element in jQuery, by id, you use this syntax: var Element = $("#ID");
So, to make sure your code works, ensure that both there is an element with the ID message, and a defined variable named result containing the html text to put into your element.
Since you want to append to <div id="clockDisplay"> <span id="user">Username :</span></div>, why not change it to:
<div id="clockDisplay">
<span id="user">Username :</span>
<div id="message"></div>
</div>

Cannot set property 'innerHTML' of null while still using window.onload to delay

I am trying to write a script that changes the color of the text if it is an active screen (there are probably more efficient ways to do this). The error I am getting is Uncaught TypeError: Cannot set property 'innerHTML' of null My JavaScript (the entire page)
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
main();
The HTML
<!DOCTYPE html>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<html>
<head>
<title>
</title>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script src="../scripts/essentials.js"></script>
</body>
</html>
The IDE (Visual Studio 2015 Cordova) says that the error is on this line in the JavaScript "var cardDivPrint = cardDiv + card + closer;" I have looked at multiple similar problems and applied what was relevant (also tried changing window.onload to document.onload) but it still throws the same error.
onload expects function to be executed after page is completely loaded. Otherwise it'll treat it as simple assignment statement and execute. Use function as follow:
window.onload = function() {
document.getElementById("header").innerHTML = cardDivPrint;
};
UPDATE
Instead of using main(), use DOMContentLoaded event.
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = window.location.href.indexOf(Check) !== -1 ? "red" : "white";
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
document.getElementById("header").innerHTML = cardDivPrint;
});
Call the main function at the end of your body content
You are getting this error just because the element dose not exists at the time of its selection by JS DOM
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<link href="../css/MasterSheet.css" rel="stylesheet" />
<script>
function main() {
var cardDiv = '<div id ="cardScreen"><a href="cardScreen.html">';
var card = "Card";
var closer = "</a></div>";
var color = (function color1(Check) {
if (window.location.href.indexOf(Check))
return "red";
else
return "white";
});
card.fontcolor = color("cardScreen");
var cardDivPrint = cardDiv + card + closer;
window.onload=document.getElementById("header").innerHTML= cardDivPrint;
}
</script>
</head>
<body>
<div id="header">
</div>
<div>Content goes here.</div>
<script>main();</script>
</body>
</html>

getElementsByName only?

The following code is meant to change the color of one field:
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<form></form>
<form>
<input name="thisone" />
</form>
<script language="javascript">
var bkColor = "red";
function getEvent(e){
if(window.event != null) {
return event;
}
return e;
}
function setBKColor(e){
e = getEvent(e);
var src = e.srcElement || e.target;
window.status="t";
if(src != null) {
src.style.bkColor = src.style.backgroundColor;
src.style.backgroundColor = bkColor;
}
}
function reSetBKColor(e){
e = getEvent(e);
var src = e.srcElement || e.target;
if(src != null) {
src.style.backgroundColor = src.style.bkColor;
}
}
function attachEvent(name,element,callBack) {
if (element.addEventListener) {
element.addEventListener(name, callBack,false);
} else if (element.attachEvent) {
element.attachEvent('on' + name, callBack);
}
}
function setListner(eve,func) {
var ele = document.forms[0].elements;
for(var i = 0; i <ele.length;i++) {
element = ele[i];
if (element.name) {
switch (element.name) {
case 'thisone':
attachEvent(eve,element,func);
}
}
}
}
setListner("focus",setBKColor);
setListner("blur",reSetBKColor);
</script>
However, when before the field which changes color there is another form, the code stops working. So at present the HTML code could look like this, to match the inconvenience:
<name="thisone">
<form></form>
<form></form>
Now this code works.
But how to make the JS part independent from <form>, and only dependent on the <Name> of the text field?
Add an id to your form and use that to refence it
function setListner(eve,func) {
var ele = document.getElementById("#formID").elements;
Using a forms index in the DOM is an unreliable way of accessing its elements

Categories