Hide elements using drag and drop - javascript

i was wandering how i can hide elements in a div, which has the same class name as another div. i do not want to change the class name, because it will effect my JavaScript. So i want one div acting as like a folder, it is kinda like a drag and drop system. I used a tutorial from Web Dev Simplified. Here is the tutorial if anyone is interested. https://www.youtube.com/watch?v=jfYWwQrtzzY&ab_channel=WebDevSimplified
const draggables = document.querySelectorAll('.draggable')
// create const with class draggable what you can drag
const containers = document.querySelectorAll('.container')
const containerx =document.querySelector('.containerx')
// containers where to drop.
// loop through each pages
draggables.forEach(draggable => {
//DRAGSTRT EVENT
draggable.addEventListener('dragstart',()=> {
draggable.classList.add('dragging')
})//what happends when we start draghging element
// DRAGEND EVENT
draggable.addEventListener('dragend', () => {
draggable.classList.remove('dragging')
})
})
// Allow elements to be dropped in containers
containers.forEach(container=>{
container.addEventListener('dragover', e =>{
e.preventDefault() // enable dropping remove default
const draggable = document.querySelector('.dragging')
//1 element willl have 'dragging' bc one selected
container.appendChild(draggable)
//SORT
const afterElement = getDragAfterElement(container, e.clientY)
if(afterElement ==null){
container.appendChild(draggable)
}else{
container.insertBefore(draggable,afterElement)
}
})
})
//sorting mouse position
function getDragAfterElement(container, y)
{ //every draggable that we are not dragging
const draggableelements = [...container.querySelectorAll('.draggable:not(.dragging)')]
return draggableelements.reduce((closest,child)=> {
const box = child.getBoundingClientRect()
const offset =(( y - box.top) - box.height) / 2 //mouse position between center boxes
if (offset < 0 && offset > closest.offset)
{
return{offset: offset,element: child}
}else{
return closest
}
},{offset: Number.NEGATIVE_INFINITY}).element
}
body{
margin:0;
background-color: rgb(29, 29, 29);
;
}
/* NAV */
/* NAV STRT */
nav {
list-style-type: none;
font-family:sans-serif;
margin: 0;
padding: 0;
width: 240px;
background-color: #3a3a3a;
height: 100%; /*full height */
position:absolute; /* Make it stick, even on scroll */
overflow: auto; /* enable scrolling if the sidenav has too much content */
left: 0;
font-size: 16px;
}
li a {
display: block; /* links as block elements, whole link area click */
color:white;
padding: 8px 1px; /*padding between pages*/
padding-top:20px;
text-decoration: none;
text-align: center;
background-color: #3a3a3a;
}
li h1,h3{
background-color: #3a3a3a;
}
ul{
list-style-type: none;
background-color: #3a3a3a;
}
/* change link color on hover */
li a:hover {
background-color:#555;
color: #F3ECEC;
}
li:hover {
background-color: aqua;
}
.title {
text-align: center;
color:white;
}
.title1
{
text-align: center;
color:white;
background-color: #3C3939;
padding-top: 20px;
}
.divider{
border-top: 3px solid #bbb;
}
/* NAV END */
/* Nav end */
/* FOLDER CONTAINER */
.container {
background-color: #333;
padding: 1rem;
margin-top: 1rem;
position: relative;
left:0;
min-height: 274px;
max-height: 800px;
min-width:1000px;
display: grid;
grid-template-columns: auto auto auto auto;
overflow-y: scroll;
overflow-x: hidden;
}
.draggable{
background-color:rgba(255, 245, 245, 0.945);
padding: 1rem;
margin-top: 1rem;
border:solid black;
cursor: move; /* change cursor */
width:128px;
height: 174px;
display: grid;
}
.draggable.dragging{
opacity: 0.5;
}
.containerx{
background-color: #3a3a3a;
position: absolute;
left:35%;
top: 30%;
height:600px;
}
.containery{
background-color: #3a3a3a;
width: 1032px;
position: relative;
left:35%;
height:400px;
}
/* END FOLDERS */
/* SCROLLBAR */
/* width */
::-webkit-scrollbar {
width: 20px;
}
/* Track */
::-webkit-scrollbar-track {
background: #f1f1f1;
}
/* Handle */
::-webkit-scrollbar-thumb {
background: #888;
}
/* Handle on hover */
::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* SCrollbar end */
<!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="test.css">
<script src="test.js" defer></script>
</head>
<body>
<nav>
<ul>
<li><div class="title"><h1>Organize</h1></div></li>
<li>Folders</li>
<li>Timeline</li>
<li>Pages</li>
<li>Meetings</li>
<li><div class="title1"><h3>documents</h3></div></li>
<li></li>
</ul>
</nav>
<div class="containery">
<div class="container" id="hidden" name="test">
</div>
</div>
<div class="containerx">
<div class="container">
<p class="draggable" draggable="true">3</p>
<p class="draggable" draggable="true">4</p>
<p class="draggable" draggable="true">1</p>
<p class="draggable" draggable="true">2</p>
<p class="draggable" draggable="true">3</p>
<p class="draggable" draggable="true">4</p>
<p class="draggable" draggable="true">1</p>
<p class="draggable" draggable="true">2</p>
</div>
</div>
</body>
</html>

Related

Collapsible side menu with CSS flexbox

