Count key presses and display them in HTML - javascript

I made a simple "spacebar simulator" game with HTML and JavaScript. Every time the user presses spacebar an image is replaced with another one, and when the key is released it is reset to the original image.
I would like to add a counter to the page, which counts the number of times the user has pressed spacebar. The source code is below:
var myRealUrl = "./assets/spacebar.png";
$("body").on("keydown", function (e) {
if(e.which == 32){
$("#spacebar").attr("src", "./assets/spacebar_pressed.png")
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
var button = document.getElementById('counter'),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
<span id="counter"><p></p></span>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed</p><p id="counter">0</p><p> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>

So set up a page level variable and increment it in the keydown event handler.
Your attempt at the "button" click code didn't work because the p element that needed to be clicked had no content inside of it, so it wasn't rendering on the screen and therefore there was nothing to click on.
Also, you can't have more than one element with the same id and it's invalid to put a p inside of a span.
var counter = 0; // Variable to hold the count
var myRealUrl = "./assets/spacebar.png";
var count = document.getElementById('counter');
$("body").on("keydown", function (e) {
if(e.which == 32){
counter++; // Increment the counter
$("#spacebar").attr("src", "./assets/spacebar_pressed.png");
count.textContent = counter; // Log the count
}
});
$("body").keyup(function (e) {
$("#spacebar").attr("src", myRealUrl)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title></title>
<link href="https://fonts.googleapis.com/css?family=Montserrat:300,400" rel="stylesheet">
<link rel="stylesheet" href="css/stylesheet.css">
<script src="js/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="container">
<div class="title">
<h1>Spacebar Simulator 2018</h1>
</div>
<img src="assets/spacebar.png" id="spacebar">
<p>Pressed <span id="counter">0</span> times.</p>
<footer>
<p>© 2018</p>
</footer>
</div>
<script src="js/spacebar.js"></script>
</body>
</html>

Related

How to reuse a function without refreshing the page

When i use the function to check if number is positive or negative it works fine but when i try to do it again nothing happens i have to refresh the whole page to make it work again. Any help is welcome!
const userNum = document.querySelector(".user-input").value;
const checkBtn = document.querySelector(".check-input");
const result = document.querySelector(".result");
function checkNum() {
if (userNum > 0) {
result.innerHTML = "Positive!!"
}
else if (userNum < 0) {
result.innerHTML = "Negativeee!!"
}
else if (userNum < 0) {
result.innerHTML = "Number is NULL"
}
else {
result.innerHTML = "Enter a Number!!"
}
return false;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="container">
<div class="intro">
<h1>A Program to Check if number is <br></h1>
<h2>Positive, Negative or Null</h2>
</div>
<div class="check-number-type">
<input type="text" class="user-input">
<button onclick="checkNum()" class="check-input">Check</button>
</div>
<div class="show-result">
<p class="result"></p>
</div>
</div>
</body>
<script src="/script.js"></script>
</html>
The reason why you say you have to "reload" the page everytime is because your code that extracts the input value was placed outside of your checkNum function that determines if it's positive or negative.
You only retrieve the input once, when the script starts, instead of getting a fresh copy everytime you enter the checkNum function.
Just move this:
const userNum = document.querySelector(".user-input").value;
Inside the checkNum() function.

Trying to add image changer in js

My goal is to have the image switch once it's been clicked and back again to the original image once the second image has been clicked again. I hope that makes sense. I've been trying this for two days with no success. Any help would be appreciated.
/* global document */
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg')
}
}
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
<!-- <script>
var myHeading = document.querySelector("h1")
myHeading.textContent = 'Be Kind' ;
</script> -->
</body>
I have fixed your code. There is one error in your code i.e., you haven't mentioned the file extension whether its in .jpg or any other format in setAttribute. So let's say if your old-typewriter is in jpg format than this code will work if you have another format of image just replace jpg with that format and try to rerun this code.
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg')
}
}
I have edited complete code and you can replace your code with below code. It will work.
<!DOCTYPE html>
<html lang="en">
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
</body>
<script>
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg');
}
}
</script>
</html>
Holy-moly! So I took "Vipul's" suggestion of wrapping the code in script> and embedding the code in my HTML file which I wasn't doing before and voila. I want to thank all of you for the suggestions made. I hope I can return the favor one day.
Best,
<head> <!-- Content in the head element will not be displayed by browers-->
<meta charset="utf-8">
<title> My Sample webpage</title>
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet" type="text/css">
<link href="stylesheets/mystyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<h1>Hello World !</h1> <!-- the size can be changed with css-->
<!-- <p class="para">It's a start of a new day</p>-->
<img src="images/cactus.jpg" alt="cactus">
<p class="para">Let us try to be</p>
<ul>
<!-- this is an unordered list-->
<li> Kind</li>
<li> Time</li>
<li> Why</li>
<li> Who</li>
</ul>
<p id="quote">The plan is to create a site that looks like this one, which was created by a popular mystery writier.</p>
<button>Change name</button>
<script src="scripts/myscripts.js"> </script>
<script>
var cactusImage = document.querySelector('img');
cactusImage.onclick = function () {
var myImages = cactusImage.getAttribute('src');
if(myImages === 'images/cactus.jpg') {
cactusImage.setAttribute ('src','images/old-typewriter.jpg');
} else {
cactusImage.setAttribute ('src','images/cactus.jpg');
}
}
var myHeading = document.querySelector("h1")
myHeading.textContent = 'Be Kind' ;
-->
This code should work:
index.html
<!doctype html>
<html>
<head>
<title>My Test Page</title>
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<a onclick="switchImg()">
<img src="img1.png" id="img">
</a>
</body>
</html>
script.js
var imgSrc = document.getElementById("img").src
function switchImg() {
if(imgSrc == "img1.png") {
document.getElementById("img").src = "img2.png";
imgSrc = document.getElementById("img").src;
}
}
Just replace the names of the image files.

