Toggle button onClick method doesn't work [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 2 years ago.
I don't understand why this code doesn't work.
It works on an online platform such as jsfiddle but it doesn't work when I try it on VS Code live server.
This code provide that responsive header. If the size of page less than 1210 pixels navbar not seems. navbar seems if you click the button. Sorry for my english.
https://jsfiddle.net/1n8zv5xL/1/
HTML
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="layout.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="contact.js"></script>
<script src="preparePage.js"></script>
</head>
<body>
<a id="infoButton" class="infoButton" href="info.html"></a>
<a id="bodyButton" class="bodyButton" href="body.html"></a>
<a id="enterButton" class="enterButton" onclick="preparePage(); return false;"></a>
<a id="leaveButton" class="leaveButton" href="leave.html"></a>
<a id="contactButton" class="contactButton" onclick="contact(); return false;"></a>
</body>
<footer>
</footer>
</html>
CSS
#import url("https://db.onlinewebfonts.com/c/b2932945dbc71a0a2a4c03dd305cfe3a?family=Bauhaus");
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
header {
background-color:white;
justify-content: space-between;
display: flex;
align-items: center;
padding: 25px 15%;
height: 100px;
}
li,a,button {
font-family: "Montserrat", sans-serif;
font-weight: 500;
font-size: 16px;
color: black;
text-decoration: none;
}
header h1 {
font-family: "Bauhaus";
color:rgba(0, 136, 169, 1);
font-size: 45px;
}
button {
padding: 9px 25px;
background-color: rgba(0, 136, 169, 1);
border: none;
border-radius: 50px;
cursor: pointer;
transition: all 0.3s ease 0s;
}
button:hover {
background-color: rgba(0, 136, 169, 0.8);
}
html{
overflow-y: scroll;
}
.navbar-links {
list-style: none;
}
.navbar-links li {
display: inline-block;
padding: 0px 20px;
}
.navbar-links li a {
transition: all 0.3s ease 0s;
}
.navbar-links li a:hover {
color: rgba(0, 136, 169, 1);
}
.logo {
width: 500px;
display: flex;
flex-direction: initial;
align-items: center;
justify-content: space-around;
}
.toggle-button {
top: .75rem;
right: 1rem;
display: none;
flex-direction: column;
justify-content: space-between;
width: 30px;
height: 21px;
}
.toggle-button .bar {
height: 3px;
width: 100%;
background-color: black;
border-radius: 10px;
}
#media screen and (max-width:1210px) {
header {
flex-direction: column;
}
.navbar-links {
display: flex;
flex-direction: column;
}
.toggle-button {
display: flex;
}
.navbar-links.active {
display: none;
}
}
JAVASCRÄ°PT
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})

The problem is with the head.
You are including the scripts in head so it will be loaded prior to the document. So, inorder for you to access dom nodes you should listen for the ready event in jquery - or you can move the scripts to the end of the body
Eg:
$(function() {
const toggleButton = document.getElementsByClassName('toggle-button')[0]
const navbarLinks = document.getElementsByClassName('navbar-links')[0]
toggleButton.addEventListener('click', () => {
navbarLinks.classList.toggle('active')
})
})
OR
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="layout.css">
</head>
<body>
<a id="infoButton" class="infoButton" href="info.html"></a>
<a id="bodyButton" class="bodyButton" href="body.html"></a>
<a id="enterButton" class="enterButton" onclick="preparePage(); return false;"></a>
<a id="leaveButton" class="leaveButton" href="leave.html"></a>
<a id="contactButton" class="contactButton" onclick="contact(); return false;"></a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="contact.js"></script>
<script src="preparePage.js"></script>
</body>
<footer>
</footer>
</html>
That should do the trick.

Related

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
);

Toggle button takes two clicks

