OnMouseEvents Issue - javascript

I am new to coding and am having trouble with the onmouseover and onmouseout events. I am trying to make it so that when my mouse rolls over an element in my navbar it will turn pink. The issue is that everything that I have found uses Jquery and not Javascript. According to a debugger navBarTextReaction is not defined but then how do I go about defining it?
Do I have to set something equal to the function? I'm so confused. Help Please!
For some reason it is working here and it still isn't working when I load it in the browser.
navBarVar = document.getElementById("navBar").classList;
function navBarTextReaction() {
if(navBarVar.contains("makeWhite")) {
navBarVar.remove("makeWhite");
}
else {
navBarVar.add("makeWhite");
}
if(navBarVar.contains("makePink")){
navBarVar.remove("makePink");
}
else {
navBarVar.add("makePink");
}
}
.background {
background: #4F4F52;
}
.navbar1 {
background: #282727;
shadow: 1em 1em #87B4CB;
font-family: Patrick Hand SC;
text-shadow: .01em .01em #171717;
font-size: 1.5em;
text-align: center;
}
.makeWhite {
color: #FFFFFF;
font-weight: bold;
}
.makePink {
color: #FBEBEB;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Cardo|Great+Vibes|Patrick+Hand+SC|Quattrocento" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div class = "background">
<div class = "container-fluid">
<div class = "row">
<div onmouseover = "navBarTextReaction()" onmouseout = "navBarTextReaction()" id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Home Page </div>
<div id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Chord Leading Chart </div>
<div id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Note Game </div>
<div id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Circle of Fifths </div>
</div>
</div>
</div>
</body>
</html>

Lose all the duplicate id attributes and just use CSS classes and the :hover pseudo-class
.navbar1 {
color: #fff;
font-weight: bold;
}
.navbar1:hover {
color: #FBEBEB;
font-weight: normal;
}
<div class="navbar1 col-sm-3">Home Page</div>
<div class="navbar1 col-sm-3">Chord Leading Chart</div>
<div class="navbar1 col-sm-3">Note Game</div>
<div class="navbar1 col-sm-3">Circle of Fifths</div>

<div onmouseover = "navBarTextReaction()" onmouseout = "navBarTextReaction()" id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Home Page </div>
Add () after function names in your HTML and I also corrected the code to use the correct function name.

navBarVar = document.getElementById("navBar").classList;
function navBarTextReaction() {
if(navBarVar.contains("makeWhite")) {
navBarVar.remove("makeWhite");
}
else {
navBarVar.add("makeWhite");
}
if(navBarVar.contains("makePink")){
navBarVar.remove("makePink");
}
else {
navBarVar.add("makePink");
}
}
.background {
background: #4F4F52;
}
.navbar1 {
background: #282727;
shadow: 1em 1em #87B4CB;
font-family: Patrick Hand SC;
text-shadow: .01em .01em #171717;
font-size: 1.5em;
text-align: center;
}
.makeWhite {
color: #FFFFFF;
font-weight: bold;
}
.makePink {
color: #FBEBEB;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Cardo|Great+Vibes|Patrick+Hand+SC|Quattrocento" rel="stylesheet">
<script src="script.js"></script>
</head>
<body>
<div class = "background">
<div class = "container-fluid">
<div class = "row">
<div onmouseover = "navBarTextReaction()" onmouseout = "navBarTextReaction()" id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Home Page </div>
<div id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Chord Leading Chart </div>
<div id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Note Game </div>
<div id = "navBar" class = "navbar1 col-sm-3 makeWhite"> Circle of Fifths </div>
</div>
</div>
</div>
</body>
</html>
navBarTextReation =>navBarTextReaction()

Related

How to get the color of an element which i have clicked or its background color via javascript?

I tried to use EyeDropper API but I think there are some issues on Linux because it requires me to share my screen and Although I shared, I could not get a result. I'm getting this after clicking the button. image
<!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>COLOR PICKER</title>
<!-- GOOGLE FONTS -->
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css2?family=Material+Symbols+Sharp:opsz,wght,FILL,GRAD#20..48,100..700,0..1,-50..200"
/>
<!-- CSS & SCRIPT -->
<link rel="stylesheet" href="style.css" />
<script defer src="./script.js"></script>
</head>
<body class="grid pi-cent">
<div class="container flex-col">
<header class="flex jc-cnt ai-cnt">
<button class="pick-btn">Pick Color</button>
</header>
<article class="flex jc-sb">
<p>Picked Color<s class="plural">s</s></p>
Clear All
</article>
<ul class="grid">
<li class="flex">
<div
class="color"
style="--bg: #000000; width: 15px; height: 15px"
></div>
<p class="clr-code">#0000</p>
</li>
</ul>
</div>
<script>
const pickBtn = document.querySelector(".pick-btn");
const pickColor = async (e) => {
try {
const eDrop = new window.EyeDropper();
const resp = await eDrop.open();
console.log(resp);
} catch (err) {
console.log(err);
}
};
pickBtn.addEventListener("click", pickColor);
</script>
</body>
</html>
You forgot to add click event to the button.
const button = document.querySelector('button');
button.addEventListener('click', () => {
if (!window.EyeDropper) {
resultElement.textContent = 'Your browser does not support the EyeDropper API';
return;
}
const eyeDropper = new EyeDropper();
eyeDropper.open().then((result) => {
console.log(result.sRGBHex);
}).catch((e) => {
console.log(e)
});
})
.green,
.blue,
.red {
cursor: pointer;
margin-bottom: 1rem;
}
.green {
color: green;
}
.blue {
color: blue;
}
.red {
color: red;
}
<div class="green">Green color</div>
<div class="blue">Blue color</div>
<div class="red">Red color</div>
<button>Pick color</button>
As #ourmaninamsterdam mentioned the EyeDropper is experimental and only supported in chromium browsers like edge, chrome, opera
Browser compatibility

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

Set different timers in javascript to show divs

I have this code that makes me able to set a timer to show/hide divs, but i wouls like to adapt it to be able to set different timers, i mean some divs for 2000ms then others for 1500ms. But i don't know how to do as i never code in JS, I tried to adapt idangerous but i cannot make it work either.
EDIT : I FOUND A WAY BY ADDING "IF" STATEMENT IN THE JS ! But still i have like 100 divs, it's a little bit "bad coded" to do it like this in my opinion.
so here is the js :
<script>
$(document).ready(function() {
var images = $('.images')
current = 0;
images.hide();
Rotator();
function Rotator() {
if (current == 1 || current == 3){
$(images[current]).fadeIn('slow').delay(2500).fadeOut('slow');
}
else{
$(images[current]).fadeIn('slow').delay(10).fadeOut('slow');
}
$(images[current]).queue(function() {
current = current < images.length - 1 ? current + 1 : 0;
Rotator();
$(this).dequeue();
});
}
});
</script>
and in the HTML :
<div id="imagescollection">
<div class="images"><!----- 1 ------>
<div class="pam _3-95 _2ph- _2lej uiBoxWhite noborder"><div class="_3-95 _2pim _2lek
_2lel">Anne faure (Brouteur)</div>
<div class="_3-95 _2let"><div><div></div><div>Coucou</div><div></div><div></div></div>
</div>
<div class="_3-94 _2lem">15 janv. 2022 à 08:29</div></div></div>
<div class="images"><!----- 73 ------>
<div class="pam _3-95 _2ph- _2lej uiBoxWhite noborder"><div class="_3-95 _2pim _2lek
_2lel">Sir Perceval</div>
<div class="_3-95 _2let"><div><div></div><div>Salut</div><div></div><div></div></div>
</div>
<div class="_3-94 _2lem">15 janv. 2022 à 08:56</div></div></div>
<div class="images"><!----- 72 ------>
<div class="pam _3-95 _2ph- _2lej uiBoxWhite noborder"><div class="_3-95 _2pim _2lek
_2lel">Anne faure (Brouteur)</div>
<div class="_3-95 _2let"><div><div></div><div>Comment tu vas</div><div></div><div></div>
</div></div>
<div class="_3-94 _2lem">17 janv. 2022 à 07:30</div></div></div>
<div class="images"><!----- 71 ------>
<div class="pam _3-95 _2ph- _2lej uiBoxWhite noborder"><div class="_3-95 _2pim _2lek
_2lel">Sir Perceval</div>
<div class="_3-95 _2let"><div><div></div><div>On se connaît?</div><div></div><div></div>
</div></div>
<div class="_3-94 _2lem">17 janv. 2022 à 11:09</div></div></div>
</div>
Is there a way to adapt this code to be able to set different times for my divs ? Thank you in advance !
If you want to render more divs you can try out this way
index.html
<!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>
<script src="./script.js"></script>
</body>
</html>
style.css
.reveal{
padding: 2rem;
background-color: pink;
margin: 1rem;
transform: translateX(150%);
transition: all 0.5s ease-in-out;
}
body{
overflow-x: hidden;
}
script.js
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
for(var i=0; i<100; i++){
var div = document.createElement('div');
div.classList.add('reveal')
div.innerText = `This is div ${i}`; // here u can use other array which contains the contents
document.body.appendChild(div);
}
var reveals = document.getElementsByClassName('reveal');
for(var i=0; i<reveals.length; i++){
((div)=>{
setTimeout(()=>{
div.style.transform = 'translate(0)';
}, 1000*(i+1));
})(reveals[i]);
}
console.log(reveals)
Its simple
All that you have to do is set different timeouts and change style as you like in the function passed as argument to this setTimeout (reference)
index.html
<!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 id="div1">This is div 1</div>
<div id="div2">This is div 2</div>
<script src="./script.js"></script>
</body>
</html>
style.css
#div1{
padding: 2rem;
background-color: grey;
font-weight: bold;
margin: 1rem;
transform: translateX(150%);
transition: all 0.5s ease-in-out;
}
#div2{
padding: 2rem;
background-color: pink;
margin: 1rem;
transform: translateX(150%);
transition: all 0.5s ease-in-out;
}
body{
overflow-x: hidden;
}
script.js
var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
setTimeout(()=>{div1.style.transform = 'translateX(0)'},1000)
setTimeout(()=>{div2.style.transform = 'translateX(0)'},2000)