Keep body scrolled at the bottom unless user scrolls up in javascript

I have a program where the user types in something and then something outputs in the "console." The most recent entered thing stays at the bottom unless the user scrolls up
The body of my document seems to be where I can dd effects like hidden scroll to it. I read another post and used scrollTop and scrollHeight and it is not working.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href = "style.css">
</head>
<body id = "scroll">
<div id="game">
<div id="console">
</div>
</div>
<div id = "command-box">
<div id = "cmd">
<input id = "command" onkeypress = "doAThing(event);">
</div>
</div>
</div>
<script src = "variables.js"></script>
<script src = "code.js"></script>
</body>
</html>
var input = document.querySelector("#command");
var theConsole = document.querySelector("#console");
theConsole.scollTop = theConsole.scrollHeight;
var myScroll = document.getElementById("scroll");
function doAThing(event) {
var theKeyCode = event.keyCode;
if(theKeyCode === 13) acceptCommand();
setInterval(scrollUpdate, 1000);
}
function scrollUpdate() {
myScroll.scrollTop = myScroll.scrollHeight;
}
function acceptCommand() {
var p = document.createElement("p");
if(input.value === "hi") theConsole.append("Hi!", p);
if(input.value === "ping") theConsole.append("Pong!", p);
}

Displaying one of two image (50 50 chance-coin toss) from a click button-javascript

I am trying to display one of two images using a click button using random number generator by assigning each image to an if and else statement. I'm not sure where the problem is. Here is what I have:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Assignment 9</title>
<link href="images/avatar.png" rel="shortcut icon" type="image/png">
<link href="css/stylesheet.css" rel="stylesheet" type="text/css">
<script src="js/javascript.js" type="text/javascript"></script>
<style type="text/css">
.auto-style1 {
text-align: center;
}
</style>
<script type="text/javascript">
</script>
</head>
<body>
<header>
</header>
<aside>
</aside>
<div id="main">
<h1> Arrays and Coditional Statements</h1>
<h2 class="auto-style1">Flip a coin </h2>
<script>
function myFunction1() {
var result = doucment.getElementById("pic");
var x = Math.floor(Math.random() * 2);
console.log(x);
if (x == 0) {
document.getElementById("Coin").innerHTML = "Heads"
result.innerHTML="<img alt=\"the frontside of a coin\" src=\"images/heads.jpg\" />"; }
else {
document.getElementById("Coin").innerHTML = "Tails";
result.innerHTML= "<img alt=\"the backside of a coin\" src=\"images/tails.jpg\" />";
}
}
myFunction1();
</script>
<button type="button" onclick="myFunction1()" id="Coin">CLick ME</button>
<p id="pic"> </p>
</div>
<footer>
</footer>
</body>
</html>
You have a very simple typo. You wrote:
var result = doucment.getElementById("pic");
document is spelled wrong

Undo for div tag

I have div tag with contentEditable = 'true'. When I enter text from my keyboard and then call the undo function (document.execCommand('undo',false, null)), all of the text I entered is deleted. I want to just undo the last character typed. How can I do that?
function doUNDO()
{
document.execCommand('undo',false, null);
}
<!DOCTYPE html>
<html>
<head>
<script src="formulas.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
</head>
<body id="main" spellcheck="false">
<span contenteditable="false">
<button onclick="doUNDO()">UNDO</button>
</span>
<div id = "mainDiv"contenteditable="true">a</div>
</body>
</html>
In doUndo() instead of calling execCommand you could just remove the last character from the div, if it is not empty.
E.g.
function doUNDO() {
var mainDIV = document.getElementById('mainDiv')
mainDIV.innerHTML = mainDIV.innerHTML.substr(0, mainDIV.innerHTML.length - 1);
}

Categories