I have made a toggle button to show some navlinks on mobile screens.
However on the first page load it takes two clicks.
After that point it toggle perfectly fine.
How can I make it so it functions correctly first time?
Heres the script that contains the function.
script.js
function ToggleNavLinks() { /
var navLink = document.getElementsByClassName("nav-links")[0];
if (navLink.style.display === "none") {
navLink.style.display = "flex";
}
else {
navLink.style.display = "none";
}
}
Heres the layout file that contains the front-end element.
I have tested if it was the external script reference and it definitely works.
layout.hbs
<!DOCTYPE html>
<html lang="en">
<head>
<title>{{title}}</title>
<meta charset="utf-8"/> <!-- Charset -->
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<link rel='stylesheet' href='/stylesheets/style.css'/>
<script type="text/javascript" src="/javascripts/script.js"></script>
</head>
<body>
<header>
<nav class="navbar">
<img class="logo" alt="logo" src="images/logo-stock.png">
<a class="nav-toggle" onclick="ToggleNavLinks()" >
<span class="bar"></span>
<span class="bar"></span>
<span class="bar"></span>
</a>
<!-- Links used in the navbar -->
<div class="nav-links">
<ul>
<li>
Home
</li>
<li>
Projects
</li>
<li>
Contact
</li>
</ul>
</div>
</nav>
</header>
<div>
{{{body}}}
</div>
</body>
</html>
Ill also include the stylesheet in case that has anything to do with it.
#import url('https://fonts.googleapis.com/css2?family=Roboto:wght#300&display=swap');
:root {
font-size: 16px;
font-family: 'Roboto', sans-serif;
--text-primary: white;
--text-secondary: #4c6bc1;
--bg-primary: #101316;
--bg-secondary: #181a1d;
}
* {
box-sizing: border-box;
}
body {
background-color: var(--bg-primary);
margin: 0;
padding: 0;
}
body::-webkit-scrollbar {
width: 0.25rem;
}
body::-webkit-scrollbar-track {
background: #181a1d;
}
body::-webkit-scrollbar-thumb {
background: #4c6bc1;
}
.navbar {
justify-content: space-between;
position: relative;
background-color: var(--bg-secondary);
display: flex;
justify-content: space-between;
align-items: center;
}
.navbar img {
width: 250px;
height: 100px;
}
.logo{
max-width: 100%;
height: auto;
}
.navbar-links {
height: 100%;
}
.nav-links ul {
margin: 0;
padding: 0;
display: flex;
}
.nav-links li {
list-style: none;
}
.nav-links li a {
font-size: 1.5rem;
text-decoration: none;
color: white;
padding: 1rem;
display: block;
}
.nav-links li a:hover {
color: #4c6bc1;
}
.nav-toggle {
position: absolute;
top: 1.5rem;
right: 1rem;
display: none;
flex-direction: column;
justify-content: space-between;
height: 21px;
width: 30px;
}
.nav-toggle:hover {
cursor: pointer;
}
.nav-toggle .bar {
height: 3px;
width: 100%;
background-color: white;
border-radius: 10px;
}
#media (max-width: 800px) {
.nav-toggle {
display: flex;
}
.nav-links {
display: none;
width: 100%;
}
.navbar {
flex-direction: column;
align-items: flex-start;
}
.nav-links ul {
width: 100%;
flex-direction: column;
}
.nav-links li {
text-align: center;
}
.nav-links.active {
display: flex;
}
element.style.display === 'none'
is true when the element has an inline style attribute, which includes display: none. Note that this is true regardless of the actual computed style property of the element. You can check it in this example:
console.log(document.querySelector('.test').style.display);
.test {
display: block !important;
}
code {
background-color: #eee;
}
<div style="display: none;" class="test">I haz <code>style.display === 'none'</code>. You are looking at me. Stop staring, it's not nice.</div>
To check the computed property of the display, use
window.getComputedStyle(element).display === 'none'
In conclusion, replace
if (navLink.style.display === "none") {
with
if (window.getComputedStyle(navLink).display === "none") {
It maybe not the problem of Your Javascript. First check your CSS file. Check if the order of your code i.e display tag is already none or flex. Then only it was not working at 1st instance.
It may be like that:
.navlink{
display: none;
}
Change it to :
.navlink{
display: flex;
}

hamburger menu doesn't close when i click

Whenever I click on the hamburger icon the menu opens but when I click on it again it is supposed to get closed... But it's not. I am trying to debug but I have no idea what is going wrong. If anyone knows, please help
// Hamberger menu
const navSearch = document.querySelector('.nav-search');
const navLeft = document.querySelector('.nav-left');
document.querySelector('.toggle').addEventListener('click', () => {
console.log(navSearch.style.display);
console.log('1');
if(navSearch.style.display = "none") {
console.log('2');
navSearch.style.display = "inline-block";
navLeft.style.display = "inline-block";
console.log(navSearch.style.display);
} else if(navSearch.style.display = "inline-block") {
console.log('3');
navSearch.style.display = "none";
navLeft.style.display = "none";
}
console.log('......');
});
// Variables
$website-width: 1280px;
$color-main: #4bbf73;
$color-dark: #343a40;
$color-light: #fff;
$color-lightx2: #f7f7f9;
//General Styles
* {
margin: 0;
padding: 0;
}
body {
background-color: $color-light;
font-family: "Nunito", Arial, Helvetica, sans-serif;
line-height: 1.6;
}
a {
text-decoration: none;
color: $color-light;
}
ul {
list-style: none;
}
h2,
h3,
h4 {
text-transform: uppercase;
}
img {
width: 100%;
}
input {
border: none;
padding: 0.7rem 1rem;
background: $color-lightx2;
&:focus {
outline: none;
}
}
// Utilities
.container {
max-width: $website-width;
padding: 0 1.5rem;
margin: auto;
overflow: hidden;
}
// navbar
header {
background: $color-dark;
height: 100px;
#navbar {
padding-top: 1.3rem;
color: $color-light;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
align-items: center;
.nav-logo {
font-size: 1.5rem;
font-weight: 900;
letter-spacing: 2px;
padding: 0.5rem 1rem;
}
ul {
display: flex;
justify-content: center;
li {
padding-left: 1.5rem;
}
}
input[type="submit"] {
margin-left: 0.4rem;
background-color: inherit;
border: $color-main 2px solid;
color: $color-main;
&:hover {
background-color: $color-main;
color: $color-light;
transition: all 0.2s ease-in-out;
}
}
input[type="text"] {
padding: 0.7rem 1rem;
}
}
.toggle {
position: absolute;
top: 2.2rem;
right: 6rem;
transform: scale(2);
display: none;
}
}
#import 'media';
#media (max-width: 850px) {
header {
height: auto;
#navbar {
flex-direction: column;
align-items: start;
input[type="text"] {
margin: 1rem 0 1.4rem 3rem;
}
ul {
padding-bottom: 1rem;
}
}
.toggle {
display: inline-block;
}
.nav-search,
.nav-left {
display: none;
}
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!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="https://use.fontawesome.com/releases/v5.15.0/css/all.css"
integrity="sha384-OLYO0LymqQ+uHXELyx93kblK5YIS3B2ZfLGBmsJaUyor7CpMTBsahDHByqSuWW+q" crossorigin="anonymous">
<link href="https://fonts.googleapis.com/css2?family=Nunito:wght#300&display=swap" rel="stylesheet">
<link rel="stylesheet" href="scss/style.css">
<title>AllMart</title>
</head>
<body>
<header>
<div class="container">
<nav id="navbar">
<div class="nav-logo">
AllMart
</div>
<div class="nav-search">
<form>
<input type="text" placeholder="Search Product...">
<input type="submit" value="SEARCH">
</form>
</div>
<div class="nav-left">
<ul>
<li id="cart"><i class="fas fa-shopping-cart"></i> CART</li>
<li id="profile"><i class="fas fa-user"></i> SIGN IN</li>
</ul>
</div>
</nav>
<span class="toggle"><i class="fas fa-bars"></i></span>
</div>
</header>
<script src="js/index.js"></script>
</body>
</html>
and this is the output I get whenever I click on the icon
I have no idea what is going wrong if anyone knows, please help
You need to use === or == in if statements, not =, which is the assignment operator. === is preferred because it tests for strict equality (no type conversion).
if(navSearch.style.display === "none")
else if(navSearch.style.display === "inline-block") {

i try to create a navbar but my javascript code doesn't work

so hello i'm trying to create a navbar and things were going pretty well , but when i was working at the responsivity of the navbar my addeventlistener function doesn't work:
here's my html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<link rel="stylesheet" href="style.css">
<script src="app.js"></script>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght#600&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Test Nav</title>
</head>
<body>
<nav class="navbar">
<h4 class="logo">Nav</h4>
<ul class="navlinks">
<li>
<a href="#" >Home</a>
</li>
<li>
<a href="#" >Work</a>
</li>
<li>
<a href="#" >About us</a>
</li>
<li>
<a href="#" >Projects</a>
</li>
</ul>
<div class="burger">
<div class="bar1"></div>
<div class="bar2"></div>
<div class="bar3"></div>
</div>
</nav>
</body>
</html>
my css:
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.navbar{
display: flex;
justify-content: space-around;
align-items: center;
min-height: 8vh;
background-color: black;
font-family: 'Poppins', sans-serif;
}
.logo{
color: white;
font-size: 20px;
text-transform: uppercase;
letter-spacing: 5px;
}
.navlinks{
display: flex;
justify-content: space-around;
width: 30%;
}
.navlinks a:hover{
background-color: rgb(37, 156, 196);
}
.navlinks li{
list-style: none;
}
.navlinks a{
color: white;
text-decoration: none;
letter-spacing: 3px;
font-weight: bold;
font-size: 14px;
}
.burger{
cursor: pointer;
display: none;
}
.burger div{
width: 25px;
height: 2px;
background-color: white;
margin: 5px;
}
#media screen and (max-width:1024px){
.navlinks{
width: 60%;
}
}
#media screen and (max-width:768px){
body{
overflow-x: hidden;
}
.navlinks{
position: fixed;
right: 0px;
height: 92vh;
top: 8vh;
background-color: black;
display: flex;
flex-direction: column;
align-items: center;
width: 50%;
transform: translateX(100%);
transition: transform 0.5s ease-in;
}
.navlinks li{
opacity: 0;
}
.burger{
display: block;
}
}
.nav-active{
transform: translateX(0%);
}
#keyframes navLinkFade{
from{
opacity: 0;
transform: translateX(50px);
}
to{
opacity: 1;
transform: translateX(0px);
}
}
and here's my javascript code:
const navSlide = () => {
const burger = document.querySelector('.burger')
const nav = document.querySelector('.navlinks')
burger . addEventListener('click',()=>{
nav.classList.toggle('nav-active')
})
}
navSlide();
i am pretty new at this forum but i heard that it was the most popular one and my code lines were making me mad so yeah and thanks again for answering my post
glad to see you're new here and decided to join!
Without using jQuery, you can use this:
const navSlide = () => {
const burger = document.querySelector('.burger')
const nav = document.querySelector('.navlinks')
burger . addEventListener('click',()=>{
nav.classList.toggle('nav-active')
})
}
document.addEventListener("DOMContentLoaded", function(event) {
navSlide();
});
Put basically, this code will wait until the page loads (so that all elements exist within the DOM which means document.querySelector will work) and then it attaches the event listener. This is best practice to avoid issues with slow rendering browsers and such without relying on the browser to render the script last.

