Close menu on click outside - Vanilla JS - javascript

I created a side menu, which displays and hides when clicking the menu button. Now, I would like that the menu closes when I click outside the menu, but I cannot figure out how to do it.
I have tried adding a clicklistener to the body, but this disables the menu completely. I also thougt about getting the ID of the clicked element anywhere in the body and close the menu if clickedElement != sideBar && sideBar.style = "200px", but I cannot get it to work. Can someone help me out here? I would like to find a solution without JQuery.
menuBtn.addEventListener("click", function () {
if (sideBar.style.width == "200px") {
sideBar.style.width = "0px";
setTimeout(function () {
menuItems.style.display = "none";
}, 1000);
} else {
sideBar.style.width = "200px";
menuItems.style.display = "block";
}
});

You can add an event listener to the parent container and check if the click's target is inside the element or not, something like:
document.addEventListener("click", (e) => {
if (box.contains(e.target)) {
result.innerHTML = "inside";
} else {
result.innerHTML = "outside";
}
});
#box {
width: 100px;
height: 100px;
background-color: dodgerblue;
}
<div id="box"></div>
<div id="result"></div>

Related

JavaScript and HTML to show or hide an element

I think this is very easy, but I just can't seem to twig it at the moment. I want to use a JavaScript function to set the visibility of an HTML tag.
I realise the below is wrong as hidden doesn't take a boolean. I'm just struggling to click what the easiest way to do it is?
So I have some script like this:
<script>
function evaluateBoolean() {
if (location.hostname.indexOf("someval" > 0) {
return true;
} else {
return false;
}
}
</script>
And I wanted to use it something like this:
<div hidden="evaluateBoolean()">
this will be shown or displayed depending on the JavaScript boolean
</div>
I would recommend doing it by altering the display style in the JavaScript code.
const el = document.getElementById('container');
const btn = document.getElementById('btn');
btn.addEventListener('click', function handleClick() {
if (el.style.display === 'none') {
el.style.display = 'block';
btn.textContent = 'Hide element';
} else {
el.style.display = 'none';
btn.textContent = 'Show element';
}
});
You have a div with id: myDIV
<div id="myDIV" class="card-header">
Hello World
</div>
You then call this Javascript function to show the element:
function showDiv() {
document.getElementById('myDIV').style.display = "block";
}
and this one to hide it:
function hideDiv() {
document.getElementById('myDIV').style.display = "none";
}
Note, that you can hide a div by:
<div id="myDIV" class="card-header" style="display:none">
Hello World
</div>
And then call the function to show it.
You trigger must be outside of the element which you hide. because if hided you cant even clicked. The js function classList toggle would be good.
function evaluateBoolean() {
const d = document.querySelector('.w div');
d.classList.toggle('hide');
}
.w {
height: 40px;
background: yellow;
}
.hide {
display: none;
}
<div class="w" onclick="evaluateBoolean()">
<div> this will be shown or displayed depending on the javascript boolean </div>
</div>
You can't explicitly run js in your html, if you aren't using any framework like angular or react, where property binding is allowed.
For achieving your intentions with js you can use this approch:
Add to your div an id:
<div id="myDiv"> Toggled div </div>
In your js script modify your function evaluateBoleean() to show/hide the element:
function evaluateBoolean() {
const div = document.querySelector("#myDiv");
if (location.hostname.indexOf("someval" > 0) {
div.hidden = true;
} else {
div.hidden = false;
}
There's a very easy option:-->
having a blank text
firsly replace the html code with this:-->
<div hidden="evaluateBoolean()" id="ThingToBeHidden"> this will be shown or displayed depending on the javascript boolean </div>
and put js code:-->
document.getElementById("ThingToBeHidden").innerHTML = "";
So you have assigned the div to have it's special id which none other element has.
So now the js code selects the div with that id and then sets the context of it to blank.
If you want the text to appear again, the js code is:-->
document.getElementById("ThingToBeHidden").innerHTML = "this will be shown or displayed depending on the javascript boolean";
You can hide an element in several ways (using jQuery):
const o = $(cssSelectorForElementToStyle);
$(o).hide();
$(o).toggle();
$(o).css('display', 'none');
$(o).addClass('css_class_for_hiding_stuff');
Here using vanilla JavaScript:
const o = document.querySelector(cssSelectorForElementToStyle);
o.style.display = 'none';
o.classList.add('css_class_for_hiding_stuff');
But your question doesn't point out exactly when you are going to make this check. So let's assume you are going to check the boolean value once when the page is loaded and hide or show a given element according to that value:
$(document).ready(
() => {
if (evaluateBoolean() === true) {
// do nothing in this case
} else {
$('#elementWithThisId').css('display', 'none');
}
}
);
Without jQuery:
document.addEventListener("DOMContentLoaded", function() {
if (evaluateBoolean() === true) {
// do nothing in this case
} else {
document.querySelector('#elementWithThisId').style.display = 'none';
}
});

Remove Click Event only in a specific browser view

I have a Toggle displaying content. I am trying to remove its click event in larger than 600px of browser view. That means the Toggle click functionality should not work in larger view of 600px. Following is the code i used.
HTML:
<div class="trigger">Trigger</div>
<div class="content">This is the Toggle Displaying content</div>
let trigger = document.querySelector(".trigger");
let content = document.querySelector(".content");
mobilefunction=(el)=>{
let cs = window.getComputedStyle(el).display;
if(cs==="none") {el.style.display="block"}
else {el.style.display="none";}
}
responsivemenu=()=> {
let windowwidth = window.innerWidth;
if(windowwidth < 500) {
trigger.addEventListener("click", ()=>{mobilefunction(content)});
}
else {
trigger.removeEventListener("click", ()=>{mobilefunction(content)});
}
}
window.addEventListener("resize", responsivemenu );
responsivemenu();
I am trying to make Click event enable only in mobile and remove it for desktop. Seeking for experts help on this. Thanks in Advance!
I'd recommend to not add/remove the eventlistener but just check inside the listener callback.
By doing this you can drop all the resize handler stuff as the width is validated the second you click.
let trigger = document.querySelector(".trigger");
let content = document.querySelector(".content");
mobilefunction = () => {
if (window.innerWidth >= 500) {
return;
}
let cs = window.getComputedStyle(content).display;
if (cs === "none") {
content.style.display = "block"
} else {
content.style.display = "none";
}
}
trigger.addEventListener("click", mobilefunction);
<div class="trigger">Trigger</div>
<div class="content">This is the Toggle Displaying content</div>

Open & Close Menu with the same button (Closing not working)

I'm trying to make an overlay menu that opens and close with the click of the same menu. I've tried using some solutions I've seen on this forum but the code I currently have only opens the menu and doesn't close it?
document.getElementById("botaomenu").addEventListener("click", toggleNav);
function toggleNav(){
navSize = document.getElementById("myNav").style.width;
if (navSize == 20) {
return close();
}
return open();
}
function open() {
document.getElementById("myNav").style.width = "20%";
}
function close() {
document.getElementById("myNav").style.width = "0";
}
Here is the fiddle: https://jsfiddle.net/Santos1600/j2L7yga5/1/
I've already got the menu working while using a different button to close the menu, but I would prefer it, from a design point of view, if the same button did both actions on click.
there is an error in width calculation
function toggleNav() {
navSize = document.getElementById("myNav").offsetWidth;
if (navSize > 0) {
return close();
}
return open();
}
If you need it to close after clicking on the different entries
you have 2 options:
1) you can close the menu if you click in any link by just adding
onclick="toggleNav();"
to the specific links.
2) Or in a more generic way, add a class on links ex "mylink"
and
document.body.addEventListener('click', function (evt) {
if (evt.target.className === 'mylink') {
toggleNav();
}
}, false);
in your code
Try this: https://jsfiddle.net/reyq2064/
// document.getElementById("botaomenu").addEventListener("click", toggleNav);
function toggleNav() {
navSize = document.getElementById("myNav").style.width;
if (navSize == '20%') {
return close();
}
return open();
}

Javascript -- how to click anywhere on page to hide opened div

I have a javascript that opens up a hidden div:
<script>
function dropdown()
{ document.getElementById("login_dropdown").style.display="block"; }
</script>
The html is:
<div onclick="dropdown()">
<div id="login_dropdown">STUFF</div>
</div>
The CSS is:
<style>
#login_dropdown {
width: 150px;
display:none;
}</style>
Using javascript alone, how can I hide this div when I click anywhere else on the page, excluding the opened DIV itself.
Something like this with vanilljs
document.addEventListener('click', function(event){
const yourContainer = document.querySelector('....');
if(!yourContainer.contains(event.target)) {
//hide things classes.. yourContainer.classList.add('hidden');
}
});
You could do this
var elem = document.getElementById("login_dropdown");
(document.body || document.documentElement).addEventListener('click', function (event) {
// If the element on which the click event occurs is not the dropdown, then hide it
if (event.target !== elem)
elem.style.display="none";
}, false);
function closest(e, t){
return !e? false : e === t ? true : closest(e.parentNode, t);
}
container = document.getElementById("popup");
open = document.getElementById("open");
open.addEventListener("click", function(e) {
container.style.display = "block";
open.disabled = true;
e.stopPropagation();
});
document.body.addEventListener("click", function(e) {
if (!closest(e.target, container)) {
container.style.display = "none";
open.disabled = false;
}
});
#popup {
border: 1px solid #ccc;
padding: 5px;
display: none;
width: 200px;
}
<div id="container">
<button id="open">open</button>
<div id="popup">PopUp</div>
</div>
Something like this:
$("document").mouseup(function(e)
{
var subject = $("#login_dropdown");
if(e.target.id != subject.attr('id'))
{
subject.css('display', 'none');
}
});
works like this. When you click anywhere on the page, the handler fires and compares the ID of the open tab vs the id of the document (which there is none) - so it closes the tab. However, if you click the tab, the handler fires, checks the ID, sees the target is the same and fails the test (thus not closing the tab).

Click on button to toggle display of another div

I have a code that works perfectly to move elements from top, left, right or bottom sides, but seems to be, that it doesn't work with display property, here's my javascript code:
$('#icon-for-search').click(function () {
var targetValue;
if ($('#search-wrapper').css('top') == "0px") {
targetValue = '55px';
} else {
targetValue = '0px';
}
$("#search-wrapper").animate({
top: targetValue
}, 500);
});
I have a button with an id called "icon-for-search" and it toggles perfectly the top value of the #search-wrapper if it's clicked, but if I change it to display: block / none it doesn't work. Any particular reason? could someone explain me?
$('#icon-for-search').click(function () {
var targetValue;
if ($('#search-wrapper').css('display') == "none") {
targetValue = 'block';
} else {
targetValue = 'none';
}
$("#search-wrapper").animate({
display: targetValue
}, 500);
});
jQuery.animate works only with numeric CSS properties. You can just toggle element:
$('#icon-for-search').click(function () {
$('#search-wrapper').fadeToggle('slow');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="icon-for-search">Search Icon</div>
<div id="search-wrapper">Search Wrapper</div>

Categories