Access a Variable within a function in Javascript - javascript

I want to Check the woodCount Variable if it is equal to or greater than 25 I want to have a new button appear on the page. For now I just had it console.log true or false.
Sorry if this is really easy or makes no sense but I am new to Javascript. Thanks!
JAVASCRIPT FILE
var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");
gatherWood.onclick = function(){
woodCount++;
wood.innerHTML = woodCount;
}
function fire() {
if woodCount >= 25 {
console.log('True');
}else{
console.log('False');
}
}
HTML FILE
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<meta name="description" content="Game">
<meta name="author" content="SitePoint">
<script src="game.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
Wood = <span id="wood">0</span>
</div>
</body>
</html>

Add a button to the DOM and keep it hidden. When it exceeds the threshold, toggle the display property from hidden to block.
Make sure we call the function where the toggling of style happens in the onclick event handler where incrementation occurs.
var woodCount = 0;
var gatherWood = document.getElementById("gatherWood");
var wood = document.getElementById("wood");
gatherWood.onclick = function() {
woodCount++;
wood.innerHTML = woodCount;
fire();
};
function fire() {
if (woodCount >= 25) {
document.getElementById("higherThan25")
.style.display = "block";
} else {
//console.log("False");
}
}
.woodbtn {
border-style: solid;
border-color: white;
color: white;
padding: 10px 10px;
text-align: center;
font-size: 13px;
cursor: pointer;
float: right;
background-color: transparent;
}
.woodtxt {
text-color: white;
}
body {
background-color: black;
color: white;
}
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Game</title>
<meta name="description" content="Game">
<meta name="author" content="SitePoint">
<script src="game.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div>
<input class="woodbtn" type="button" value="Gather Wood" id="gatherWood" />
<input style="display: none;" class="woodbtn" type="button" value="Higher Than 25" id="higherThan25" />
Wood = <span id="wood">0</span>
</div>
</body>
</html>

Related

How to make a tooltip with the same look and feel as when we add "title" attribute to an element?

I am trying to replicate the look and feel of the tooltip when we add the "title" attribute to an element.
Tooltip should be hovarable
Tooltip should be dismissable by pressing the Esc key
Currently, my custom tooltip is not hoverable. Also the look and feel is not matched with - https://www.w3schools.com/tags/tryit.asp?filename=tryhtml5_global_title
Any help is really appreciated and thanks in advance
const tooltipTrigger = document.querySelector(".tooltip-trigger");
const tooltipText = document.querySelector(".tooltip-text");
tooltipTrigger.addEventListener("mouseenter", showTooltip);
tooltipTrigger.addEventListener("mouseleave", hideTooltip);
tooltipText.addEventListener("keydown", dismissTooltip);
function showTooltip() {
tooltipText.style.visibility = "visible";
}
function hideTooltip() {
tooltipText.style.visibility = "hidden";
}
function dismissTooltip(event) {
if (event.keyCode === 27) {
tooltipText.style.visibility = "hidden";
}
}
.tooltip-text {
visibility: hidden;
position: absolute;
background-color: #000;
color: #fff;
padding: 4px;
z-index: 1;
}
.tooltip-trigger{
cursor: pointer;
}
.tooltip-trigger:hover .tooltip-text {
visibility: visible;
}
<!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.css" />
<title>Tooltip</title>
</head>
<body>
<span class="tooltip-trigger" aria-describedby="tooltip-text"
>Hover over me</span
>
<div id="tooltip-text" class="tooltip-text" role="tooltip">
This is the tooltip text
</div>
<script src="script.js"></script>
</body>
</html>
const tooltipTrigger = document.querySelector(".tooltip-trigger");
const tooltipText = document.querySelector(".tooltip-text");
let timeout = null;
tooltipTrigger.addEventListener("mouseenter", showTooltip);
tooltipTrigger.addEventListener("mouseleave", hideTooltip);
window.addEventListener("keydown", dismissTooltip);
function showTooltip(event) {
timeout = setTimeout(() => {
tooltipText.style.visibility = "visible";
tooltipText.style.left = `${event.clientX}px`
tooltipText.style.top = `${event.clientY}px`
}, 1000)
}
function hideTooltip() {
clearTimeout(timeout);
timeout = null;
tooltipText.style.visibility = "hidden";
}
function dismissTooltip(event) {
if (event.key === 'Escape') {
tooltipText.style.visibility = "hidden";
}
}
.tooltip-text {
visibility: hidden;
position: absolute;
background-color: #000;
color: #fff;
padding: 4px;
z-index: 1;
}
.tooltip-trigger {
cursor: pointer;
}
<!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.css" />
<title>Tooltip</title>
</head>
<body>
<span class="tooltip-trigger" aria-describedby="tooltip-text">Hover over me</span
>
<div id="tooltip-text" class="tooltip-text" role="tooltip">
This is the tooltip text
</div>
<script src="script.js"></script>
</body>
</html>
The ultimate answer is in fact, you can't.
You can't replicate the exact behavior of a tooltip generated by a title attribute, simply because their appearance and behavior can be dramatically different across browsers, devices and OS.
You can certainly try to approach very close what it looks like on a particular browser/device/OS, but won't probably be able to replicate exactly everything everywhere. Note that doing user agent detection to finetune is most often a bad idea.