Pausing Audio in Javascript

I'm trying to make a digital MPC with buttons that trigger different audio clips.
I got the buttons to function and play the audio when clicked once, however, I'm trying to make the audio pause when clicked again.
I've entered my entire code into this post incase anyone wanted to run it, however my issue is in the Javascript file with the "mousedown" function.
If anyone could offer insight I'd appreciate it.
$(document).ready(function() {
var padOne = new Audio('allstar.mp3');
$('.pad-1').mousedown(function() {
padOne.load()
padOne.play();
});
$(window).keydown(function(e) {
var code = e.keyCode;
var kc = String.fromCharCode(e.keyCode);
$("div[data-code='"+code+"']").addClass("active")
console.log(code);
switch(kc) {
case "R":
padOne.load();
padOne.play();
break;
}
});
$(window).keyup(function(e) {
var code = e.keyCode;
$("div[data-code='"+code+"']").removeClass("active");
});
});
#import 'https://fonts.googleapis.com/css?family=Oswald';
html, body {
background: #000000;
height: 100%;
width: 100%;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
overflow: hidden;
font-family: 'Oswald', sans-serif;
}
h1 {
color: #fff;
font-size: 5vw;
letter-spacing: 6px;
}
.pad {
width: 500px;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.box {
width: 100px;
height: 100px;
margin: 10px 0;
box-shadow: 0 8px 6px -6px black;
background-color: #444;
display: flex;
justify-content: center;
align-items: center;
font-size: 20px;
color: rgba(255, 255, 255, 0.4);
user-select: none;
&:hover {
background-color: lighten(#444, 10%);
cursor: pointer;
}
&:active {
background-color: darken(#444, 10%);
transform: scale(1.1);
transition: all .2s;
}
}
.active {
background-color: darken(#444, 10%);
transform: scale(1.1);
transition: all .2s;
}
.pad-1{
background-image: url(../images/shrek.jpg);
background-size:cover;
background-repeat: no-repeat;
background-position: center;
border: 2px solid #ffffff;
}
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Viral Remix</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/normalize/5.0.0/normalize.min.css">
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<h1>VIRAL REMIXER</h1>
<div class="pad">
<div class="box pad-1" data-code="82">R</div>
</div>
<script src='https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js'></script>
<script src="js/scripts.js"></script>
</body>
</html>
I would just use a boolean flag to represent the playing state.
var playing = false;
$('.pad-1').mousedown(function() {
if(!playing) {
play();
} else {
pause();
}
});
function play() {
padOne.load();
padOne.play();
playing = true;
}
function pause() {
padOne.pause();
playing = false;
}

Categories

Resources