SessionStorage.getitem not working when loading page - javascript

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");

Related

Javascript code for simple slide show page is not working

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">

How to program a button to change stylesheets with javascript

Please note that I am not using classes. I haven't found an answer for this SPECIFIC question.
Using javascript, how can I program a button to change the stylesheet each time the button is clicked?
I've tried different if, else if and else, but when I try them, it breaks the code (ie, it will change the color to blue if red, but not back again).
It works with 2 buttons, but getting it to change each time a single button is clicked seems to be eluding me. I got feed up and programmed a second button to change it back.
This works for 2 buttons:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
<style>
</style>
</head>
<body>
<p>booga</p>
<button id="x" onclick="myFunction()">blue</button>
<button id="x1" onclick="myFunction1()">red</button>
<script>
function myFunction() {
if (document.getElementById("um").href = "stylesheet1.css"){
document.getElementById("um").href = "stylesheet2.css"}
}
function myFunction1() {
if (document.getElementById("um").href = "stylesheet2.css"){
document.getElementById("um").href = "stylesheet1.css"}
}
</script>
</body>
I would like to be able to get rid of the second button and second function and have it all with one button.
EDIT...
I tried this, and it failed.
function myFunction() {
if (document.getElementById("um").href == "stylesheet1.css")
{document.getElementById("um").href = "stylesheet2.css"};
else {document.getElementById("um").href = "stylesheet1.css"}
}
Make sure you're using == instead of = for your comparisons!
if (document.getElementById("um").href == "stylesheet1.css")
etc
Try this:
<button id="x" onclick="myFunction()">Change</button>
<script>
function myFunction() {
var link = document.getElementById("um");
var segments = link.href.split('/');
var currentStyle = segments[segments.length - 1];
var style = (currentStyle == 'stylesheet1.css') ? 'stylesheet2'
: 'stylesheet1';
document.getElementById("um").href = style + ".css"
}
</script>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>"Your Title Here"</title>
<link id="um" rel="stylesheet" href="stylesheet1.css">
</head>
<body>
<p>booga</p>
<button onclick="myFunction('um','stylesheet1.css', 'stylesheet2.css')">swap</button>
<script>
function myFunction(id,a,b) {
var el = document.getElementById(id);
var hrefStr;
if(~el.href.indexOf(a)) {
hrefStr = el.href.replace(a, b);
el.href = hrefStr;
} else {
hrefStr = el.href.replace(b, a);
el.href = hrefStr;
}
}
</script>
</body>
</html>

Javascript - basic programing, canĀ“t change picture

