using localStorage and to store a count read that count - javascript

I am trying to set up localStorage to have when the button is clicked the number of times the background color has changed is stored there. I also need to be able to clear it at any given point in time, and finally When the document starts, or the page reloaded, access the count that was saved in the above step. If there is not any data – then this is the first time to the web site so there is no need to show the count.
I do not know where to put the localStorage to be able to grab the count, or how to set up the button to clear the localStorage, sorry folks I am very new at all of this and having a very hard time trying to learn this. I am not looking for anyone to write code for me I am just looking for suggestions on what to do next
The code is below any help is greatly appreciated
Thanks all!
<!DOCTYPE html>
<html lang="en">
<head>
<title> </title>
<meta charset="utf-8">
<script type="text/javascript">
var count = 0;
var interval;
function getRandom(num){
return Math.floor(Math.random()*num);
}
function changeColor(){
count ++;
var num1 = getRandom(255);
var num2 = getRandom(255);
var num3 = getRandom(255);
var col = "rgb("+num1+","+num2+","+num3+")";
var div = document.getElementById( 'myDiv' );
div.style.background = col;
}
function stop() {
clearInterval(interval);
alert('The background color has changed ' + count + ' times before you clicked me!');
}
interval = setInterval("changeColor()", 2000);
</script>
<style type="text/css">
.Div {
position:absolute;
width: 800px;
height: 100px;
z-index: 15;
top: 50%;
left: 15%;
background: red;
}
</style>
</head>
<body onLoad="setInterval()">
<div id="myDiv" class="Div">
<input type="button" onClick="stop()", value="I like this color" align="absmiddle">
</div>
</body>
</html>

Related

How could I make a function in JS that works like a Upgrade Button

