I want to show a div on link click and hide if click outside the div.
The script is not working.
I cant close side bar by pressing outside the div.
Here is my code
<body>
<div id="mySidenav" class="sidenav ">
×
ITEM 1
ITEM 2
ITEM 3
ITEM 4
</div>
<!-- Use any element to open the sidenav -->
<span onclick="openNav()" style="cursor: pointer; background: green; border: 1px solid black; padding: 5px;">Click me to get the right sidebar.</span>
<!-- Add all page content inside this div if you want the side nav to push page content to the right (not used if you only want the sidenav to sit on top of the page -->
<div id="main">
... rest of the content ...
</div>
</body>
This is my javascript functions :
<script type="text/javascript">
/* Simple appearence with animation AN-1*/
function openNav() {
document.getElementById("mySidenav").style.width = "934px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.body.style.backgroundColor = "white";
}
$(document).mouseup(function(e){
var container = $("#mySidenav");
// If the target of the click isn't the container
if(!container.is(e.target) && container.has(e.target).length === 0){
container.hide();
}
});
/* Simple appearence with animation AN-1*/
</script>
<!-- container -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/js/bootstrap.bundle.min.js"
integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous">
</script>
</body>
Here's an example of how you can use event.stopPropagation(). This will allow you to have your $(document).click() function which will close the sideNav, and also prevent that from happening when someone clicks in the sideNav.
https://api.jquery.com/event.stoppropagation/
$(document).click(function() {
console.log('doc clicked');
})
$('.sideNav').click(function(e) {
console.log('box clicked');
e.stopPropagation();
})
.sideNav {
width: 200px;
height: 400px;
background-color: #ccc;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class='sideNav'></div>
I got your mouseup handler working by changing container.hide() to closeNav().
Here is an example by modifying your code:
function openNav() {
document.getElementById("sidebar").style.width = "200px";
document.body.style.backgroundColor = "rgba(0,0,0,0.4)";
}
function closeNav() {
document.getElementById("sidebar").style.width = "75px";
document.body.style.backgroundColor = "white";
}
$(document).click(function(e) {
var container = $("#sidebar");
// If the target of the click isn't the container
if (!container.is(e.target) && !container.has(e.target).length) {
closeNav()
}
});
closeNav()
#sidebar {
background-color: #cccccc;
width: 75px;
height: 100%;
position: fixed;
transition: width 750ms;
}
.content {
margin-left: 75px;
display: flex;
height: 100vh;
}
body {
margin: 0;
transition: background-color 750ms;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="sidebar">
<button onclick="openNav()">Open</button>
<br/> Your sidebar content here!
</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Volutpat ac tincidunt vitae semper quis lectus nulla at volutpat. Accumsan in nisl nisi scelerisque eu ultrices. Ornare suspendisse
sed nisi lacus. Massa tempor nec feugiat nisl pretium fusce id velit.
</div>
Related
how to hover on one element when scrolling. If you don't know how it's done, please tell me at least what it's called. There is a similar effect here. link
searched on many forums. Because I don't know what it's called, that's why I couldn't find it
If you want to know how it works I leave you my implementation of this feature (not perfect) with some comments
//add event on scroll on the window element and trigger scrollLeftAnimation function
window.addEventListener("scroll", scrollLeftAnimation);
function scrollLeftAnimation() {
//get each element who have scrollLeftAnimation class
let scrollLeftAnimationElements = document.querySelectorAll(".scrollLeftAnimation");
//for each scrollLeftAnimation element, call updateAnimation
scrollLeftAnimationElements.forEach(SectionElement => updateAnimation(SectionElement));
function updateAnimation(SectionElement) {
let ContentElement = SectionElement.querySelector(".animationContent");
//get the top value of element
//for reference see https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect
let y = ContentElement.getBoundingClientRect().y;
//get a pourcent of scrolling
let pourcent = Math.abs(SectionElement.getBoundingClientRect().y / (SectionElement.clientHeight - ContentElement.clientHeight));
let ContentOverflowElement = SectionElement.querySelector(".animationContentOverflow");
//get the scroll left available distance
let ContentOverflowElementLeftScrollDistance = ContentOverflowElement.scrollWidth - ContentOverflowElement.clientWidth;
if (y == 0) {
//if element is sticky then scroll left = (max scroll left available distance) * (pourcent of scrolling)
ContentOverflowElement.scrollLeft = ContentOverflowElementLeftScrollDistance * pourcent;
} else if (y > 0) {
//if element is bellow, then scroll left = 0
ContentOverflowElement.scrollLeft = 0;
} else {
//if element is above, then scroll left = max scroll left available distance
ContentOverflowElement.scrollLeft = ContentOverflowElementLeftScrollDistance;
}
}
}
section {
height: 100vh;
}
/*Main CSS*/
section.scrollLeftAnimation {
/*The more the ratio between the height of
.scrollLeftAnimation compared to .animationContent
the more it will be necessary to scroll*/
height: 300vh;
}
section.scrollLeftAnimation .animationContent {
/* using sticky to keep the element inside the window*/
position: sticky;
top: 0;
height: 100vh;
}
.animationContent .animationContentOverflow {
height: 25vh;
overflow: hidden;
}
/*CSS for card element*/
.animationContent ul {
margin: 0;
padding: 0;
height: 100%;
white-space: nowrap;
}
.card {
border: 1px solid black;
height: 100%;
width: 35vw;
background-color: gray;
display: inline-block;
}
.card + .card {
margin-left: 50px;
}
.card:first-child {
margin-left: 25px;
}
.card:last-child {
margin-right: 25px;
}
<section style="background-color: darkorchid;">Regular section 1</section>
<section class="scrollLeftAnimation" style="background-color: deeppink;">
<div class="animationContent">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet consectetur adipiscing elit pellentesque habitant. In fermentum posuere urna nec.</p>
<div class="animationContentOverflow">
<ul>
<li class="card">card 1</li>
<li class="card">card 2</li>
<li class="card">card 3</li>
<li class="card">card 4</li>
</ul>
</div>
</div>
</section>
<section style="background-color: violet;">Regular section 4</section>
<section style="background-color: silver;">Regular section 5</section>
<section class="scrollLeftAnimation" style="background-color: peru;">
<div class="animationContent">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Lorem ipsum dolor sit amet consectetur adipiscing elit pellentesque habitant. In fermentum posuere urna nec. Posuere ac ut consequat semper viverra nam libero justo laoreet. Tristique risus nec feugiat in fermentum posuere urna nec tincidunt. Rhoncus dolor purus non enim praesent elementum facilisis leo. Turpis tincidunt id aliquet risus feugiat in ante metus.</p>
<div class="animationContentOverflow">
<ul>
<li class="card">card 1</li>
<li class="card">card 2</li>
<li class="card">card 3</li>
<li class="card">card 4</li>
</ul>
</div>
</div>
</section>
<section style="background-color: orange;">Regular section 7</section>
I am building a reactJS application in which the navbar is present only in middle column. But when I switch to mobile view, due to bootstrap by default the navbar comes below the first column. If I try to change the position to fixed-top it extends to all columns. I need it to stay in the middle in both lg and md views, but in small screens it should come above the first column. I have attached a screenshot.
This is the application in desktop view
This is in mobile view
How can I make this change in my website ??
You need to implement a combination of css, media breakpoints, and some pure JS. Here's a working example.
Switch the nav to position: fixed; at the mobile breakpoint, which I assume is 768.
Because fixed will remove it from the regular HTML element flow and place it overtop of other items, to account for that shift, add margin-top to the first container .element-one that is the same height as the nav + a few extra pixels to account for spacing.
var navBreakpoint = 768,
el1 = document.body.querySelector('.element-one');
navHeight();
window.addEventListener('resize', function(){
navHeight();
});
function navHeight(){
var mt = document.body.querySelector('nav').offsetHeight + 10,
docWidth = document.body.clientWidth;
if( docWidth < navBreakpoint ){
el1.style.marginTop = mt+'px';
} else {
el1.style.marginTop = 'unset';
}
}
.container {
display: flex;
position: relative;
}
.container > div {
padding: 1rem;
margin: 3px;
border: 1px solid #efefef;
}
.container nav {
position: relative;
border: 1px solid #efefef;
background: #efefef;
}
#media(max-width: 768px){
.container {
flex-direction: column;
}
.container nav {
position: fixed;
top: 0;
width: 100%;
height: auto;
left: 0;
padding: 0.5rem;
}
.element-one {
padding-top: 3rem;
}
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="container">
<div class="element-one">
Logo
</div>
<div class="element-two">
<nav>I AM THE NAV</nav>
Mi quis hendrerit dolor magna eget est lorem ipsum dolor. Tempor orci eu lobortis elementum nibh tellus molestie. Nulla facilisi morbi tempus iaculis urna.
</div>
<div class="element-three">
A condimentum vitae sapien pellentesque habitant morbi tristique senectus. Eget mauris pharetra et ultrices neque ornare. Lorem mollis aliquam ut porttitor.
</div>
</div>
I coded a simple javascript "clearning Shopping List" code.
I was able to remove the shopping list and add two messages:
One says that the shopping list has been cleared and one pops up a button that asks if it was a mistake and you want to undo your change.
Now my problem is that when you press the "Undo" button the class doesn't get added back.
// javascript
var shoppingList = document.querySelector(".shoppingCart");
var toggleButton = document.querySelector("button.showList");
var clearedBox = document.querySelector(".clearedBox");
var clearedUndo = document.querySelector("button.clearedUndo");
//Toggle Shopping Cart
toggleButton.addEventListener("click", () => {
shoppingList.remove(".shoppingCart");
clearedBox.style.display = "block";
toggleButton.remove("button.showList");
});
//Undo Removal
clearedUndo.addEventListener("click", () => {
clearedUndo.createClass(".shoppingCart");
});
html, body {
margin: 0;
padding: 0;
margin-left:30px;
}
.clearedBox {
display:none;
}
.clearedMessage {
background:#D66A68;
color: white;
padding:10px;
width:260px;
text-align:center;
border-radius:10px;
}
.clearedUndo {
background:#1C77C3;
color: white;
padding:5px;
width:225px;
border-radius:5px;
text-align:center;
font-size:12px;
}
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>index.html</h1>
<button class="showList">Show</button>
<div class="shoppingCart">
<ul>
<li>Milk</li>
<li>Eggs</li>
<li>Juice</li>
<li>Pasta</li>
<li>Water</li>
<li>Donuts</li>
</ul>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et.</p>
</div>
<div class="clearedBox">
<p class="clearedMessage">Your Shopping cart is now cleared!</p>
<button class="clearedUndo">Accidental? Undo your change!</button>
</div>
<script src="index.js"></script>
</body>
</html>
I would assume this part is wrong:
//Undo Removal
clearedUndo.addEventListener("click", () => {
clearedUndo.createClass(".shoppingCart");
});
Once you remove it, it's gone, and if you want to put it back with JavaScript then all that markup really needs to be re-inserted, so I'd consider just hiding and showing the elements as needed, by changing the JS to this:
var shoppingList = document.querySelector(".shoppingCart");
var toggleButton = document.querySelector("button.showList");
var clearedBox = document.querySelector(".clearedBox");
var clearedUndo = document.querySelector("button.clearedUndo");
//Toggle Shopping Cart
toggleButton.addEventListener("click", () => {
shoppingList.style.display = "none";
clearedBox.style.display = "block";
toggleButton.style.display = "none";
});
//Undo Removal
clearedUndo.addEventListener("click", () => {
shoppingList.style.display = "block";
clearedBox.style.display = "none";
toggleButton.style.display = "block";
});
ISSUE
Don't use the elem.remove .Because if you undo the action no elements are present .For alternatively you can use elem.classList.toggle
// javascript
var shoppingList = document.querySelector(".shoppingCart");
var toggleButton = document.querySelector("button.showList");
var clearedBox = document.querySelector(".clearedBox");
var clearedUndo = document.querySelector("button.clearedUndo");
//Toggle Shopping Cart
toggleButton.addEventListener("click", () => {
shoppingList.classList.toggle('hide')
clearedBox.classList.toggle('show')
//toggleButton.remove("button.showList");
});
//Undo Removal
clearedUndo.addEventListener("click", () => {
shoppingList.classList.toggle('hide')
clearedBox.classList.toggle('show')
});
html,
body {
margin: 0;
padding: 0;
margin-left: 30px;
}
.clearedBox {
display: none;
}
.hide{
display: none;
}
.show{
display: block;
}
.clearedMessage {
background: #D66A68;
color: white;
padding: 10px;
width: 260px;
text-align: center;
border-radius: 10px;
}
.clearedUndo {
background: #1C77C3;
color: white;
padding: 5px;
width: 225px;
border-radius: 5px;
text-align: center;
font-size: 12px;
}
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>index.html</h1>
<button class="showList">Show</button>
<div class="shoppingCart">
<ul>
<li>Milk</li>
<li>Eggs</li>
<li>Juice</li>
<li>Pasta</li>
<li>Water</li>
<li>Donuts</li>
</ul>
<p>Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et.</p>
</div>
<div class="clearedBox">
<p class="clearedMessage">Your Shopping cart is now cleared!</p>
<button class="clearedUndo">Accidental? Undo your change!</button>
</div>
<script src="index.js"></script>
</body>
</html>
I am trying to make #switch visible after the .content element is hovered and to make #caption disappear.
Like the element IDs suggest, the #switch element should replace the caption on hover. I used Javascript to work that out, but onmouseover and onmouseout functions did not work with .content and #caption and #switch are abruptly shifting on hover.
document.getElementById('caption').onmouseover = function() {
displaySwitch()
};
document.getElementById('switch').onmouseout = function() {
hideSwitch()
};
function displaySwitch() {
document.getElementById('caption').style.display = "none";
document.getElementById('switch').style.display = "inline-block";
}
function hideSwitch() {
document.getElementById('switch').style.display = "none";
document.getElementById('caption').style.display = "block";
}
body {
margin: 50px;
}
.content {
height: 500px;
width: 100%;
border: 3px solid black;
}
#caption {
font-size: 3em;
}
#switch {
/* The element is hidden in advance. */
display: none;
}
<div class="content">
<a id="caption">Lorem Ipsum</a>
<div id="switch">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ornare libero et vestibulum pellentesque. In accumsan et est dapibus viverra.</p>
</div>
</div>
As per your requirement 'to make #switch visible after the .content element is hovered and to make #caption disappear', added new id box to content element. And bind onmouseover and onmouseout events to box element.
Please verify the output, is it as per your requirement or I did something different?
document.getElementById('box').onmouseover = function() {
displaySwitch()
};
document.getElementById('box').onmouseout = function() {
hideSwitch()
};
function displaySwitch() {
document.getElementById('caption').style.display = "none";
document.getElementById('switch').style.display = "inline-block";
}
function hideSwitch() {
document.getElementById('switch').style.display = "none";
document.getElementById('caption').style.display = "block";
}
body {
margin: 50px;
}
.content {
height: 500px;
width: 100%;
border: 3px solid black;
}
#caption {
font-size: 3em;
}
#switch {
/* The element is hidden in advance. */
display: none;
}
<div class="content" id="box">
<a id="caption">Lorem Ipsum</a>
<div id="switch">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla ornare libero et vestibulum pellentesque. In accumsan et est dapibus viverra.</p>
</div>
</div>
I'm trying to create this floating modal popup that sits in the top right-hand corner of the screen. I want the background to be active (as in I can do things normally on the webpage without the popup bothering it.
The problem arises when I want to resize the modal to the content on the inside. So for example, if I were to write a paragraph inside that popup, it would automatically resize the modal to contain that text. Preferably I want the width to be constant but I want it to extend downward depending on the text.
Here's what I have so far:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "inline-block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
right: 0;
top: 0;
width: 50%; /* Full width */
height: 50px; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: orange;
position: absolute;
right: 0px;
border: 1px solid #888;
width: 100%;
height: 100%;
margin: auto;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
</body>
</html>
So when the "modal-content" div increases in size due to text, I want the parent div (myModal) to adjust its size accordingly. I can't figure out how to do this. Any ideas?
Thanks!
I removed the overflow:auto so the scrollbar will not appear when there's a long text. The modal expands automatically and has a minimum height of 100 pixels.
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "inline-block";
}
span.onclick = function() {
modal.style.display = "none";
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
right: 0;
top: 0;
width: 30%;
/* Full width */
height: auto;
min-height: 100px;
/* Full height */
background-color: orange;
border: 1px solid #888;
}
.modal-content {
}
/* The Close Button */
.close {
color: #aaaaaa;
font-size: 28px;
font-weight: bold;
position: absolute;
top: 0;
right: 0;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam purus nunc, rhoncus in pellentesque vitae, bibendum vitae nunc. Morbi a arcu blandit, maximus tortor rhoncus, commodo libero. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vivamus egestas odio mauris, eu imperdiet ligula lobortis malesuada. Cras sit amet laoreet odio. Vivamus feugiat tortor a ullamcorper pulvinar. Mauris vestibulum semper ex nec pretium. Curabitur in elementum leo, et mollis dui. Integer convallis scelerisque metus, vel pulvinar metus sollicitudin eu. Nunc eu tristique odio.</p>
</div>
</div>
Remove position absolute from modal content and add some padding
<!DOCTYPE html>
<html>
<head>
<title> Modal Content </title>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
right: 0;
top: 0;
width: 50%; /* Full width */
height: auto; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
background-color: orange;
border: 1px solid #888;
margin: auto;
padding:20px;
}
/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<span class="close">×</span>
<p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "inline-block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
</script>
</body>
</html>