Traversing through them DOM

Im having trouble trying to do the following:
When I hit the button(the first time), I want it to select the first box and then change the background to grey, and as the button is being pressed, I want it to jump to the next box and change that box into grey. Help Please!
const boxes = document.querySelector('#boxes');
const button = document.querySelector('button');
button.addEventListener('click', () => {
let firstChild = boxes.firstElementChild;
for (let i = 0; i < boxes.length; i++) {
firstChild.nextElementSibling.style.backgroundColor = 'grey';
}
})
body {
background: rgb(78, 78, 78);
}
.boxes {
height: 600px;
width: 380px;
background: rgb(236, 236, 236);
border-radius: 20px;
}
.box {
height: 100px;
background: rgb(26, 149, 187);
}
<!doctype html>
<html lang="en">
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<!-- My CSS -->
<link rel="stylesheet" href="main.css">
<title>Hello, world!</title>
</head>
<body>
<div class="container boxes mt-5">
<h1 class="text-center mb-4">App.js</h1>
<div id='boxes' class="row justify-content-around">
<div class="col-3 box "></div>
<div class="col-3 box "></div>
<div class="col-3 box "></div>
</div>
<div class="row mt-4 justify-content-around">
<div class="col-3 box "></div>
<div class="col-3 box "></div>
<div class="col-3 box "></div>
</div>
<div class="container text-center mt-4">
<button id="button" type="button" class="btn btn-warning">Submit</button>
</div>
</div>
</body>
</html>
This is one way to do it using closures:
const boxes = document.querySelector('#boxes');
const button = document.querySelector('button');
const createListener = () => {
let counter = 0
return () => {
boxes.children[counter %
boxes.children.length].style.backgroundColor = 'gray'
counter++
}
}
button.addEventListener('click', createListener())
I did not test it but it should work. If you don't understand what's going on please research on closures. It'll be very useful.

Access a Variable within a function in 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>

Categories

Resources