So I want to make a clicker game and I am now at the part where I want to add a function to the 'upgrade click' button so that when I click it, it takes away 'x' amount of money but it makes my clicks generate 'x' more money
Here is my code:
"use strict";
let varible = 0
const button = document.getElementById('dollarButton');
button.addEventListener('click', myFunc);
function myFunc() {
varible++;
document.getElementById('score').innerHTML = "$" + varible
}
img
{
width:200px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="dollarButton" style="
border: none;
top: 45%;
left: 20%;
position: absolute;
cursor: pointer;
"><img src="https://www.pngfind.com/pngs/m/94-940164_button-images-png-button-background-image-green-transparent.png" /></button>
<h1 id="score">Time to Make Money!</h1>
<div id="updaCash" class="button red">
<span id="updaCash_text" class="color-white">Upgrade click</span>
</div>
<script src="script.js"></script>
</body>
</html>
You'd want to add a event listener to updaCash that fires whenever it's clicked. I'd also suggest adding a variable that tracks how much money is added per click. For example:
script.js
"use strict";
function myFunc() {
varible += amountToAdd;
document.getElementById('score').innerHTML = "$" + varible
}
function upgradeClick() {
amountToAdd += 1; // 1 could be any other number you'd like
}
let varible = 0;
const amountToAdd = 1;
const button = document.getElementById('dollarButton');
const upgradeButton = document.getElementById("updaCash");
button.addEventListener('click', myFunc);
upgradeButton.addEventListener("click", upgradeClick);
Hope this helps! And good luck on your clicker game :D
You need to change your js code.
So your final Js code look like:
"use strict";
function myFunc() {
varible += amountToAdd;
document.getElementById('score').innerHTML = "$" + varible
}
function upgradeClick() {
amountToAdd += 1;
}
let varible = 0;
const amountToAdd = 1;
const button = document.getElementById('dollarButton');
const upgradeButton = document.getElementById("updaCash");
button.addEventListener('click', myFunc);
upgradeButton.addEventListener("click", upgradeClick);
Similarly Your HTML code looks like:
<button id="dollarButton">
<img src="https://fastly.picsum.photos/id/2/200/300.jpg?hmac=HiDjvfge5yCzj935PIMj1qOf4KtvrfqWX3j4z1huDaU" /></button>
<h1 id="score">Time to Make Money!</h1>
<div id="updaCash" class="button red">
<span id="updaCash_text" class="color-white">Upgrade click</span>
</div>
</button>
And Your CSS code :
#dollarButton{
border: none;
top: 45%;
left: 45%;
position: absolute;
cursor: pointer;
}
Here you have to use another variable to keep track of the amount. So when you click the button x amount is added and next time you click x more amount is added.
"use strict";
let varible = 0
let amount =1
const button = document.getElementById('dollarButton');
button.addEventListener('click', myFunc);
function myFunc() {
varible+=amount;
amount+=1 // replace 1 with x (value you want)
document.getElementById('score').innerHTML = "$" + varible
}
img
{
width:200px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button id="dollarButton" style="
border: none;
top: 45%;
left: 20%;
position: absolute;
cursor: pointer;
"><img src="https://www.pngfind.com/pngs/m/94-940164_button-images-png-button-background-image-green-transparent.png"/></button>
<h1 id="score">Time to Make Money!</h1>
<div id="updaCash" class="button red">
<span id="updaCash_text" class="color-white">Upgrade click</span>
</div>
<script src="script.js"></script>
</body>
</html>

Problems show/hiding DIV content depending on whether a variable is NULL [duplicate]

This question already has an answer here:
Why am I getting "TypeError: Cannot read property 'value' of null" when using getElementById?
(1 answer)
Closed 5 months ago.
Right now, I have to create printable documents. Now that I've got the formatting done, my client comes and says that if there are two Trustee names, he needs multiple Trustee signatures. This means I need to generate a second Signature page with the correct name on it. So I check the SecondTrustee variable and am trying to get the second page to show. Otherwise, just show one page.
Can someone show me what I'm doing wrong?
#trustee {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
<body>
<script type="text/javascript">
var second = "asdf";
function checkSigs() {
var x = document.getElementById("trustee");
if (second === "") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
document.onload = checkSigs()
</script>
<p>First Trustee Page</p>
<div id="trustee">
<p>This is my Second Trustee Page.</p>
</div>
</body>
Your javascript code is running before the div element is available so variable x is null. You need to move your script to the end of the html body.
You need to use window load not document load, or add your script at the end of the body.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#trustee {
width: 100%;
padding: 50px 0;
text-align: center;
background-color: lightblue;
margin-top: 20px;
}
</style>
</head>
<body>
<script type="text/javascript">
var second = "asdf";
function checkSigs() {
var x = document.getElementById("trustee");
if (second === "") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
window.addEventListener('load', checkSigs)
</script>
<p>First Trustee Page</p>
<div id="trustee">
<p>This is my Second Trustee Page.</p>
</div>
</body>
</html>

How to update text in window using .innerHTML

I am making a very simple page that just counts how many seconds the user has had the tab open. In the console the seconds update, but on the page in the browser, it ain't.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.seconds = document.getElementById('counts');
var count = setInterval('counter()', 1000);
function counter(){
console.log(seconds)
document.getElementById('counts').innerHTML = window.seconds + 1;
}
</script>
<style>
h2 {
text-align:center;
color:#032441;
font-family:monospace;
}
div {
text-align:center;
color:#032441;
font-size:70px;
font-family:monospace;
}
</style>
</head>
<body>
<script>
document.body.style.backgroundColor = "#EBE9BD"
</script>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
What is the problem?
The variable seconds is declared too soon before the element is even rendered, that's why I added the window.onload wrapper to your code.
You need to use innerHTML to change the content of a div element.
Not related, but you can also style the body tag via CSS rule.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Counter</title>
<script type="text/javascript">
window.onload = function () {
var seconds = document.getElementById('counts');
var count = setInterval(counter, 1000);
function counter(){
var newCount = Number(seconds.innerHTML) + 1
console.log(newCount);
seconds.innerHTML = newCount;
}
}
</script>
<style>
body {
backgroundColor: "#EBE9BD";
}
h2 {
text-align: center;
color: #032441;
font-family: monospace;
}
div {
text-align: center;
color: #032441;
font-size: 70px;
font-family: monospace;
}
</style>
</head>
<body>
<h2>
You have been on this page for
</h2>
<div id="counts">
0
</div>
<h2>
seconds.
</h2>
</body>
</html>
You could use the following:
<script type="text/javascript">
window.seconds = document.getElementById('counts');
setInterval('counter()', 1000);
function counter(){
console.log(seconds.innerHTML);
window.seconds.innerHTML++;
}
</script>
Bare in mind that 'counts' is not yet defined as soon as the script runs.
To access the "body" of an Element you have to access it via element.innerHTML which in your case would look like window.seconds.innerHTML = window.seconds.innerHTML + 1
EDIT: But that won't fix your problem.
Your script does not detect the <div id="counts"> element, since it has not been loaded yet, you can fix this by moving the script after the div
Since innerHTML returns a string, performing + will attach both strings and your seconds will look like 011111111 So you'll have to parse it to a string via parseInt(window.seconds.innerHTML)
So changing
window.seconds = window.seconds + 1
to
window.seconds.innerHTML = parseInt(window.seconds.innerHTML) + 1;
and moving the script tag at the very bottom, should to the trick

images are not rendering on website?

ive looked at other answers and none of them seemed to work which is why i decided to re-ask the question and show you guy my code so you can help me so here it is :
function searchForm() {
var body = document.getElementsByTagName('body')[0]
var search = document.getElementById('GIF-search').value;
var content = document.getElementById('content')
var xhr = $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=api");
xhr.done(function(data) {
var image = data;
var GIF = image['data'][0]['embed_url'];
var GIF_image = document.createElement('img');
GIF_image.setAttribute('src', GIF);
GIF_image.setAttribue('id', 'GIF');
content.appendChild(GIF_image)
});
}
var searchGIF = document.getElementById('search_GIF')
searchGIF.addEventListener('click', searchForm, false);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>GIF viewer</title>
<style type="text/css">
#content {
width: 100%
}
img {
width: 250px;
height: 250px
}
</style>
</head>
<body>
<div id="Search">
<input type="text" name="" id="GIF-search">
<button id="search_GIF">Search GIFs</button>
</div>
<div id="content"></div>
<script src="jquery-3.2.1.js"></script>
<script src="GIFsearch.js"></script>
</body>
</html>
my problem here is that im getting a blank image on my site can anyone explain why this is happening and how i can fix it so it will actually show the GIF?
btw i know in the $.get("http://api.giphy.com/v1/gifs/search?q=" + search + "&api_key=api"); the apikey in not valid (this is on purpose);
Couple of things:
There was no jQuery in jsfiddle. Make sure you have it in your code.
Make https:// api call if your page is using https:// protocol.
setAttribute when you are setting id has got a typo. Look carefully.
URL you are getting at image['data'][0]['embed_url'] is not a image url but a webpage url. Try console log it and see. So you cant really set it as a src of some img tag. Find the correct image url and then proceed.

I want to be able to change each picture to appear in the same place on the screen every time i click a button

I am having some problems, the plan is when i click a button, the pictures change one bu one to represent a traffic light sequence. So when i run the code i want it to start on red and run through the sequence (British sequence). Although when i do run the code all i get is all the pictures coming up at the same time with no effect coming from the button. if anyone can help to accomplish this then that would be greatly appreciated! :)
Cheers!
Here is my code for HTML:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Traffic Lights</title>
<link href="flag_style.css" rel="stylesheet" type="text/css">
<script src="flagscript.js"></script>
</head>
<body>
<input type="button" value="click me" onclick="changeLight()">
<img id="state_1" onclick="changeLight()" src="http://www.drivingtesttips.biz/images/traffic-light-red.jpg">
<img id="state_2" onclick="changeLight()" src="http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg">
<img id="state_3" onclick="changeLight()" src="http://www.drivingtesttips.biz/images/traffic-lights-green.jpg">
<img id="state_3" onclick="changeLight()" src="https://assets.digital.cabinet-office.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg">
</body>
</html>
CSS:
.state_1 {
width:300px;
height:300px;
}
.state_2 {
width:300px;
height:300px;
}
.state_3 {
width:300px;
height:300px;
}
.state_4 {
width:300px;
height:300px;
}
JavaScript:
var flagSeq = ["state_1","state_2","state_3","state_4"];
var state = 0;
function changeFlag() {
if (state == 0) {
document.getElementById("state_1").className = flagSeq[state][0];
state++;
}
if else (state == 1) {
document.getElementById("state_2").className = flagSeq[state][1];
state++;
}
if else (state == 2) {
document.getElementById("state_3").className = flagSeq[state][2];
state++;
}
if else (state == 3) {
document.getElementById("state_4").className = flagSeq[state][3];
state = 0;
}
}
I deleted my other answer because this is apparently a homework problem. I'll gladly point out what to improve, though, so here's the first paragraph from the answer I posted.
There are several issues with your code, to the point where I wonder why you haven't noticed some of them yourself.
You seem to only want to show one image at a time, but you never actually hide any of them.
You're giving the images id attributes but only use class selectors in your CSS.
There are two elements with an id of state_3.
if else is not valid in JavaScript (the console will be happy to point out a syntax error). You probably meant to write else if instead.
As j08691 pointed out, you define a function changeFlag but refer to it as changeLight in your HTML.
Side note: for real-life projects, you'd be better off downloading the images and using those instead of linking to external resources.
What I would do is have only one img element and use JavaScript to change its src attribute.
What you want is something like this plunker
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Traffic Lights</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script src="script.js"></script>
</head>
<body>
<input type="button" value="click me" onclick="changeLight()">
<div id="light-div" class="light light-0" onclick="changeLight()"></div>
</body>
</html>
.light {
width: 300px;
height: 300px;
display: block;
background-position: center center;
background-repeat: no-repeat;
}
.light-0 {
background-image: url(http://www.drivingtesttips.biz/images/traffic-light-red.jpg);
}
.light-1 {
background-image: url(http://www.drivingtesttips.biz/images/traffic-lights-red-amber.jpg);
}
.light-2 {
background-image: url(http://www.drivingtesttips.biz/images/traffic-lights-green.jpg);
}
.light-3 {
background-image: url(http://assets.digital.cabinet-office.gov.uk/media/559fbe48ed915d1592000048/traffic-light-amber.jpg);
}
var lightSeq = ['light-0', 'light-1', 'light-2', 'light-3'];
var state = 0;
function changeLight() {
state++;
if (state === lightSeq.length)
state = 0;
document.getElementById('light-div').className = 'light ' + lightSeq[state];
}
Really there are a lot of errors in your code both HTML/JS, first hide something then better try to show it-
Still I got something for you, maybe this is what you needed, check the link below-
$(document).ready(function(e){
$('#ab').click(function(e){
//alert(1);
var a = document.getElementsByTagName('img');
for(i=1;i<=a.length;i++){
setTimeout(function(x){
return (function(){
$('img#state_'+x).show();
});
}(i),1000*i)
}
});
});
https://plnkr.co/XGG5PHI6bMP0XJ484rUS?p=preview

Categories