I'm trying to create a collapsible sidebar on the left.
I want to set it up real simple: 2 columns which contains of 2 flex boxes, and when a button is pushed: the left flex box increases in width and the tight flexbox just moves with. When the button is clicked again, the flexbox on the left decreases again in side, back to the first state where the menu cannot be seen.
My problem is that I don't know how a click event of a button can control the width size of the flexbox.
What I have now is this:
html
<div>
<button
onClick={handleViewMenu}??
style={{ height: "30px", width: "30px" }}>
</button>
</div>
<div className='container'>
<div className='container-left'>
Left
</div>
<div className='container-right'>
right
</div>
</div>
scss
.container { width: 100vw;
height: 100vh;
display: flex;
&-left {
flex-grow: 0;
flex-shrink: 0;
flex-basis: auto;
// flex: 0.3 0 auto;
// background-color: aqua;
} &-right {
flex: 1 0 auto;
}
}
I just don't know how to deal with the onClick event (where I put the ??. I work in React so I found different things like:
const [sideMenuOpen, setMenuOpen] = useState(false);
const handleViewMenu = () => {
setMenuOpen(!sideMenuOpen);
};
But it should be pretty easy to handle this I think, but I can't find a solution..
Here's a solution that doesn't need javascript by using the :has() pseudo class. Just set the width of the side bar when the checkbox is clicked and if you're using normal flexbox the right hand one will automatically shift to suit. See below. Any questions drop me a comment.
/* essential to add this as there's a default 8px margin */
body {
margin: 0;
}
/* this is also essential to avoid a world of width-based pain */
* {
box-sizing: border-box;
}
/* Just making things pretty here */
nav {
display: flex;
width: 100%;
gap: 1rem;
padding: 0.5rem 1rem;
background-color: purple;
color: white;
}
/*the menu button is basically a hidden check box, we use label to style it as a button */
.menubutton>input {
display: none;
}
/*these toggles the display of the menu button, it works because the label after the input element */
.menubutton>input:checked+label .not-active {
display: none;
}
.menubutton>input:not(:checked)+label .active {
display: none;
}
.container {
display: flex;
width: 100%;
}
.container-left {
background-color: plum;
height: 50vh;
padding: 0.5rem 0.5rem;
border: 1px solid transparent;
width: 3rem;
transition: width 300ms;
}
/* this is the bit that styles the width of the sidebar when the checkbox is checked. */
body:has(.menubutton > input:checked) .container-left {
width: 10rem;
}
/* just style the right box for visibility */
.container-right {
border: 1px solid lightgray;
height: 50vh;
flex-grow: 1;
padding: 0.5rem 0.5rem;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<nav>
<div class='menubutton'><input type='checkbox' id='menubuttoninput'><label for='menubuttoninput'><i class="fa-solid fa-bars not-active"></i><i class="fa-solid fa-xmark active"></i></label></div>
This is a navbar!
</nav>
</div>
<div class='container'>
<div class='container-left'>
Left
</div>
<div class='container-right'>
right
</div>
</div>
If you do need a javascript solution then attach a listener to the checkbox input element and toggle the sidebar class to change the width as below:
window.onload = () => {
document.querySelector('.menubutton input').addEventListener('change', (e) => {
const sidebar = document.querySelector('.container-left');
if (e.target.checked) {
sidebar.classList.add('sidebar-active');
} else {
sidebar.classList.remove('sidebar-active');
}
});
}
/* essential to add this as there's a default 8px margin */
body {
margin: 0;
}
/* this is also essential to avoid a world of width-based pain */
* {
box-sizing: border-box;
}
/* Just making things pretty here */
nav {
display: flex;
width: 100%;
gap: 1rem;
padding: 0.5rem 1rem;
background-color: cornflowerblue;
color: white;
}
/*the menu button is basically a hidden check box, we use label to style it as a button */
.menubutton>input {
display: none;
}
/*these toggles the display of the menu button, it works because the label after the input element */
.menubutton>input:checked+label .not-active {
display: none;
}
.menubutton>input:not(:checked)+label .active {
display: none;
}
.container {
display: flex;
width: 100%;
}
.container-left {
background-color: lightblue;
height: 50vh;
padding: 0.5rem 0.5rem;
border: 1px solid transparent;
width: 3rem;
transition: width 300ms;
}
/* this is the bit that styles the width of the sidebar when the checkbox is checked. We just add this using javascript*/
.sidebar-active {
width: 10rem;
}
/* just style the right box for visibility */
.container-right {
border: 1px solid lightgray;
height: 50vh;
flex-grow: 1;
padding: 0.5rem 0.5rem;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.1/css/all.min.css" integrity="sha512-MV7K8+y+gLIBoVD59lQIYicR65iaqukzvf/nwasF0nqhPay5w/9lJmVM2hMDcnK1OnMGCdVK+iQrJ7lzPJQd1w==" crossorigin="anonymous" referrerpolicy="no-referrer"
/>
<nav>
<div class='menubutton'><input type='checkbox' id='menubuttoninput'><label for='menubuttoninput'><i class="fa-solid fa-bars not-active"></i><i class="fa-solid fa-xmark active"></i></label></div>
This is a navbar!
</nav>
</div>
<div class='container'>
<div class='container-left'>
Left
</div>
<div class='container-right'>
right
</div>
</div>

Click outside a modal to toggle a CSS attribute with JS

When the hamburger menu is open, I am trying to allow a click-off screen to toggle the visibility attribute. The other solutions I have seen I do not understand and have been unable to integrate into my code.
The code thus far will either toggle the visibility on click OR toggle visibility when pushing the menu button. With the click off modal event clicking on the screen (but not the menu button) will open and close the modal menu. If you get rid of the click off modal event then the menu button will work.
const navToggle = document.querySelector(".mobile-nav-toggle");
const primaryNavigation = document.querySelector(".primary-navigation");
let dataVisible = false;
//Reference 1: Click off modal
document.addEventListener("click", function () {
if (dataVisible) {
primaryNavigation.toggleAttribute("data-visible");
dataVisible;
}
});
//Reference 2: Menu button
navToggle.addEventListener("click", function () {
primaryNavigation.hasAttribute("data-visible")
? navToggle.setAttribute("aria-expanded", false)
: navToggle.setAttribute("aria-expanded", true);
primaryNavigation.toggleAttribute("data-visible");
dataVisible;
});
dataVisible = function () {
dataVisible = dataVisible ? false : true;
};
.mobile-nav-toggle {
display: none;
}
#media (max-width: 50em) {
.primary-navigation {
display: none;
/* position: fixed; */
position: fixed;
margin-top: 2em;
width: auto;
max-width: 25rem;
padding: var(--size-300);
background: var(--accent-primary);
border-radius: var(--size-100);
box-shadow: 0 0 0 100em rgba(0, 0, 0, 0.486);
}
.navigation::before[data-overlay] {
content: "";
position: fixed;
inset: 0;
background-image: linear-gradient(rgb(0 0 0 / 0), rgb(0 0 0 / 0.8));
}
.nav-list {
display: block !important;
/* gap: var(--size-400) !important; */
text-align: center;
font-weight: var(--fw-bold);
font-size: 1.5rem !important;
}
.nav-list li {
padding: 0.5rem 7ch;
white-space: nowrap;
}
.nav-list li:hover {
background-color: white;
padding: 0.5rem;
border-radius: 5px;
}
.primary-navigation[data-visible] {
display: block;
}
.mobile-nav-toggle {
display: block;
z-index: 100;
cursor: pointer;
background: blue;
border: 0;
padding: 0.5em;
}
.mobile-nav-toggle .icon-close {
display: none;
}
}
<!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>
</head>
<body>
<div class="section">
<button class="mobile-nav-toggle">Menu</button>
<nav class="primary-navigation" id="primary-navigation">
<div class="nav-logo"> </div>
<div>
<ul role="list" class="nav-list" aria-label="primary">
<li>Services</li>
<li>Work</li>
<li>Blog</li>
<li>About</li>
<li>Buy Now</li>
</ul>
</div>
</nav>
</div>
</body>
</html>

when click on the one dropdown other dropdown will be close

I created a dropdown list Javascript Toggle method. I face a problem a problem. The problem is - After clicking one dropdown, another dropdown still opens. I want others dropdown Will to be closed when I click on dropdown. This happen will be each dropdown. How do I do it?
<html>
<head>
<style>
nav{
width:100%;
height:50px;
background-color:#000;
}
button{
height:50px;
margin-left: 10px;
border:0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
div{
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1{
background-color: rgb(0,0,255);
color: #fff;
}
#myDIV2{
background-color: rgb(0,255,0);
color: #000;
}
.show{
display:block;
}
</style>
</head>
<body>
<nav>
<button onclick="myFunction1()">Dropdown1</button>
<button onclick="myFunction2()">Dropdown2</button>
</nav>
<div id="myDIV1">
This Dropdown for Dropdown 1
</div>
<div id="myDIV2">
This Dropdown for dropdown 2
</div>
<script>
function myFunction1() {
var element = document.getElementById("myDIV1");
element.classList.toggle("show");
}
function myFunction2() {
var element = document.getElementById("myDIV2");
element.classList.toggle("show");
}
</script>
</body>
</html>
here is the solution, all the code is commented.
div1 and div2 are hidden by default...
so with .toggle(): https://developer.mozilla.org/en-US/docs/Web/API/DOMTokenList/toggle
I will add the class .show if there isn't
else I will remove the class from it.
so if the user clicks the first time on the button it will show the div1 then if he reclicked will hide, and this is looped (if he reclick)...
with classList.remove, we will hide the other element (always):
if clicked the button N1 will hide div2
if clicked the button N2 will hide div1
let div1 = document.getElementById("myDIV1");
let div2 = document.getElementById("myDIV2");
function myFunction1() {
div1.classList.toggle("show");
// remove the class for the second div
div2.classList.remove("show");
}
function myFunction2() {
div2.classList.toggle("show");
// remove the class for the first div
div1.classList.remove("show");
}
nav {
width: 100%;
height: 50px;
background-color: #000;
}
button {
height: 50px;
margin-left: 10px;
border: 0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
div {
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1 {
background-color: rgb(0, 0, 255);
color: #fff;
}
#myDIV2 {
background-color: rgb(0, 255, 0);
color: #000;
}
/* this is the class we add and remove or toggle with javascript*/
.show {
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">
<script src="./script.js" defer></script>
</head>
<body>
<!-- navbar -->
<nav>
<button onclick="myFunction1()">Dropdown1</button>
<button onclick="myFunction2()">Dropdown2</button>
</nav>
<!-- 1 -->
<div id="myDIV1">
This Dropdown for Dropdown 1
</div>
<!-- 2 -->
<div id="myDIV2">
This Dropdown for dropdown 2
</div>
</body>
</html>
You can make this a little easier to scale by using one function for all dropdown menus. This function closes all open drop-downs and toggles the target one.
function toggleDropDown(id) {
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
}
function toggleDropDown(id) {
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
}
nav {
width: 100%;
height: 50px;
background-color: #000;
}
button {
height: 50px;
margin-left: 10px;
border: 0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
.dropdown-menu {
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1 {
background-color: rgb(0, 0, 255);
color: #fff;
}
#myDIV2 {
background-color: rgb(0, 255, 0);
color: #000;
}
.show {
display: block;
}
<nav>
<button onclick="toggleDropDown('myDIV1')">Dropdown1</button>
<button onclick="toggleDropDown('myDIV2')">Dropdown2</button>
</nav>
<div class='dropdown-menu' id="myDIV1">
This Dropdown for Dropdown 1
</div>
<div class='dropdown-menu' id="myDIV2">
This Dropdown for dropdown 2
</div>
Here is the same thing, but instead of hard-coding click events, it's better practice to use eventListeners, which get applied through the script after the page loads, like:
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('nav button').forEach(button => {
button.addEventListener('click', e => {
let id = e.target.dataset.dropdown
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
})
})
})
document.addEventListener('DOMContentLoaded', () => {
document.querySelectorAll('nav button').forEach(button => {
button.addEventListener('click', e => {
let id = e.target.dataset.dropdown
document.querySelectorAll('.dropdown-menu').forEach(el => el.id === id ? el.classList.toggle('show') : el.classList.remove("show"));
})
})
})
nav {
width: 100%;
height: 50px;
background-color: #000;
}
button {
height: 50px;
margin-left: 10px;
border: 0;
background-color: transparent;
color: #fff;
cursor: pointer;
}
.dropdown-menu {
display: none;
width: 100%;
height: 300px;
position: absolute;
}
#myDIV1 {
background-color: rgb(0, 0, 255);
color: #fff;
}
#myDIV2 {
background-color: rgb(0, 255, 0);
color: #000;
}
.show {
display: block;
}
<nav>
<button data-dropdown="myDIV1">Dropdown1</button>
<button data-dropdown="myDIV2">Dropdown2</button>
</nav>
<div class='dropdown-menu' id="myDIV1">
This Dropdown for Dropdown 1
</div>
<div class='dropdown-menu' id="myDIV2">
This Dropdown for dropdown 2
</div>

onClick JS not go to top of the page

I have a page with an initial description, followed by 2 buttons, where the user can choose typeA or typeB. They work by "target": when the user clicks typeA comes the content relative to typeA, bellow the buttons; same to typeB.
typeA is the most common selection, then, when the page loads, a javascript emulates the click to typeA and opens respective content. To avoid hidden the initial description, there is another javascript to put the page at the top. Worked on Chrome and Edge, not on Firefox.
I would like to repeat the same process when the user clicks: opens the respective content, but positioning the page at the top, or, at least, showing the buttons. I thought event onClick calling the same js backToTop would worked - but not.
I put an alert on js and enters there but not execute: always keeps the content of the button selected in its better visibility.
I tried:
window.location.href = '#top';
window.scrollBy(0, -500);
document.html.scrollTop = document.documentElement.scrollTop = 0;
without success.
What am I doing wrong?
<head>
<meta charset="UTF-8">
<title>TOP PAGE TEST</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body,html {margin-left:auto; margin-right:auto;width:70%; font-family:verdana; font-size:1.2em;}
.menuFAQ {background:#aaa; font-size:2em; width:100%;}
.menuFAQ ul {list-style-type:none; position:relative; margin-left:-40px; /* to avoid user agent chrome */}
.menuFAQ li {display:inline-block; margin-top:10px; margin-bottom:10px; width:49%; background:#fff; text-align:center; box-shadow:2px 3px 4px 0px rgba(170,170,170,1); font-weight:400; line-height:80px;}
.menuFAQ li a {display:block; color:#020062; background:#fff; font-weight:400; text-decoration:none;}
.menuFAQ li .active,.menuFAQ li:hover a {color:#fff; font-weight:400; background-image:linear-gradient(#165686, #0f3a5a); }
:target {color:#fff;font-size:1em;}
div.items>div:not(:target) {display:none}
div.items>div:target {display:block; margin-left:auto; margin-right:auto; color:#000; border:1px solid #aaa;}
</style>
</head>
<body>
<div id="top">Top Page</div>
<br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5
<div class="menuFAQ">
<ul>
<li><a id="preferedFAQ" onclick="backToTop()" class="target" href="#typeA">TypeA</a></li>
<li><a onclick="backToTop()" class="target" href="#typeB">TypeB</a></li>
</ul>
</div>
<div class="items">
<div id="typeA">
<nav>
A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
<br>[...]
</nav>
</div>
</div>
<div class="items">
<div id="typeB">
<nav>
A long and variable text size to explain TypeB
<p>text1B</p><p>text2B</p><p>text3B</p>
<br>[...]
</nav>
</div>
</div>
<script>
const allTargetLinks = document.querySelectorAll('.target')
allTargetLinks.forEach(targetLink => {
targetLink.addEventListener('click', () => {
allTargetLinks.forEach(targetLink => {
targetLink.classList.remove('active')
})
targetLink.classList.add('active')
})
})
window.onload = function() {assignPreferedFAQ()};
function assignPreferedFAQ() {
document.getElementById("preferedFAQ").click();
backToTop();
};
function backToTop() {
//document.html.scrollTop = document.documentElement.scrollTop = 0;
//document.body.scrollTop = document.documentElement.scrollTop = 0;
document.body.scrollTop = 0;
document.documentElement.scrollTop = 0;
};
</script>
You had a real mess there regarding how you process click events and href attribute, i.e:
You had onclick attribute on your links, and you were adding yet another listener to them in JS
You didn't event.preventDefault() in your function, and default browser behavior when you click on a link is to get you to its href path
I've cleaned up a bit and changed some things. Since we need to prevent default behavior :target selector will no longer work, so instead I did what you've already been doing with links, and added an active class to your content. clickHandler() will now remove and add class active as necessary. At the end just scroll to the top. Here's the snippet:
document.querySelectorAll('.target').forEach(targetLink => targetLink.addEventListener('click', clickHandler, false));
function clickHandler(ev) {
ev.preventDefault(); // prevent browser from automatically scrolling to href pos
if (!ev.currentTarget.classList.contains('active')) {
// disable active elements
document.querySelector('.target.active').classList.remove('active');
document.querySelector('.items div.active').classList.remove('active');
// add class to the clicked on button and its corresponding content tab
ev.currentTarget.classList.add('active');
// to prevent pointless string slicing below, you'd have to store ids somewhere else i.e in the data-id attribute
const id = ev.currentTarget.href.slice(ev.currentTarget.href.lastIndexOf('#') + 1);
document.getElementById(id).classList.add('active');
}
window.scrollTo(0,0);
}
* {
font-family: verdana;
font-size: 1em;
}
.menuFAQ {
background: #aaa;
font-size: 2em;
width: 100%;
}
.menuFAQ ul {
list-style-type: none;
text-align: center;
padding: 0;
/* to avoid user agent chrome */
}
.menuFAQ li {
display: inline-block;
width: 48%;
margin-top: 10px;
margin-bottom: 10px;
background: #fff;
text-align: center;
box-shadow: 2px 3px 4px 0px rgba(170, 170, 170, 1);
font-weight: 400;
line-height: 80px;
}
.menuFAQ li a {
display: block;
color: #020062;
background: #fff;
font-weight: 400;
text-decoration: none;
}
.menuFAQ li .active,
.menuFAQ li:hover a {
color: #fff;
font-weight: 400;
background-image: linear-gradient(#165686, #0f3a5a);
}
div.items>div {
display: none;
}
div.items>div.active {
display: block;
margin-left: auto;
margin-right: auto;
color: #000;
border: 1px solid #aaa;
}
<div id="top">Top Page</div>
<br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5
<div class="menuFAQ">
<ul>
<li><a class="target active" href="#typeA">TypeA</a></li>
<li><a class="target" href="#typeB">TypeB</a></li>
</ul>
</div>
<div class="items">
<div class="active" id="typeA">
<nav>
A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
<br>[...]
</nav>
</div>
</div>
<div class="items">
<div id="typeB">
<nav>
A long and variable text size to explain TypeB
<p>text1B</p>
<p>text2B</p>
<p>text3B</p>
<br>[...]
</nav>
</div>
</div>
Note that instead of artificially clicking at the page load, now your content just loads with class active.
Hope this help you.
< script >
window.onload = function() {
document.getElementById("preferedFAQ").click();
backToTop();
};
function backToTop() {
document.documentElement.scrollTop = document.body.scrollTop = 0;
//alert("enter backToTop");
var elmnt = document.getElementById("top");
var x = elmnt.scrollLeft;
var y = elmnt.scrollTop;
}; <
/script>
body,
html {
margin-left: auto;
margin-right: auto;
width: 70%;
font-family: verdana;
font-size: 1.2em;
}
.menuFAQ {
background: #aaa;
font-size: 2em;
width: 100%;
}
.menuFAQ ul {
list-style-type: none;
position: relative;
margin-left: -40px;
/* to avoid user agent chrome */
}
.menuFAQ li {
display: inline-block;
margin-top: 10px;
margin-bottom: 10px;
width: 49%;
background: #fff;
text-align: center;
box-shadow: 2px 3px 4px 0px rgba(170, 170, 170, 1);
font-weight: 400;
line-height: 80px;
}
.menuFAQ li a {
display: block;
color: #020062;
background: #fff;
font-weight: 400;
text-decoration: none;
}
.menuFAQ li .active,
.menuFAQ li:hover a {
color: #fff;
font-weight: 400;
background-image: linear-gradient(#165686, #0f3a5a);
}
:target {
color: #fff;
font-size: 1em;
}
div.items>div:not(:target) {
display: none
}
div.items>div:target {
display: block;
margin-left: auto;
margin-right: auto;
color: #000;
border: 1px solid #aaa;
}
<div id="top">Top Page</div> <br>textExp1<br>textExp2<br>textExp3<br>textExp4<br>textExp5<br>textExp6<br>textExp7<br>textExp8<br>textExp9<br>textExpA<br>textExpB<br>textExpC<br>textExpD
<br>textExpE
<div class="menuFAQ">
<ul>
<li><a id="preferedFAQ" onclick="backToTop()" class="target" href="#typeA">TypeA</a></li>
<li><a onclick="backToTop()" class="target" href="#typeB">TypeB</a></li>
</ul>
</div>
<div class="items">
<div id="typeA">
<nav>
A long and variable text size to explain TypeA <br>text1A<br>text2A<br>text3A<br>text4A<br>text5A<br>text6A<br>text7A<br>text8A<br>text9A<br>textAA<br>textBA<br>textCA<br>textDA
<br>[...]
</nav>
</div>
</div>
<div class="items">
<div id="typeB">
<nav>
A long and variable text size to explain TypeB
<p>text1B</p>
<p>text2B</p>
<p>text3B</p>
<br>[...]
</nav>
</div>
</di

Vanilla JS left to right toggle animation

I am a newbie to code and I am learning vanilla JS. I created this drawer navigation with a circle that moves from left tor right, but there is an issue. I uploaded the current state here: http://setup.industries/masquarade/
The issue that gets me stuck:
The first click on the hamburger nav icon doesn't open the drawer and the animation is switched. I suspect the problem to be in the if(open) as the open var doesn't truly capture the toggle state with open = header.style.width == '0%' After the initial bug, it works fine. A real head scratcher for me.
If you have other tips for better code, or point out my bad practices, I'd be happy to learn.
--
Edit 1: I have added the full code to this question. I am not sure how I can make the ellipse visible, i linked directly to hosted url.
// open sidenav //
function openNav() {
let header = document.getElementById("header");
let open = header.style.width == '0%'
let width = document.body.clientWidth;
var ellipse = document.getElementById("ellipse");
function moveEllipseRight() {
ellipse.animate([
// keyframes
{ transform: 'translateX(0px)' },
{ transform: 'translateX('+ width + 'px)' }
], {
// timing options
duration: 500,
iterations: 1,
easing: 'ease-in-out',
fill: 'forwards'
});}
function moveEllipseLeft() {
ellipse.animate([
// keyframes
{ transform: 'translateX('+ width + 'px)' },
{ transform: 'translateX(0px)' }
], {
// timing options
duration: 500,
iterations: 1,
easing: 'ease-in-out',
fill: 'forwards'
});}
// open sidenav //
if (open) {
header.style.width = "100%";
moveEllipseRight();
} else {
header.style.width = '0%';
moveEllipseLeft();
}
}
// if (open) {
// ellipse.classList.remove("ellipse_left");
// ellipse.classList.add("ellipse_right");
// } else {
// ellipse.classList.remove("ellipse_right");
// ellipse.classList.add("ellipse_left");
// }
// let ellipse = document.getElementById("ellipse");
// let pos = 0;
// let id = setInterval(frame, 5);
// function myMove() {
// console.log('Hello')
// var ellipse = document.getElementById("ellipse");
// var pos = -200;
// var id = setInterval(frame, 1);
// let width = document.body.clientWidth; // - $('#mydiv').width();
//
// function frame() {
// if (pos == width - 200) {
// clearInterval(id);
// } else {
// pos++;
// ellipse.style.left = pos + "px";
// }
// }
// }
// information tabs //
function openTab(evt, tab) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tab).style.display = "block";
evt.currentTarget.className += " active";
}
html, body {
max-width: 100%;
overflow-x: hidden;
}
body {
background: black;
color: white;
font-family: 'Helvetica Neue', sans-serif;
font-size: 1.2em;
line-height: 1.4em;
}
a {
color: white;
}
.clear {
clear: both; float: none; height: 40px;
}
/* Ellipse */
#ellipse {
position: absolute;
top: 120px;
z-index:99;
animation: 3s linear 0s slide 1;
left: -200px;
}
/*
.ellipse_left {left: -200px;}
.ellipse_right {right: -200px;}
*/
/* Masquarede Logo */
img.masquarade_events {
opacity: 0.3;
position: absolute;
bottom: 20px;
right: 20px;
}
img.masquarade_events:hover {
opacity: 0.9;
}
/* Content */
.content {
margin: 150px 0 0 300px;
width: 700px;
height: 400px;
}
#media screen and (max-width: 992px) {
.content {
margin: 150px 0 0 0;
width: 700px;
height: 400px;
}
}
.date {
font-weight: bold;
margin-bottom: -10px;
}
.location {
}
ul.lineup {
list-style-position: inside;
padding: 0;
list-style-type: none;
width: 100%
overflow: hidden;
margin-bottom: 100px;
}
ul.lineup li {
margin-right: 50px;
line-height: 2.5em;
float: left;
}
/* Buttons */
a.button {
margin-right: 10px;
padding: 10px 50px 10px 50px;
text-decoration: none;
border-radius: 200px;
font-size: 0.7em;
transition: 0.3s;
}
a.white {
background: white;
color: black;
}
a.white:hover {
color: white;
background: #D90E46;
}
a.black {
border: 2px white solid;
color: white;
}
a.black:hover {
border: 2px #FCF454 solid;
color: #FCF454;
}
/* Header */
header {
position: absolute;
background-color: black;
top:0;
left:0;
width: 0;
height: 100%;
z-index: 1;
}
/* Navigation */
header nav {
position: absolute;
top: 100px;
right:300px;
}
nav ul {
list-style-position: inside;
width: 400px;
padding: 0;
list-style-type: none;
font-size: 1em;
}
nav ul li{
border-bottom: 1px solid white;
padding: 10px 0 10px 0;
}
nav ul li:hover{
font-weight: bold;
padding: 10px 0 10px 10px;
}
li.active {
font-weight: bold;
}
nav ul li:first-child{
/* border-top: 1px solid white;*/
}
nav ul li a{
text-decoration: none;
}
nav ul h2{
margin-bottom: 10px;
}
.tabcontent {
display: none;
}
/* Header Icon */
img.icon {
position: absolute;
z-index: 999;
top:60px;
right:70px;
}
/* Display */
.display {
width: 400px;
height: 400px;
position: absolute;
top: 100px;
right:750px;
}
.display p {
margin:0 30px 30px 0;
}
<!doctype html>
<html lang="en">
<head>
<!-- SETUP Industries - FUNCTIONAL DESIGN -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- <link rel="shortcut icon" type="image/png" href="favicon.png"/> -->
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="assets/style.css" />
<link href="https://fonts.googleapis.com/css?family=Heebo:400,700,900" rel="stylesheet">
<!-- JS -->
<script src="assets/javascript.js"></script>
<title>Masquarade Classix 2019</title>
</head>
<body>
<!-- Navigation -->
<!-- Icon -->
<img onclick="openNav()"id="icon" src="http://setup.industries/masquarade/assets/icon.svg" class="icon" width="40" alt="Expand Navigation" />
<header id="header">
<nav>
<ul>
<h2>Information</h2>
<li class="tablinks" onmouseover="openTab(event, 'Tickets')">Tickets and pricing </li>
<li class="tablinks" onmouseover="openTab(event, 'Location')">Location</li>
<li class="tablinks" onmouseover="openTab(event, 'Transportation')">Transportation</li>
<li class="tablinks" onmouseover="openTab(event, 'Amenities')"><a href="#">Ameneties</li>
<li class="tablinks" onmouseover="openTab(event, 'HouseRules')">House rules</li>
<li class="tablinks" onmouseover="openTab(event, 'TermsAndConditions')">Terms and conditions</li>
<li class="tablinks" onmouseover="openTab(event, 'Contact')">Contact</li>
<li class="tablinks" onmouseover="openTab(event, 'Partners')">Partners</li>
</ul>
</nav>
<div class="display">
<div id="Tickets" class="tabcontent">
<h2>Tickets and pricing</h2>
<p>Saturday day tickets cost 45 EUR incl. service costs and 21% BTW. You can buy tickets online via the button below or at one of the resellers listed below.</p>
Buy Tickets
<br><br>
<p style="font-size:0.8em;"> <strong>Paperpoint</strong><br>
3930 Hamont-achel<br><br>
<strong>Dag en nachtwinkel </strong><br>
3900 Overpelt<br><br>
<strong>VDM bvba, Q8 tankstation</strong> <br>
Peer<br><br>
<strong>Frituur De Kromme Draai</strong> <br>
Eksel<br><br>
<strong>’t frituurke</strong> <br>
Haag 22, 3910 Achel<br></p>
</div>
<div id="Location" class="tabcontent">
<h2>Location</h2>
</div>
<div id="Transportation" class="tabcontent">
<h2>Transportation</h2>
</div>
<div id="Amenities" class="tabcontent">
<h2>Amenities</h2>
</div>
<div id="HouseRules" class="tabcontent">
<h2>House Rules</h2>
</div>
<div id="TermsAndConditions" class="tabcontent">
<h2>Terms And Conditions</h2>
</div>
<div id="Contact" class="tabcontent">
<h2>Contact</h2>
</div>
<div id="Partners" class="tabcontent">
<h2>Partners</h2>
</div>
</div>
</header>
<!-- Navigation End -->
<div class="container">
<div id="ellipse" class="ellipse_left">
<img src="assets/ellipse.svg" alt="ellipse" width="400" height="400"/>
</div>
<img class="masquarade_events" src="assets/masquarade_events.png" alt="Masquarade Events" width="125" height=""/>
<div class="content">
<p class="date">25 mei 2019</p>
<p class="location">Hennemeeuwis Neerpelt</p>
<h1>Masquarade Classix </h1>
<ul class="lineup">
<li>Nina Kraviz</li>
<li>Recondite</li>
<li>Mind Against</li>
<li>Âme</li>
<li>Vince Watson</li>
<li>Kölsch</li>
<li>Rodriguez Jr. </li>
<li></li>
</ul>
<div class="clear"></div>
Buy Tickets
More Information
</div>
</div>
</body>
</html>
The value for element.style is set by using either javascript or inline style attribute, css will not set the value for you. Therefore, if you are using a css to style the header's width, the value for header.style.width would be an empty string initially, making the expression header.style.width == '0%' to be falsy.
You can add a console.log(document.getElementById('header').style.width) to check the value yourself.
As a result, the first time you click the hamburger, the else block in the conditional will always be ran.
After the first time you click the hamburger, document.getElementById('header').style.width is now being set through javascript, so the subsequent clicks will behave as expected.
To solve the problem, you can either use an inline style attribute to style your header's width, or you can get the style using javascript with
const headerWidth = getComputedStyle(document.getElementById('header')).width;
const open = headerWidth === '0px' || headerWidth === '0%';
You had your open logic reversed. Simply changing the order of 100% / 0% fixes this.
Improvement tips:
checking the elements state by using a class instead of the actual CSS. (Adding an open class to the element when it is open, and removing it when it is not open)
By doing the above, you can move the manipulation of width to the CSS class open: header.open {width: 100%}
By using "`" and encapsulating your variables in ${} you can get rid of many "+" like so: { transform: `translateX(${width}px)` }
Can be seen in the snippet:
// open sidenav //
function openNav() {
let header = document.getElementById("header");
let open = header.className.includes('open')
let width = document.body.clientWidth;
var ellipse = document.getElementById("ellipse");
function moveEllipseRight() {
ellipse.animate([
// keyframes
{ transform: 'translateX(0)' },
{ transform: `translateX(${width}px)` }
], {
// timing options
duration: 500,
iterations: 1,
easing: 'ease-in-out',
fill: 'forwards'
});}
function moveEllipseLeft() {
ellipse.animate([
// keyframes
{ transform: `translateX(${width}px)` },
{ transform: 'translateX(0)' }
], {
// timing options
duration: 500,
iterations: 1,
easing: 'ease-in-out',
fill: 'forwards'
});}
// open sidenav //
if (open) {
moveEllipseLeft();
header.classList.remove("open");
} else {
moveEllipseRight();
header.classList.add("open");
}
}
// information tabs //
function openTab(evt, tab) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(tab).style.display = "block";
evt.currentTarget.className += " active";
}
html, body {
max-width: 100%;
overflow-x: hidden;
}
body {
background: black;
color: white;
font-family: 'Helvetica Neue', sans-serif;
font-size: 1.2em;
line-height: 1.4em;
}
a {
color: white;
}
.clear {
clear: both; float: none; height: 40px;
}
/* Ellipse */
#ellipse {
position: absolute;
top: 120px;
z-index:99;
animation: 3s linear 0s slide 1;
left: -200px;
}
/*
.ellipse_left {left: -200px;}
.ellipse_right {right: -200px;}
*/
/* Masquarede Logo */
img.masquarade_events {
opacity: 0.3;
position: absolute;
bottom: 20px;
right: 20px;
}
img.masquarade_events:hover {
opacity: 0.9;
}
/* Content */
.content {
margin: 150px 0 0 300px;
width: 700px;
height: 400px;
}
#media screen and (max-width: 992px) {
.content {
margin: 150px 0 0 0;
width: 700px;
height: 400px;
}
}
.date {
font-weight: bold;
margin-bottom: -10px;
}
.location {
}
ul.lineup {
list-style-position: inside;
padding: 0;
list-style-type: none;
width: 100%
overflow: hidden;
margin-bottom: 100px;
}
ul.lineup li {
margin-right: 50px;
line-height: 2.5em;
float: left;
}
/* Buttons */
a.button {
margin-right: 10px;
padding: 10px 50px 10px 50px;
text-decoration: none;
border-radius: 200px;
font-size: 0.7em;
transition: 0.3s;
}
a.white {
background: white;
color: black;
}
a.white:hover {
color: white;
background: #D90E46;
}
a.black {
border: 2px white solid;
color: white;
}
a.black:hover {
border: 2px #FCF454 solid;
color: #FCF454;
}
/* Header */
header {
position: absolute;
background-color: black;
top:0;
left:0;
width: 0;
height: 100%;
z-index: 1;
}
/* Header animation css */
header.open {
width: 100%;
}
/* Navigation */
header nav {
position: absolute;
top: 100px;
right:300px;
}
nav ul {
list-style-position: inside;
width: 400px;
padding: 0;
list-style-type: none;
font-size: 1em;
}
nav ul li{
border-bottom: 1px solid white;
padding: 10px 0 10px 0;
}
nav ul li:hover{
font-weight: bold;
padding: 10px 0 10px 10px;
}
li.active {
font-weight: bold;
}
nav ul li:first-child{
/* border-top: 1px solid white;*/
}
nav ul li a{
text-decoration: none;
}
nav ul h2{
margin-bottom: 10px;
}
.tabcontent {
display: none;
}
/* Header Icon */
img.icon {
position: absolute;
z-index: 999;
top:60px;
right:70px;
}
/* Display */
.display {
width: 400px;
height: 400px;
position: absolute;
top: 100px;
right:750px;
}
.display p {
margin:0 30px 30px 0;
}
<!doctype html>
<html lang="en">
<head>
<!-- SETUP Industries - FUNCTIONAL DESIGN -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- <link rel="shortcut icon" type="image/png" href="favicon.png"/> -->
<!-- CSS -->
<link rel="stylesheet" type="text/css" href="assets/style.css" />
<link href="https://fonts.googleapis.com/css?family=Heebo:400,700,900" rel="stylesheet">
<!-- JS -->
<script src="assets/javascript.js"></script>
<title>Masquarade Classix 2019</title>
</head>
<body>
<!-- Navigation -->
<!-- Icon -->
<img onclick="openNav()"id="icon" src="http://setup.industries/masquarade/assets/icon.svg" class="icon" width="40" alt="Expand Navigation" />
<header id="header">
<nav>
<ul>
<h2>Information</h2>
<li class="tablinks" onmouseover="openTab(event, 'Tickets')">Tickets and pricing </li>
<li class="tablinks" onmouseover="openTab(event, 'Location')">Location</li>
<li class="tablinks" onmouseover="openTab(event, 'Transportation')">Transportation</li>
<li class="tablinks" onmouseover="openTab(event, 'Amenities')"><a href="#">Ameneties</li>
<li class="tablinks" onmouseover="openTab(event, 'HouseRules')">House rules</li>
<li class="tablinks" onmouseover="openTab(event, 'TermsAndConditions')">Terms and conditions</li>
<li class="tablinks" onmouseover="openTab(event, 'Contact')">Contact</li>
<li class="tablinks" onmouseover="openTab(event, 'Partners')">Partners</li>
</ul>
</nav>
<div class="display">
<div id="Tickets" class="tabcontent">
<h2>Tickets and pricing</h2>
<p>Saturday day tickets cost 45 EUR incl. service costs and 21% BTW. You can buy tickets online via the button below or at one of the resellers listed below.</p>
Buy Tickets
<br><br>
<p style="font-size:0.8em;"> <strong>Paperpoint</strong><br>
3930 Hamont-achel<br><br>
<strong>Dag en nachtwinkel </strong><br>
3900 Overpelt<br><br>
<strong>VDM bvba, Q8 tankstation</strong> <br>
Peer<br><br>
<strong>Frituur De Kromme Draai</strong> <br>
Eksel<br><br>
<strong>’t frituurke</strong> <br>
Haag 22, 3910 Achel<br></p>
</div>
<div id="Location" class="tabcontent">
<h2>Location</h2>
</div>
<div id="Transportation" class="tabcontent">
<h2>Transportation</h2>
</div>
<div id="Amenities" class="tabcontent">
<h2>Amenities</h2>
</div>
<div id="HouseRules" class="tabcontent">
<h2>House Rules</h2>
</div>
<div id="TermsAndConditions" class="tabcontent">
<h2>Terms And Conditions</h2>
</div>
<div id="Contact" class="tabcontent">
<h2>Contact</h2>
</div>
<div id="Partners" class="tabcontent">
<h2>Partners</h2>
</div>
</div>
</header>
<!-- Navigation End -->
<div class="container">
<div id="ellipse" class="ellipse_left">
<img src="assets/ellipse.svg" alt="ellipse" width="400" height="400"/>
</div>
<img class="masquarade_events" src="assets/masquarade_events.png" alt="Masquarade Events" width="125" height=""/>
<div class="content">
<p class="date">25 mei 2019</p>
<p class="location">Hennemeeuwis Neerpelt</p>
<h1>Masquarade Classix </h1>
<ul class="lineup">
<li>Nina Kraviz</li>
<li>Recondite</li>
<li>Mind Against</li>
<li>Âme</li>
<li>Vince Watson</li>
<li>Kölsch</li>
<li>Rodriguez Jr. </li>
<li></li>
</ul>
<div class="clear"></div>
Buy Tickets
More Information
</div>
</div>
</body>
</html>

Categories