How to perform action: "if resize() function" , if Width < 990 and .close class is not present (nav class=sidebar ), otherwise NOT perform action if Width < 990 and .close is present (nav class=sidebar close ).
Please understand as I'm new to javascript.. Here's the code below with the example, I can't use only css because the complete code has many other css elements, which would make it impossible to do everything with css, I would like an alternative to using javascript. I already appreciate the help.
I need the javascript to recognize a .close class, if it is activated do nothing, if it is not active and a screen for < 990px, then execute a function to add .close, with that the .sidebar will automatically reduce the size to be responsive without the need to use click text "Close Menu Click"..
<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>
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
.sidebar{
position: fixed;
top: 0;
left: 0;
height: 100%;
width: 260px;
background: red;
z-index: 100;
transition: all 0.5s ease;
}
.sidebar.close{
background: yellow;
width: 80px;
}
.home-section{
position: relative;
background: #E4E9F7;
height: 100vh;
left: 260px;
width: calc(100% - 260px);
transition: all 0.5s ease;
}
.sidebar.close ~ .home-section{
left: 80px;
width: calc(100% - 80px);
}
.textClose{
cursor: pointer;
}
</style>
<body>
<nav >
<ul>
<li>Menu 01</li>
<li><a href="#">Menu 02</a></li>
<li><a href="#">Menu 03</a></li>
</ul>
</nav>
<section >
<div >
<span >Close Menu Click</span>
</div>
<br>
Body Home...
</section>
<script>
let sidebar = document.querySelector(".sidebar");
let sidebarBtn = document.querySelector(".textClose");
console.log(sidebarBtn);
sidebarBtn.addEventListener("click", ()=>{
sidebar.classList.toggle("close");
});
document.addEventListener("DOMContentLoaded", function(event) {
var element = document.querySelector('.sidebar');
function resize() {
if (window.innerWidth < 990 ) {
element.classList.add('close');
} else {
element.classList.remove('close');
}
}
window.onresize = resize;
window.onload = resize;
});
</script>
</body>
</html>
CodePudding user response:
If I understand you correctly you want this:
if (window.innerWidth < 990 && element.classList.contains('close') === false)
Edit:
There should be no loop anymore:
if (window.innerWidth < 990 && element.classList.contains('close') === false) {
element.classList.toggle("close");
}
JSFiddle: https://jsfiddle.net/9zLfwg0h/5/