My h1 keeps repositioning while I update it

Okay so I'm making this thing where I use the reddit api and i get a post number then spit out all the info from it. Now I am making a custom number input and here is images of me using it.
How it looks when i load it
How it looks when i update the number
Here's my code:
const numberText = document.querySelector("#numberText")
const modalOpenBtn = document.querySelector("#numberBtn")
const modal = document.querySelector("#modal")
const done = document.querySelector("#done")
modalOpenBtn.addEventListener("click", () => {
modal.showModal()
})
done.addEventListener("click", () => {
let number = document.querySelector("#number")
number.textContent = numberText.value;
modal.close()
})
// The code below is in another file
const add = document.querySelector('#add');
const subtract = document.querySelector('#subtract');
let number = document.querySelector('#number');
add.addEventListener('click', () => {
number.innerHTML = `<h1>${parseInt(number.textContent) + 1}</h1>`;
})
subtract.addEventListener('click', () => {
if (parseInt(number.textContent) <= 0) {
alert('Cannot subtract from 0');
} else {
number.innerHTML = `<h1>${parseInt(number.textContent) - 1}</h1>`;
}
})
body, h1 {
background: rgb(34, 116, 165);
color: rgb(250, 250, 255);
font-family: 'Dosis', sans-serif;
}
button {
background: none;
border: none;
cursor: pointer;
resize: none;
}
div, button {
display: flex;
justify-content: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance: textfield;
}
<!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">
<title>the most stupidest app ive ever made</title>
<script defer src="input.js"></script>
<script defer src="openModal.js"></script>
<link rel="stylesheet" href="style.css">
<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=Dosis:wght#200;800&display=swap" rel="stylesheet">
</head>
<body>
<!-- intro -->
<h1>the most stupidest app ive ever made</h1>
<p>this app is from a reddit post with random knowledge; enter the number of the reddit post and you'll get it's info:</p><br>
<!-- buttons -->
<div>
<button class="add-subtract"><img src="add.svg" width="50" height="50" title="add" id="add"></button>
<button title="number" id="numberBtn"><h1 id="number">0</h1></button>
<button class="add-subtract"><img src="subtract.svg" width="50" height="50" title="subtract" id="subtract"></button>
</div>
<!-- da modal -->
<dialog id="modal">
<input type="number" id="numberText"><br>
<button id="done"><img src="./check.svg"></button>
</dialog>
</body>
</html>
Ask me any question in the comments regarding the code.
Help is appreciated. Thanks!!!
You should have inspected the layout first. You're adding a new h1 to the existing one. Thats what causing the shift. Instead replace the number inside it.
Just replace this line with
number.innerHTML = `<h1>${parseInt(number.textContent) + 1}</h1>`
to
number.innerHTML = `${parseInt(number.textContent) + 1}`
Since according to your comment you couldn't make this simple fix and say that solution isn't working for you, I'm adding the snippet you shared with the change I mentioned
const numberText = document.querySelector("#numberText")
const modalOpenBtn = document.querySelector("#numberBtn")
const modal = document.querySelector("#modal")
const done = document.querySelector("#done")
modalOpenBtn.addEventListener("click", () => {
modal.showModal()
})
done.addEventListener("click", () => {
let number = document.querySelector("#number")
number.textContent = numberText.value;
modal.close()
})
// The code below is in another file
const add = document.querySelector('#add');
const subtract = document.querySelector('#subtract');
let number = document.querySelector('#number');
add.addEventListener('click', () => {
number.innerHTML = `${parseInt(number.textContent) + 1}`;
})
subtract.addEventListener('click', () => {
if (parseInt(number.textContent) <= 0) {
alert('Cannot subtract from 0');
} else {
number.innerHTML = `${parseInt(number.textContent) - 1}`;
}
})
body, h1 {
background: rgb(34, 116, 165);
color: rgb(250, 250, 255);
font-family: 'Dosis', sans-serif;
}
button {
background: none;
border: none;
cursor: pointer;
resize: none;
}
div, button {
display: flex;
justify-content: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
input[type=number] {
-moz-appearance: textfield;
}
<!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">
<title>the most stupidest app ive ever made</title>
<script defer src="input.js"></script>
<script defer src="openModal.js"></script>
<link rel="stylesheet" href="style.css">
<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=Dosis:wght#200;800&display=swap" rel="stylesheet">
</head>
<body>
<!-- intro -->
<h1>the most stupidest app ive ever made</h1>
<p>this app is from a reddit post with random knowledge; enter the number of the reddit post and you'll get it's info:</p><br>
<!-- buttons -->
<div>
<button class="add-subtract"><img src="add.svg" width="50" height="50" title="add" id="add"></button>
<button title="number" id="numberBtn"><h1 id="number">0</h1></button>
<button class="add-subtract"><img src="subtract.svg" width="50" height="50" title="subtract" id="subtract"></button>
</div>
<!-- da modal -->
<dialog id="modal">
<input type="number" id="numberText"><br>
<button id="done"><img src="./check.svg"></button>
</dialog>
</body>
</html>
You can add position: relative to your navbar.
example for mi code
.navbar.navbar-inverse {
position: relative;
}
<div style="margin-top: 15px;text-align: center;" class="navbar navbar-inverse navbar-fixed-top container">

How can i get specific element with 'document.querySelector' according to 'color' property?

I want to get the 'p' element with red color attribute. To do this i wrote the code below but i get a null result. What am i doing wrong?
test.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./test.css">
<script src="./test.js" defer></script>
<title>test</title>
</head>
<body>
<p id="p1">red</p>
<p id="p2">green</p>
<p id="p3">blue</p>
</body>
</html>
test.js
test.js
"use strict"
let element = document.querySelector("p[color='red']");
console.log(element); // logs null
test.css
#p1 {
color: red;
}
#p2 {
color: green;
}
#p3 {
color: blue;
}
You're trying to select an element based not on its HTML attributes, but on the CSS rules that are applied to it. This can't be done with a plain querySelector.
For the general case, iterate over all possibly matching elements and call getComputedStyle on each to find the one that matches:
const p = [...document.querySelectorAll('p')]
.find(p => window.getComputedStyle(p).color === 'rgb(255, 0, 0)');
console.log(p);
#p1 {
color: red;
}
#p2 {
color: green;
}
#p3 {
color: blue;
}
<p id="p1">red</p>
<p id="p2">green</p>
<p id="p3">blue</p>
Note that for color, you need to use rgb syntax.

