Displaying Text When Clicked - javascript

In this project, my aim is to change emoji when I click and also I want "it wasn't funny bro" text to show up when I click to the emoji. When I click to the emoji it changes, but the text does not show up. I followed the same steps, it works for emojis but doesn't work for text. I could not figure out why it's not working.
My code looks like this:
const beginningFace = document.querySelector(".beginning");
const reactionFace = document.querySelector(".reaction");
const beginningText = document.querySelector(".beginningT");
const reactionTextFirst = document.querySelector(".reactionT-first");
const reactionTextSecond = document.querySelector(".reactionT-second");
beginningFace.addEventListener('click',()=>{
if(reactionFace.classList.contains('reaction')){
reactionFace.classList.add('active');
beginningFace.classList.remove('active');
}
});
beginningText.addEventListener('click',()=>{
if(reactionTextFirst.classList.contains('reactionT-first') && reactionTextSecond.classList.contains('reactionT-second')){
reactionTextFirst.classList.add('active');
reactionTextSecond.classList.add('active');
beginningFace.classList.remove('active');
}
});
#import url('https://fonts.googleapis.com/css2?family=Mr+Dafoe&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Exo:wght#900&display=swap');
body, html {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background-color: #202076;
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
perspective: 700px;
}
.beginningT {
display: none;
}
.reactionT-first {
display:none;
position: relative;
font-family: 'Exo';
font-size: 5em;
margin: 0;
transform: skew(-15deg);
letter-spacing: 0.03em;
}
.reactionT-second{
display: none;
font-family: 'Mr Dafoe';
margin: 0;
font-size: 5.5em;
margin-top: -0.6em;
color: white;
text-shadow: 0 0 0.05em #fff, 0 0 0.2em #fe05e1, 0 0 0.3em #fe05e1;
transform: rotate(-7deg);
}
.emoji{
font-size: 18rem;
cursor: pointer;
user-select: none;
}
.beginning{
display: none;
}
.reaction{
display: none;
}
.active{
display: block;
}
<!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>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="emoji beginning active">šŸ˜ƒ</div>
<div class="emoji reaction">šŸ˜</div>
<div class ="text beginningT active" style="font-size: 2rem; font-style: italic; font-family: Verdana, Geneva, Tahoma, sans-serif; color: #F98299;">My reaction after your jokeā†‘ (click to see it!)</div>
<div class="text reactionT-first">IT WASN'T</div>
<div class="text reactionT-second">FUNNY BRO</div>
<script src="app.js"></script>
</body>
</html>

If you want your other text to show up when you click on the emoji, you have to do all the logic inside beginningFace.addEventListener, instead of using two diffent event listeners. I moved the logic, and removed the second click listener.
These lines were missing in the first click listener
reactionTextFirst.classList.add('active');
reactionTextSecond.classList.add('active');
beginningText.classList.remove('active');
const beginningFace = document.querySelector(".beginning");
const reactionFace = document.querySelector(".reaction");
const beginningText = document.querySelector(".beginningT");
const reactionTextFirst = document.querySelector(".reactionT-first");
const reactionTextSecond = document.querySelector(".reactionT-second");
beginningFace.addEventListener('click',()=>{
if(reactionFace.classList.contains('reaction')){
reactionFace.classList.add('active');
beginningFace.classList.remove('active');
reactionTextFirst.classList.add('active');
reactionTextSecond.classList.add('active');
beginningText.classList.remove('active');
}
});
#import url('https://fonts.googleapis.com/css2?family=Mr+Dafoe&display=swap');
#import url('https://fonts.googleapis.com/css2?family=Exo:wght#900&display=swap');
body, html {
width: 100%;
height: 100%;
margin: 0;
overflow: hidden;
background-color: #202076;
}
body {
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
perspective: 700px;
}
.beginningT {
display: none;
}
.reactionT-first {
display:none;
position: relative;
font-family: 'Exo';
font-size: 5em;
margin: 0;
transform: skew(-15deg);
letter-spacing: 0.03em;
}
.reactionT-second{
display: none;
font-family: 'Mr Dafoe';
margin: 0;
font-size: 5.5em;
margin-top: -0.6em;
color: white;
text-shadow: 0 0 0.05em #fff, 0 0 0.2em #fe05e1, 0 0 0.3em #fe05e1;
transform: rotate(-7deg);
}
.emoji{
font-size: 18rem;
cursor: pointer;
user-select: none;
}
.beginning{
display: none;
}
.reaction{
display: none;
}
.active{
display: block;
}
<!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>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="emoji beginning active">šŸ˜ƒ</div>
<div class="emoji reaction">šŸ˜</div>
<div class ="text beginningT active" style="font-size: 2rem; font-style: italic; font-family: Verdana, Geneva, Tahoma, sans-serif; color: #F98299;">My reaction after your jokeā†‘ (click to see it!)</div>
<div class="text reactionT-first">IT WASN'T</div>
<div class="text reactionT-second">FUNNY BRO</div>
<script src="app.js"></script>
</body>
</html>