I have five jpg pictures and on a homepage i want to choose between these five pics by typing 1,2,3,4 or 5 and click OK and then i want that picture to show.
My code looks like this:
var inputElem, msgElem;
function init() {
msgElem = document.getElementById("message");
inputElem = [];
inputElem[1] = document.getElementById("input1");
inputElem[2] = document.getElementById("input2");
inputElem[3] = document.getElementById("input3");
document.getElementById("btn1").onclick = showFruit;
}
window.onload = init;
function showFruit() {
var nr, fruitUrl;
fruitUrl = (fruitImg.src = "pics/fruit" + nr + ".jpg");
nr = Number(input1.value);
fruitImg.src = "pics/fruit" + nr + ".jpg";
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
The problem is that I can't change the picture.I don't know whats missing, or how to make it choose between pic 1-5.
I have no privilege to write comments, so can't estimate what you actually want. But the resulting effect may be the thing you want.
But have look up below examples (live here). Enter a number then click button.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp">
<input type="submit" id="btn1" onclick="showFruit('inp')">
<script type="text/javascript">
makeImageFromNum = function (n) {
var nr = document.getElementById(n).value;
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
In below example (live here) just change the number - no need to click a button, there is no any actually :)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div id="image">
<img src="salon1.jpg" id="fruit">
</div>
<input type="number" id="inp" onchange="showFruit(this.value)">
<script type="text/javascript">
makeImageFromNum = function (nr) {
if (parseInt(nr)>5) {
nr = 5;
}
else if (parseInt(nr)<1) {
nr = 1;
}
return "salon"+nr+".jpg";
}
showFruit = function (n) {
document.getElementById("fruit").src = makeImageFromNum(n);
}
</script>
</body>
</html>
Note that you're always assinging the first image in this line of code (the last Iine if your code)
fruitUrl = document.getElementById("fruitImg").src = "pics/fruit1.jpg";
So, you'll always see image one

Palindrome incorrect results.

I'm trying to create a palindrome checker. And now it seems that my lengthChecker() is no longer being called, nor is the condition whenever a word isn't a palindrome, then say it's not a palindrome. What could be the issue?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Lesson #6 Homework</title>
<script type="text/javascript" src="./js/palindrome.js"></script>
</head>
<body>
<h1>Is it a Palindrome?</h1>
<div id="mainCont">
<p>Hello. Please enter a word, and I'll see if it is a palindrome.</p>
<p>Word:
<input type="text" id="str" name="string" />
<button id="checkInput">Submit</button>
</p>
</div>
</body>
</html>
Here is the JS as of now:
function lengthChecker() {
var str = document.getElementById("str").value;
if (str.length > 10 ) {
alert("Sorry. Your input surpasses the 10 characters maximum. Please try again.")
return false;
} else if (str.length == 0) {
alert ("Sorry. Your input is too short, and doesn't meet the 10 characters maximum. Please try again.")
return false;
}
palindrome();
}
function palindrome() {
var revStr = "";
var str = document.getElementById("str").value;
var i = str.length;
for (var j = i; j >= 0; j--) {
revStr = revStr + str.charAt(j);
}
if (str == revStr) {
isPalindrome();
} else {
alert(str + " -is not a Palindrome");
}
}
function isPalindrome() {
alert(str + " is a Palindrome.");
}
document.addEventListener("DOMContentLoaded" , function(e){
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});
You have your Javascript linked in the head element, so it is executed before the <button id="checkInput"> gets into the DOM. Move it to the end of body or make it deferred.
Because you are tying to access your button, before your page is properly loaded.
You need to get your button and bind your event handler, when DOM is loaded.
document.addEventListener("DOMContentLoaded", function(e) {
var el = document.getElementById("checkInput");
el.addEventListener("click", isPalindrome);
});

Create and save new list item with Javascript and HTML 5

I have the following code.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function addChildElements()
{
var newdiv=document.createElement("li");
var newtext=document.createTextNode("test");
newdiv.appendChild(newtext);
document.getElementById("scribble").appendChild(newdiv);
}
</script>
<script>
function storeUserScribble(id) {
var scribble = document.getElementById('scribble').children;
localStorage.setItem('userScribble',scribble);
}
function getUserScribble() {
if ( localStorage.getItem('userScribble')) {
var scribble = localStorage.getItem('userScribble');
}
else {
var newdiv=document.createElement("li");
var newtext=document.createTextNode("test");
newdiv.appendChild(newtext);
document.getElementById("scribble").appendChild(newdiv);
}
document.getElementById('scribble').children = scribble;
}
function clearLocal() {
clear: localStorage.clear();
return false;
}
</script>
</head>
<body>
<ol id="scribble" contenteditable="false" onclick="storeUserScribble(this.id);">
</ol>
<input type="button" value="Add Child Element" onclick="addChildElements(); storeUserScribble(document.getElementById('scribble').id);"/>
</body>
</html>
Which is meant to save the list items as they are created, but i'm completely at a loss. This code doesn't work. I know it probably has something to do with:
var scribble = document.getElementById('scribble').children;
or
onclick="addChildElements(); storeUserScribble(document.getElementById('scribble').id);"
But that is about where my JS knowledge stops.
Any help is much appreciated.

Categories