the purpose of this code is to add an article at the end of the page, but the broblem is that appear then it desappear

the purpose of this code is to add an article at the end of the page, but the broblem is that appear then it desappear.please help me to figur it out :)
const button = document.getElementById("buttad");
function addNewArticle() {
const fragment = document.createDocumentFragment();
const header = document.createElement("p");
header.textContent ="Ferhane riyadh ";
const text = document.createElement("p");
text.textContent ="Ferhane riyadh ";
fragment.appendChild(header);
fragment.appendChild(text);
document.body.appendChild(fragment);
}
button.addEventListener("click", addNewArticle);
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>adding articles</title>
</head>
<body>
<div>
<form>
<input type="text" name="title" id="title" placeholder="TAP YOUR TITLE" style="display:block; margin-bottom: 5px; margin-left:8px;">
<input type="text" name="description" id="description" placeholder="DESCRIPTION" style="display:block; margin-left:8px;">
<button id="buttad" style="padding:3px; position:absolute; left:12%; margin-top:12px; background-color: black; color: white; outline: none; border: black 1px solid; cursor: pointer ">ADD</button>
</form>
</div>
</body>
</html>
This is because you are using a form without preventing the submit of it. There is no need for the form here, and by default it will submit to the same page it's on, causing a window reload.
This has been discussed here: How to prevent form from being submitted?

How to display javascript variables

I have looked up a question on the website (How to display javascript variables in a html page without document.write)
But when executing it in my own coding program it does not work. Hope you can help out!
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset ="UTF-8">
<meta name="viewport" content="width=device-width">
<style type="text/css">
html {
font-family: sans-serif;
font-size: 16px;
}
h1 {
margin: 1em 0 0.25em 0;
}
input[type=text] {
padding: 0.5em;
}
.jsValue, .jqValue {
color: red;
}
</style>
</head>
<body>
<!-- This <input> field is where I'm getting the name from -->
<label>Enter your name: <input class="name" type="text" value="World"/></label>
<!-- Plain Javascript Example -->
<h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>
<!-- jQuery Example -->
<h1>jQuery Example</h1>Hello <span class="jqValue">World</span>
<script>
//https://stackoverflow.com/questions/9689109/how-to-display-javascript-variables-in-a-html-page-without-document-write
// Plain Javascript Example
var $jsName = document.querySelector('.name');
var $jsValue = document.querySelector('.jsValue');
$jsName.addEventListener('input', function(event)){
$jsValue.innerHTML = $jsName.value;
}, false);
</script>
</body>
</html>
Because you have syntax error.. check the console.
Correct code should be:
$jsName.addEventListener('input', function(event){
$jsValue.innerHTML = $jsName.value;
}, false);

Categories

Resources