Related

appendChild does not work on shop website

i was making a website with a function to add products on the homepage. The user entered the name, price and description of the product. but when publishing this product on the homepage, he does not appear. All the code works, except for appendChild()
first html file:
<!DOCTYPE html>
<html lang="pt-br">
<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>Loja</title>
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/f2a567fbc9.js" crossorigin="anonymous"></script>
<script src="scripts.js"defer ></script>
</head>
<body>
<header>
<h1>Loja TemDeTudo</h1>
<ul class="list">
<li><i class="fa-solid fa-plus"></i></li>
<!--<i class="fa-solid fa-xmark"></i>-->
</ul>
</header>
<main class="posts">
<ul class="produtos">
</ul>
</main>
</body>
</html>
second html file:
<!DOCTYPE html>
<html lang="pt-br">
<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>Loja</title>
<link rel="stylesheet" href="style.css">
<script src="https://kit.fontawesome.com/f2a567fbc9.js" crossorigin="anonymous"></script>
<script src="scripts.js" defer></script>
</head>
<body>
<header>
<h1>Loja TemDeTudo</h1>
<ul class="list">
<li><i class="fa-solid fa-xmark"></i></li>
</ul>
</header>
<main class="criaposts">
<input id="nome" type="text" name="" id="" placeholder="nome do produto"><br>
<input id="price" type="number" name="" id="" placeholder="preƧo em R$"><br>
<textarea name="" id="descriĆ§Ć£o" cols="30" rows="10" placeholder="descriĆ§Ć£o do produto"></textarea><br>
<button class="cancel">cancelar</button>
<button class="confirm" id="add">confirmar</button>
</main>
</body>
</html>
css file:
* {
padding:0;
margin: 0;
font-family: sans-serif;
}
header {
display: flex;
padding: 30px;
background-color: purple;
color: whitesmoke;
}
.list {
margin-left: 60%;
font-size: 40px;
list-style-type: none;
color: rgb(255, 255, 177);
transition-duration: .6s;
cursor: pointer;
}
.list:hover {
color:purple;
background-color: rgb(255, 255, 177);
padding: 1rem;
border-radius: 20px;
}
a {
color: inherit;
}
textarea {
resize: none;
margin-top: 1.3rem;
font-size: 20px;
padding: 1rem;
outline: none;
border-radius: 1rem;
border-color: black;
}
.criaposts {
margin-top: 50px;
text-align: center;
position: absolute;
width:100%;
}
input {
font-size: 22px;
border: none;
margin-top: 1.1em;
width: 25%;
outline: none;
padding: .3em;
}
textarea:focus {
border-color: black;
}
button {
margin-top: 20px;
margin: 20px;
font-size: 1.4em;
padding: 1rem;
border-radius: 1rem;
border: none;
cursor: pointer;
color: whitesmoke;
transition-duration: .3s;
}
.confirm {
background-color: rgb(9, 255, 0);
}
.cancel {
background-color: crimson;
}
.cancel:hover , .confirm:hover {
opacity: .8;
font-size: 1.3em;
}
.posts {
margin-top: 3em;
margin-left: 8rem;
}
.produtos {
display: flex;
list-style: none;
}
.detalhes {
margin-top: 5em;
}
p {
margin-top: 1em;
color: rgb(31, 31, 31);
opacity: .95;
}
.produtosPub {
transition-duration: .2s;
padding: 1rem;
width: 15%;
}
.produtosPub:hover {
opacity: .8;
cursor: pointer;
}
js file:
const add = document.querySelector("#add");
const posts = document.querySelector(".posts");
const ancora = document.querySelector("#ancora");
const produtos = document.querySelector(".produtos")
add.addEventListener("click" , () => {
const nomeProdu = document.querySelector("#nome").value;
const price = document.querySelector("#price").value;
const descriƧao = document.querySelector("#descriĆ§Ć£o").value;
if(nomeProdu.length > 25) {
alert("o nome estĆ” muito grande");
ancora.removeAttribute("href");
nomeProdu = "";
}
else if(!nomeProdu || !price || !descriƧao) {
ancora.removeAttribute("href");
alert("Esta faltando informaƧƵes do produto");
nomeProdu = "";
price = "";
descriƧao = "";
}
else {
ancora.setAttribute("href","index.html");
const lista = document.createElement("li");
lista.classList.add("produtosPub");
lista.innerHTML = `<h2>${nomeProdu}</h2>
<div class="detalhes">
<h2>
R$: ${price}
</h2>
<p>
${descriƧao}
</p>
</div>`
produtos.appendChild(lista)
}
})
i don't know why this is happening.
I've already tried changing the appendChild() to the innerHTML and it keep going wrong
Based on your JS code, you don't wait for the page to load fully before running querySelector queries. This could lead to produtos equal to undefined.
Please check the browser's console for errors to check this theory.
Ideally, you should run any JS code after this event is triggered
window.addEventListener('DOMContentLoaded', (event) => {
// your JS initialization code here
});
This will ensure that all the components on the page are created and ready to be accessed via querySelector.
Please let me know if this helps.

Highlight first word in input using javascript?

Hello!
I'm trying to make a terminal like interface, similar to PowerShell or Command Prompt.
I want to highlight the command name that the user inputs.
What I want in to look like:
Is there a possible way to do this with Javascript, CSS and HTML?
I am able to highlight the first word but it looks like this:
I took some code from another post and here is what it looks like for me:
The post: Set background-color of first word in textbox?
//=== MAIN ===\\
$(document).on(
"keydown keyup change",
".terminal-input-area #terminal-input",
function () {
if ($(this).val().length && $(this).val().split(" ").length) {
$(this)
.closest(".terminal-input-area")
.find(".first-word")
.html($(this).val().split(" ")[0])
.show();
} else {
$(this).closest(".terminal-input-area").find(".first-word").hide();
}
}
);
$(document).on("click", ".terminal-input-area .first-word", function () {
$(this).closest(".terminal-input-area").find("#terminal-input").focus();
});
/* ===== FONTS ==== */
#font-face {
font-family: "Fira Code";
src: url("fonts/FiraCode-Regular.ttf");
}
#font-face {
font-family: "Fira Code Retina";
src: url("fonts/FiraCode-Retina.ttf");
}
#font-face {
font-family: "Fira Code Light";
src: url("fonts/FiraCode-Light.ttf");
}
#font-face {
font-family: "Fira Code Medium";
src: url("fonts/FiraCode-Medium.ttf");
}
#font-face {
font-family: "Fira Code Semi-Bold";
src: url("fonts/FiraCode-SemiBold.ttf");
}
#font-face {
font-family: "Fira Code Bold";
src: url("fonts/FiraCode-Bold.ttf");
}
/* ===== VARIABLES ==== */
:root {
--background: #171717;
--text: #aaa;
}
/* ===== STYLES ==== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
}
.terminal-container {
background: var(--background);
cursor: text;
height: 100vh;
overflow-x: hidden;
overflow-y: auto;
}
.terminal-content {
color: var(--text);
display: flex;
flex-direction: column;
font-family: "Fira Code";
font-size: 15px;
line-height: 20px;
padding: 20px;
white-space: pre-wrap;
}
.terminal-input-area {
align-items: center;
display: inline-flex;
width: 100%;
}
.terminal-prompt {
margin-right: 5px;
}
#terminal-input {
background: transparent;
border: 0;
color: var(--text);
font-family: inherit;
font-size: inherit;
white-space: pre-wrap;
outline: none;
width: 100%;
}
.first-word {
color: #F0BF81;
}
<!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>coolterminalthing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="terminal-container" tabindex="-1">
<div class="terminal-content">
<div class="terminal-input-area">
<span class="terminal-prompt">></span>
<div class="form-control first-word"></div>
<input name="input" id="terminal-input" spellcheck="false" autocapitalize="none" autocomplete="off" value="">
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/main.js" defer></script>
<script src="js/prompt.js" defer></script>
</body>
</html>
Thanks.
This will help you!
//=== MAIN ===\\
$("#terminal-input").keyup(
function () {
const [first,...second] = $(this).val().split(" ");
const f = `${first.length?first+" ":""}`
$(this)
.closest(".terminal-input-area")
.find("#first")
.html(f);
$(this)
.closest(".terminal-input-area")
.find("#second")
.html(`${second?second.join(" "):''}`);
}
);
$(document).on("click", ".terminal-input-area .first-word", function () {
$(this).closest(".terminal-input-area").find("#terminal-input").focus();
});
/* ===== FONTS ==== */
#font-face {
font-family: "Fira Code";
src: url("fonts/FiraCode-Regular.ttf");
}
#font-face {
font-family: "Fira Code Retina";
src: url("fonts/FiraCode-Retina.ttf");
}
#font-face {
font-family: "Fira Code Light";
src: url("fonts/FiraCode-Light.ttf");
}
#font-face {
font-family: "Fira Code Medium";
src: url("fonts/FiraCode-Medium.ttf");
}
#font-face {
font-family: "Fira Code Semi-Bold";
src: url("fonts/FiraCode-SemiBold.ttf");
}
#font-face {
font-family: "Fira Code Bold";
src: url("fonts/FiraCode-Bold.ttf");
}
/* ===== VARIABLES ==== */
:root {
--background: #171717;
--text: #aaa;
}
/* ===== STYLES ==== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
height: 100vh;
}
.terminal-container {
background: var(--background);
cursor: text;
height: 100vh;
overflow-x: hidden;
overflow-y: auto;
}
.terminal-content {
color: var(--text);
display: flex;
flex-direction: column;
font-family: "Fira Code";
font-size: 15px;
line-height: 20px;
padding: 20px;
white-space: pre-wrap;
}
.terminal-input-area {
align-items: center;
display: inline-flex;
width: 100%;
}
.terminal-prompt {
margin-right: 5px;
}
#terminal-input {
background: transparent;
border: 0;
font-family: inherit;
font-size: inherit;
white-space: pre-wrap;
outline: none;
width: 100%;
position: absolute;
left: 37px;
color: transparent;
caret-color: white;
}
#first {
color: #F0BF81;
}
<!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>coolterminalthing</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="terminal-container" tabindex="-1">
<div class="terminal-content">
<div class="terminal-input-area">
<span class="terminal-prompt">></span>
<span id ="first"></span>
<p id="second"></p>
<input name="input" id="terminal-input" spellcheck="false" autocapitalize="none" autocomplete="off" value="">
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="js/main.js" defer></script>
<script src="js/prompt.js" defer></script>
</body>
</html>

why does this javascript code work differently? Is there any thing that I am missing?

i dont' get why my javascript code works differently despite it looks like same to me. I am a beginner and I tried to figure out what is wrong and I couldn't. In one method which I have commented the code works in a way it should work while in other it looks like the code is broken. It works in way it shouldn't and I couldn't figure out why it is happening.
let smallCups = document.querySelectorAll(".cup-small")
let liters = document.getElementById("liters")
let percentage = document.getElementById("percentage")
let remained = document.getElementById("remained")
// smallCups.forEach(function (cup, idx) {
// cup.addEventListener("click", function () {
// highLightCups(idx)
// })
// })
// function highLightCups(idx) {
// if (smallCups[idx].classList.contains("full")) {
// idx--
// }
// smallCups.forEach(function (cup, idx2) {
// if (idx2 <= idx) {
// cup.classList.add("full")
// } else {
// cup.classList.remove("full")
// }
// })
// }
smallCups.forEach(function(cup, idx) {
cup.addEventListener("click", function() {
if (smallCups[idx].classList.contains("full")) {
idx--
}
smallCups.forEach(function(cup, idx2) {
if (idx2 <= idx) {
cup.classList.add("full")
} else {
cup.classList.remove("full")
}
})
})
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--border-color: #144fc6;
--fill-color: #6ab3f8;
}
html {
font-size: 62.5%;
/* 1rem = 10px */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-size: 1.6rem;
font-family: "Poppins", sans-serif;
background-color: #3494e4;
display: flex;
flex-direction: column;
align-items: center;
color: #fff;
}
h1 {
margin: 10px 0 0;
}
h3 {
font-weight: 400;
margin: 10px 0;
}
.cup {
background-color: #fff;
border: 4px solid var(--border-color);
color: var(--border-color);
border-radius: 0 0 40px 40px;
height: 330px;
width: 150px;
margin: 30px 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.cup.cup-small {
height: 95px;
width: 50px;
border-radius: 0 0 15px 15px;
background-color: rgba(255, 255, 255, 0.9);
cursor: pointer;
font-size: 14px;
align-items: center;
justify-content: center;
text-align: center;
margin: 5px;
transition: .3s ease;
}
.cups {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
width: 280px;
}
.cup.cup-small.full {
background-color: var(--fill-color);
color: #fff;
}
.remained {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
flex: 1;
transition: .3s ease;
}
.remained span {
font-size: 20px;
font-weight: 600;
}
.remained small {
font-size: 12px;
}
.percentage {
background-color: var(--fill-color);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 3rem;
height: 0;
transition: .3s ease;
}
.text {
text-align: center;
margin: 0 0 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet" />
<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>
<h2>drink water</h2>
<h3>goal : 2 liter</h3>
<div class="cup">
<div class="remained" id="remainded">
<span id="liters">1.5l</span>
<span>remained</span>
</div>
<div class="percentage" id="percentage">20%</div>
</div>
<p class="text">select how many glasses of water that you have drank</p>
<div class="cups">
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
</div>
<script src="https://kit.fontawesome.com/d48313b36e.js" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>
The problem is idx.
In the commented version idx is passed to the function and is passed by value. A local variable (also called idx) is created. Any changes to the value of idx are not persisted between clicks.
In your version the variable idx is captured in a closure by the event handler . Each time the click handler runs it gets the value of the captured variable idx which is being updated by the code. The next time the handler runs it uses the updated value of idx and not the original value.
To fix your version you will have to create a copy of idx e.g. let index = idx; and use the variable index inside the click handler to make sure the value of idx never changes!
let smallCups = document.querySelectorAll(".cup-small")
let liters = document.getElementById("liters")
let percentage = document.getElementById("percentage")
let remained = document.getElementById("remained")
smallCups.forEach(function(cup, idx) {
cup.addEventListener("click", function() {
// use original value of idx but do not update it!
let index = idx;
if (smallCups[index].classList.contains("full")) {
index--
}
smallCups.forEach(function(cup, idx2) {
if (idx2 <= index) {
cup.classList.add("full")
} else {
cup.classList.remove("full")
}
})
})
})
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
:root {
--border-color: #144fc6;
--fill-color: #6ab3f8;
}
html {
font-size: 62.5%;
/* 1rem = 10px */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
body {
font-size: 1.6rem;
font-family: "Poppins", sans-serif;
background-color: #3494e4;
display: flex;
flex-direction: column;
align-items: center;
color: #fff;
}
h1 {
margin: 10px 0 0;
}
h3 {
font-weight: 400;
margin: 10px 0;
}
.cup {
background-color: #fff;
border: 4px solid var(--border-color);
color: var(--border-color);
border-radius: 0 0 40px 40px;
height: 330px;
width: 150px;
margin: 30px 0;
display: flex;
flex-direction: column;
overflow: hidden;
}
.cup.cup-small {
height: 95px;
width: 50px;
border-radius: 0 0 15px 15px;
background-color: rgba(255, 255, 255, 0.9);
cursor: pointer;
font-size: 14px;
align-items: center;
justify-content: center;
text-align: center;
margin: 5px;
transition: .3s ease;
}
.cups {
display: flex;
flex-wrap: wrap;
align-items: center;
justify-content: center;
width: 280px;
}
.cup.cup-small.full {
background-color: var(--fill-color);
color: #fff;
}
.remained {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
text-align: center;
flex: 1;
transition: .3s ease;
}
.remained span {
font-size: 20px;
font-weight: 600;
}
.remained small {
font-size: 12px;
}
.percentage {
background-color: var(--fill-color);
display: flex;
align-items: center;
justify-content: center;
font-weight: bold;
font-size: 3rem;
height: 0;
transition: .3s ease;
}
.text {
text-align: center;
margin: 0 0 5px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#100;200;300;400;500;600;700;800;900&display=swap" rel="stylesheet" />
<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>
<h2>drink water</h2>
<h3>goal : 2 liter</h3>
<div class="cup">
<div class="remained" id="remainded">
<span id="liters">1.5l</span>
<span>remained</span>
</div>
<div class="percentage" id="percentage">20%</div>
</div>
<p class="text">select how many glasses of water that you have drank</p>
<div class="cups">
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
<div class="cup cup-small">250ml</div>
</div>
<script src="https://kit.fontawesome.com/d48313b36e.js" crossorigin="anonymous"></script>
<script src="main.js"></script>
</body>
</html>

How to close dropdown when clicked off of dropdown menu? [duplicate]

This question already has answers here:
How do I detect a click outside an element?
(91 answers)
Closed 9 months ago.
I am having trouble as to how to make the contents of the dropdown menu hide when clicking off of the dropdown menu on the page. I have provided the code below and need some assistance. Please help in explaining the correct javascript code.
<!-- html code -->
<!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>HTML 5 Boilerplate</title>
<link rel="stylesheet" href="styles.css">
<script src="https://kit.fontawesome.com/36947df53d.js" crossorigin="anonymous"></script>
<script src="script.js"></script>
<script src="jquery-3.6.0.min.js"></script>
</head>
<body>
<div class = "header">
<div class = "logo">Logo</div>
<div class = "dropdown">
<div class ="button">
<i class="fa-solid fa-bars" id ="button"></i>
</div>
<div class = "dropdown-content" id = "myDropdown">
<nav>
<ul class ="dropdownMenu">
<li>Home</li>
<li>About</li>
<li>Store</li>
<li>Contact</li>
</ul>
</nav>
</div>
</div>
</div>
</body>
</html>
This is the CSS Code for the webpage.
/* css code */
#import url('https://fonts.googleapis.com/css2?family=Montserrat:wght#100&family=Open+Sans:wght#300;400&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
.header {
height: 80px;
background-color: lightblue;
box-shadow: 0px 3px #888888;
display: flex;
justify-content: space-between;
line-height: 55px;
z-index: 99;
}
ul {
list-style-type: none;
}
ul li {
display: inline-block;
padding: 10px 10px;
}
ul li a {
text-decoration: none;
color: black;
font-family: 'Montserrat', sans-serif;
}
.logo {
padding: 10px 10px;
font-family: 'Montserrat', sans-serif;
font-size: 3em;
}
#button {
display: none;
}
#media only screen and (max-width: 550px) {
body {
padding: 0;
margin: 0;
background-color: lightblue;
}
.header {
display: flex;
flex-direction: column;
/*z-index: 99;*/
}
ul li {
display: flex;
flex-direction: column;
width: 100%;
padding: 0;
}
ul li a {
display: flex;
justify-content: center;
align-items: center;
padding: 0;
margin: 0;
height: 5em;
width: 100%;
text-align: center;
border-bottom: 1px solid black;
color: black;
font-size: 20px;
font-weight: 800;
justify-content: center;
}
a:hover {
background-color: lightblue;
}
#button {
display: inline;
top: 0;
right: 0;
padding: 30px;
/*z-index: 98;*/
position: absolute;
color: black;
}
.dropdown-content {
display: none;
background-color: white;
/*z-index: 97;*/
}
.show {display:block;}
}
This is the javascript code for the webpage.
// JS Code
// Not sure how to close dropdown menu when page is clicked off of dropdown menu on page
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
You can add a click handler on the whole page and toggle the dropdown with it. Though would need some checks and bubbling prevention on the dropdown itself, but this way it should work:
document.documentElement.addEventListener(
'click',
() => document.getElementById("myDropdown").classList.toggle("hide"),
false
);

html javacsript how to change background image of section while on hover?

hey guys i am new to javascript and i am trying to figure out how to change the background image of my section while hovering the respective texts. currently i want to load 3 different backgrounds but i have issues trying to figure out. below is the code im using .do lmk if u have any suggestions. thanks in advance .
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3d model</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Krona+One&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* custom webkit scrollbar
*/
html {
-ms-scroll-snap-type: y mandatory;
scroll-snap-type: y mandatory;
}
body {
overflow-x: hidden;
font-family: 'Krona One', sans-serif;
background-color: rgb(0, 0, 0);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
pointer-events: none;
}
.section {
width: 100%;
height: 100vh;
display: grid;
place-items: center;
scroll-snap-align: center;
user-select: none;
}
h1 {
font-weight: 500;
font-size: 5vw;
text-transform: uppercase;
color: white;
line-height: 100%;
text-align: center;
}
h2 {
font-weight: 500;
font-size: 6vw;
text-transform: uppercase;
-webkit-text-stroke: 1px white;
color: transparent;
}
</style>
</head>
<section class="section">
<h1 id="gold">Gold</h1>
<h2 id="silver">Silver</h2>
<h1 id="blue">Light Blue</h1>
</section>
</body>
</html>
First you need to get the element and then you need to set the backgroundImage property to that element like
var goldElement = document.getElementById('gold');
goldElement.addEventListener('mouseover'), (event)=> { `goldElement.style. backgroundImage = "url('path_to_image')" ` }
And change the background to normal when mouse leave.
goldElement.addEventListener('mouseleave', (event)=> { `goldElement.style. backgroundImage = "url('')" ` });
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3d model</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Krona+One&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* custom webkit scrollbar
*/
html {
-ms-scroll-snap-type: y mandatory;
scroll-snap-type: y mandatory;
}
body {
margin:0;
padding:0;
overflow-x: hidden;
font-family: 'Krona One', sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
pointer-events: none;
}
.section {
width: 100%;
height: 100vh;
display: grid;
place-items: center;
scroll-snap-align: center;
user-select: none;
background-color: rgb(0, 0, 0);
}
h1 {
font-weight: 500;
font-size: 5vw;
text-transform: uppercase;
color: white;
line-height: 100%;
text-align: center;
}
h2 {
font-weight: 500;
font-size: 6vw;
text-transform: uppercase;
-webkit-text-stroke: 1px white;
color: transparent;
}
</style>
</head>
<body>
<section class="section">
<h1 id="gold" onMouseOver="gold()" onMouseOut="leave()">Gold</h1>
<h2 id="silver" onMouseOver="silver()" onMouseOut="leave()">Silver</h2>
<h1 id="blue" onMouseOver="blue()" onMouseOut="leave()">Light Blue</h1>
</section>
<script>
var sect = document.querySelector('section');
function gold(){
sect.style.background = '#FFD700';
}
function silver(){
sect.style.background = '#C0C0C0';
}
function blue(){
sect.style.background = '#ADD8E6';
}
function leave(){
sect.style.background = '#000000';
}
</script>
</body>
</html>
If you want to stay on the color just hovered, then remove the leave function from the above code and from the Tags too.
You can use the :hover property in CSS to add styles only whenever the mouse is over the specific HTML element; and to add an image you can use the CSS property background: url(URL_HERE);
For example, your gold ID can be set to display a background by creating a specific :hover property as such:
#gold:hover {
background: url(" https://via.placeholder.com/600x200.png/FFFF00/");
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>3d model</title>
<style>
#import url('https://fonts.googleapis.com/css2?family=Krona+One&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* custom webkit scrollbar
*/
html {
-ms-scroll-snap-type: y mandatory;
scroll-snap-type: y mandatory;
}
body {
overflow-x: hidden;
font-family: 'Krona One', sans-serif;
background-color: rgb(0, 0, 0);
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
canvas {
position: fixed;
top: 0;
left: 0;
z-index: -1;
pointer-events: none;
}
.section {
width: 100%;
height: 100vh;
display: grid;
place-items: center;
scroll-snap-align: center;
user-select: none;
}
h1 {
font-weight: 500;
font-size: 5vw;
text-transform: uppercase;
color: white;
line-height: 100%;
text-align: center;
}
h2 {
font-weight: 500;
font-size: 6vw;
text-transform: uppercase;
-webkit-text-stroke: 1px white;
color: transparent;
}
#gold:hover {
background: url(" https://via.placeholder.com/600x200.png/FFFF00/");
}
#silver:hover {
background: url(" https://via.placeholder.com/600x200.png/CCCCCC/");
}
#blue:hover {
background: url(" https://via.placeholder.com/600x200.png/0000FF/");
}
</style>
</head>
<body>
<section class="section">
<h1 id="gold">Gold</h1>
<h2 id="silver">Silver</h2>
<h1 id="blue">Light Blue</h1>
</section>
</body>
</html>
For every image, you would need to provide a separate class - if you don't want this behaviour, consider using JavaScript instead to dynamically adjust the background image.

Categories

Resources