Facebook Modal Popup that Prevents Scroll on Main Page - javascript

See the Facebook comment modal box in the below. I'm trying to achieve a similar effect whereby a user clicks on a button and then it opens up a popup/modal box. This box will allow scroll within the new box (as it could be many pages of text), but will disallow scrolling outside of the modal on the main page. How do I achieve a similar effect where the modal allows scrolling within the modal window but not elsewhere? Thanks.

Usually this works by doing the following:
Adding height:100% to body and html tags.
Adding overflow: hidden to body when the modal is showing.
Basic Demo: jsFiddle
$("body").on("click", function(){
$("body").toggleClass("modalview");
})
html, body {background:#666; color:#FFF; margin: 0; padding: 0; height:100%;}
#content {
padding:1em;
width:90%;
margin:0 auto;
}
#modal {
/* hidden by default */
display: none;
/* box */
width:75%;
height:75%;
padding:1em;
position: fixed; z-index:1;
overflow: auto;
/* center modal vertically and horizontally */
left: 50%; top: 50%;
transform: translate(-50%,-50%);
/* style */
text-align: center;
background:#FFF;
box-shadow:1px 1px 15px #000;
color:#000;
}
/* prevent page scrollbars in modal view */
body.modalview { overflow:hidden; }
/* show #modal in modal view */
body.modalview #modal { display: block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="modal">
<p>All UR SCROLLS ARE BELONG TO US!!!</p>
<p>Et velit odit cumque hic, aspernatur. Perferendis assumenda est necessitatibus cupiditate cum odit deleniti doloribus earum veniam dolores, neque laudantium laboriosam optio numquam autem iure animi ipsa dolor fugit blanditiis?</p>
<p>Unde quidem sunt quos itaque minus, quia modi nisi temporibus. Consectetur natus perferendis possimus, rem, sed tempora cumque dolorum quod provident blanditiis eum ipsam voluptate dolor, harum doloremque id amet.</p>
</div>
<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Animi assumenda quas, rem voluptas et, totam officia quos, quaerat doloribus eaque odio aperiam a obcaecati explicabo quod eveniet eum aliquid! Repellat.</p>
<p>Vitae ipsum explicabo voluptatibus corrupti odio ipsa, tenetur modi veritatis excepturi architecto nam dignissimos ratione. Iusto temporibus ipsum cupiditate excepturi modi eos alias dolores eveniet possimus. Alias, esse error quam!</p>
<p>Ea numquam quae laborum ut vitae molestias dolorum fugit, asperiores aliquid voluptates vero ab consequuntur ipsum maxime obcaecati temporibus voluptate sed quaerat, necessitatibus deleniti. Quibusdam iste saepe inventore amet eius.</p>
<p>Aut veritatis quos quaerat, placeat nam est ad tempora delectus magnam molestiae, ipsum cupiditate debitis illum perferendis ut nisi beatae voluptas provident consectetur inventore assumenda eveniet? Molestiae architecto ullam nulla.</p>
<p>Explicabo, debitis? Mollitia reiciendis sint minus adipisci, consectetur consequatur assumenda blanditiis pariatur ex facilis expedita et earum molestiae quos, laborum sed suscipit doloribus placeat ipsam in vero quaerat aliquid iure!</p>
<p>Earum dolorem eveniet laboriosam vel dolor! Ullam nisi adipisci voluptatem, voluptatum tenetur, itaque ducimus laboriosam repudiandae quibusdam numquam dignissimos aperiam praesentium culpa porro sapiente ab eos magni? Maiores, doloremque, aspernatur.</p>
</div>
In my approach, I used a CSS class for body to toggle the overflow state. When body gets the class (.modalview) it will hide content below the fold and remove scrollbars from page while showing the actual modal.
jQuery is used to apply the class to body and show #modal through a on click function.
For demonstration sake, I made the #modal show up when you just click on the page, you can bind the function to a button click, like so:
$("#myButton").on("click", function(){
$("body").toggleClass("modalview");
})
To see this properly, load up the jsFiddle demo and play with the page width to see how the scrolling is changed.

Related

Fix division at the middle of the container

I have three different divisions in a single container. div toolbar, div one and div two. I am trying to make toolbar, div one stick to the same place of the screen. and I also want to make sticky the div.fixed-header, only the contents inside div.fixed-header-contents should
be scrollable and shouldn't go behind the divisons above it. I have tried postion sticky and fixed but the div.fixed-header-contents overlaping the previous divisions.
Here's the example :
.toolbar{
border : 1px solid;
position : sticky;
z-index : 1000;
top: 0;
}
.fixed-header{
border-top : 1px solid;
border-bottom : 1px solid;
}
/* .one{
position : fixed
} */
<body>
<div class="toolbar"> // I want this div to be stick to the current position
<h4>
toolbar
</h4>
</div>
<div class="one"> //I want this div to be stick to the current position
<h3>
some images
</h3>
<h3>
some buttons
</h3>
<h3>
some contents
</h3>
</div>
<div class="two">
<div class="fixed-header"> //I want this div to be stick to the current position
<h4>
fixed header items
</h4>
</div>
<div class="fixed-header-contents"> //this div should be scrollable but should not overlap the previous screen
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
</div>
</div>
</body>
To solve this problem you need to know .toolbar and .one height. You can set to the top property as an absolute value in the CSS, or if don't know to use Javascript to get height of elements.
For the scrollable container (fixed-header-contents) we need to add an extra wrapper, since we restrict viewport then overflow the child element with the min-height: 100%.
document.addEventListener('DOMContentLoaded', function() {
const toolbar = document.querySelector('.toolbar');
const one = document.querySelector('.one');
const two = document.querySelector('.two');
const toolbarHeight = toolbar.getBoundingClientRect().height;
const oneHeight = one.getBoundingClientRect().height;
one.setAttribute('style', `--toolbar-height: ${toolbarHeight}px`);
two.setAttribute('style', `--one-height: ${toolbarHeight + oneHeight}px`);
});
.toolbar,
.one,
.two {
position: sticky;
z-index: 1000;
}
.toolbar {
border: 1px solid;
top: 0;
}
.one {
top: var(--toolbar-height);
}
.two {
top: var(--one-height);
}
.fixed-header {
border-top: 1px solid;
border-bottom: 1px solid;
}
/* for scrollable */
.fixed-header-contents {
overflow: hidden;
height: 5rem;
display: flex;
}
/* for scrollable */
.scrollable {
min-height: 100%;
overflow-y: auto;
}
/* not important */
section {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
<div class="toolbar">
// I want this div to be stick to the current position
<h4>toolbar</h4>
</div>
<div class="one">
//I want this div to be stick to the current position
<h3>some images</h3>
<h3>some buttons</h3>
<h3>some contents</h3>
</div>
<div class="two">
<div class="fixed-header">
//I want this div to be stick to the current position
<h4>fixed header items</h4>
</div>
<div class="fixed-header-contents">
<div class="scrollable">
//this div should be scrollable but should not overlap the previous screen "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto
beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor
sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid
ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"
</div>
</div>
</div>
<section>
<h1>section 1</h1>
</section>
<section>
<h1>section 2</h1>
</section>

Terms and Conditions modal read-detection - Plain Javascript (No libraries)

I'm trying to figure out a way to create a scrollable modal that detects when the reader has scrolled to the bottom before enabling the 'Agree' button. This is for a Terms and Conditions type of box. I am also trying to create this with nothing more than plain html, css, and javascript. This is what I have so far.
var termsModal = document.getElementById("terms-modal");
// Get the button that opens the modal
var agreeCheckbox = document.getElementById("agree-checkbox");
// Get the <span> element that closes the modal
var closeModal = document.getElementsByClassName("close")[0];
var modalContent = document.getElementsByClassName("modal-content");
var agreeButton = document.getElementById("agreeBtn");
var agreementContainer = document.getElementById("agreement");
// Enables agree button when user scrolls all the way down
// modalContent.scroll(function() {
// var disable = (((agreementContainer.height())) >= (modalContent.scrollTop() + modalContent.height() + 1));
// agreeButton.disabled = disable;
// })
// When user clicks agree button in modal, keeps agree checkbox checked
agreeButton.onclick = function() {
agreeCheckbox.checked = true;
termsModal.style.display = "none";
}
// When the user clicks the button, open the modal
agreeCheckbox.onclick = function() {
if (agreeCheckbox.checked === true) {
termsModal.style.display = "block";
} else {
agreeCheckbox.checked === false;
}
}
// When the user clicks on <span> (x), close the modal
closeModal.onclick = function() {
termsModal.style.display = "none";
agreeCheckbox.checked = false;
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
termsModal.style.display = "none";
agreeCheckbox.checked = false;
}
}
body {
font-family: Arial, Helvetica, sans-serif;
}
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
padding-bottom: 100px;
left: 0;
top: 0;
scroll-behavior: smooth;
width: 100%;
/* Full width */
height: 100%;
/* 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 */
overflow: hidden;
border-radius: 5px;
}
.modal-header {
display: flex;
justify-content: flex-end;
width: 100%;
padding-right: 5%;
}
.modal-inner-container {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
/* align-self: center; */
/* padding-bottom: 10%; */
width: 70%;
background-color: #fefefe;
border: 1px solid #888;
/* margin-bottom: 20%; */
margin-right: 10%;
margin-left: 10%;
height: 450px;
/* padding: 20px; */
border-radius: 5px;
}
#agreement {
height: 350px;
margin-bottom: 5%;
border-radius: 5px;
display: flex;
flex-direction: column;
}
/* Modal Content */
.modal-content {
display: flex;
flex-direction: column;
/* justify-content: center; */
align-items: center;
background-color: #fefefe;
margin: auto;
/* padding: 20px; */
border: 1px solid rgb(179, 179, 179);
border-radius: 5px;
width: 97%;
/* margin-bottom: 20%; */
overflow-y: scroll;
}
.modal-footer {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
<h2>Modal Example</h2>
<!-- Trigger/Open The Modal -->
<!-- <a href=""> -->
<input type="checkbox" id="agree-checkbox">
</>
<p>
I HAVE READ THE <span>PRIVACY POLICY</span> AND AGREE TO THE <span>TERMS AND CONDITIONS</span> OF THIS AGREEMENT.
</p>
<!-- </a> -->
<!-- The Modal -->
<div id="terms-modal" class="modal">
<div class="modal-inner-container">
<div class="modal-header">
<span class="close">×</span>
</div>
<!-- Modal content -->
<div class="modal-content">
<!-- <p>Some text in the Modal..</p> -->
<div id="agreement" class="termsImages">
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Repudiandae reprehenderit est, hic esse, numquam omnis autem exercitationem eum a nobis perspiciatis et labore voluptatibus accusamus molestias eveniet laboriosam amet cumque ut, fuga soluta atque
porro eaque voluptatem? Doloremque, culpa modi. Corrupti optio similique excepturi inventore architecto ipsum, officiis explicabo sunt ducimus, iusto dolorum animi eius pariatur fuga consectetur rerum? Ratione, amet. Explicabo culpa accusamus
consectetur esse odio quis, unde officiis quidem veniam, doloremque sed modi error tenetur eligendi quisquam molestiae, ut dicta suscipit nisi officia necessitatibus voluptatem ex delectus. Praesentium tenetur consequuntur repellendus voluptatum,
dolorem adipisci. Voluptate ab repellendus eum nobis alias quae corporis odit quasi unde, aut pariatur quod! Laboriosam qui quisquam minima quia, eum perspiciatis odio non ullam ipsum culpa quae iste voluptatum velit aspernatur? Nisi vitae dolor
fuga dignissimos facere culpa voluptate, delectus ipsam iste laboriosam at iure. Quod porro perferendis modi laboriosam, error expedita explicabo similique et ex, facilis dignissimos natus, tenetur cupiditate iure tempora debitis aspernatur
repudiandae sequi voluptatem eos blanditiis! Veritatis pariatur hic illum. Nemo laboriosam aliquam reiciendis! Voluptas sequi modi nisi veniam error vel aperiam a ab ipsam, nam porro rerum laudantium totam corporis suscipit maiores quam nihil
temporibus asperiores, ex consequuntur doloremque! Illo nisi tenetur minima consectetur ad iste non molestias fugit, laborum molestiae delectus fugiat saepe quos dolorum? Magni nobis consequatur ut maiores adipisci magnam rem ex odit nesciunt
ullam temporibus rerum quis, nostrum distinctio quisquam facilis quia ducimus necessitatibus impedit earum deleniti. Mollitia, tempore minima? Atque molestiae perspiciatis velit dolore eius? Nisi id aperiam magnam consequatur eum distinctio,
architecto aliquid temporibus. Natus accusantium magni fugit aliquid, libero ratione. Modi maiores asperiores, consectetur dignissimos impedit eaque similique culpa quo obcaecati sequi rerum possimus assumenda! Modi nesciunt alias quisquam quas!
Quas, maiores. Molestias tenetur nihil, ducimus nam a possimus fugit minima fugiat assumenda dolor molestiae soluta delectus veritatis laborum laudantium quia quae magnam porro saepe quibusdam doloremque. Dignissimos quaerat laborum possimus
quis nisi at, sequi delectus, quasi inventore tempore facilis modi repudiandae? Aperiam dolores quos inventore eveniet mollitia est ipsa. Nihil repellat molestiae possimus qui itaque! Cum id recusandae error et dolor beatae iure quidem dolorem
ratione, eveniet, consequuntur laborum veritatis. Sapiente quis nostrum possimus illo nihil quisquam consequuntur. Commodi quidem nisi rem porro impedit at, praesentium qui non fugiat aspernatur illo reiciendis et quos soluta atque similique
aut? Dolore illum quas obcaecati laboriosam, eos tempora delectus ex rerum iure, temporibus soluta voluptates. Neque recusandae, aspernatur inventore voluptatibus sint quae? Quibusdam repellendus deserunt nobis illo adipisci iste. Sed explicabo
dolore accusantium, inventore repellat ratione praesentium minus magni doloremque, itaque ab sunt error, at ut consectetur repudiandae ullam ea repellendus distinctio? Illum modi similique rerum tenetur odit ad quae, vitae architecto repellendus
illo harum iste quas iusto eveniet molestiae reprehenderit ab nisi quasi ullam. Aliquid enim vero hic ipsam natus consequuntur, at repellat ipsa inventore, sequi veritatis eveniet deserunt illum ut? Error a autem sint consequatur, nulla totam
quisquam. Dicta repellendus iste corporis ut? Iusto aperiam aut placeat recusandae similique quis perspiciatis fugit molestiae sapiente consectetur voluptates, quia quae tempora error obcaecati eum perferendis exercitationem ipsam delectus!
Saepe earum, alias hic dignissimos deleniti doloribus, minus architecto aliquam odio explicabo vitae ab, blanditiis numquam. Itaque nihil deleniti omnis nobis, vitae odit quam nam excepturi neque officiis iste ducimus quidem tenetur recusandae
voluptatem exercitationem, iure sequi sed eum repudiandae fugiat similique? Rem nostrum quidem in quia magnam necessitatibus placeat magni voluptate, dolorum quos adipisci molestiae quibusdam tempora sed, aperiam illum odio excepturi. Voluptate
nostrum natus, fugit perspiciatis tempora cupiditate officia alias eos, ducimus ad dolore autem excepturi laborum! Distinctio ad aliquid quibusdam odio nemo, itaque, totam inventore velit corporis illo, facere maxime consectetur fugit consequuntur
necessitatibus quia. Debitis adipisci recusandae dicta illo quisquam, tempora voluptas id odit et commodi ab, excepturi iure velit explicabo libero aliquid asperiores officiis vitae aperiam eius? Accusantium sint a labore, pariatur dolores,
veniam ipsa quae ab blanditiis consequuntur tempore optio vel aperiam sunt! Dolorem eius adipisci magni ab corrupti, dolor modi recusandae qui ut nam quasi minima ea voluptas ullam corporis blanditiis commodi iure voluptates obcaecati, ducimus
velit explicabo? Laborum sit temporibus magni illum qui assumenda porro inventore totam suscipit vero esse perferendis tenetur voluptates eligendi ratione, tempora maiores ex alias sequi impedit amet error. Voluptate, nobis labore, maxime eius
repudiandae iusto culpa quidem nisi quo, dicta consectetur sint! Et officiis itaque deleniti qui delectus molestiae, doloribus, cumque dolores fugiat inventore quisquam mollitia similique consequuntur sapiente. Nihil vero quod, fugit rerum consequuntur
ipsam magnam quibusdam blanditiis amet aut iusto corporis qui repellendus odit reiciendis maxime et sit dolore nam. Eligendi repellendus, at modi deserunt accusamus voluptate expedita eos culpa adipisci, voluptatum sed veniam quaerat quod quibusdam
distinctio natus animi odio maxime facere repudiandae! Minus dolore eum illum numquam! Labore velit enim amet at doloribus esse magnam natus eaque provident mollitia!
</p>
</div>
</div>
<div class="modal-footer">
<p class="instructions">Please read through to the end of the Agreement to enable the AGREE button.</p>
<button type="button" id="agreeBtn" class="agree-Btn" data-dismiss="modal" aria-hidden="true">AGREE</button>
</div>
</div>
</div>
It's not currently working. Any help is appreciated!

Image animation resets page scroll on mobile devices

EDIT 2: I just figured it out. The overflow css property applied on the body is not being inherited by the slideshow div. Adding "overflow: hidden" to the slideshow div fixed it.
ORIGINAL POST
I have a webpage with an image slideshow. The slideshow is set to run every 5 seconds using setInterval and calling the below function:
function startSlideShow() {
console.log('starting slideshow');
const img = slideImages.shift();
img.style.zIndex = 0
slideImages.push(img);
slideImages[0].style.zIndex = 10;
slideImages[0].style.display = "block";
removePreviousImage(img);
}
The animation keyframe:
#keyframes slide {
from {
transform: translateX(100%);
}
to {
transform: translateX(0);
}
}
The structure of the page is:
Header
Slideshow
Other Content
The header "position: sticky", so it should always be visible.
The Problem: On mobile or responsive mode on browser dev tool, when I scroll down while the animation is running, the header is not visible, i.e it is ignoring the "position: sticky" css rule. Once the animation completes, the page resets the scroll position back to the top.
It works as expected on desktop, i.e the header is always visible at the top of the screen and the scroll position does not get reset.
I am still learning and I don't understand what is causing the issue and why only on mobile? Tried google but no luck, mostly because I am not sure what to search for.
EDIT:
Recreated the problem as per the code below:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Slideshow</title>
<style>
body {
min-height: 100%;
font-family: Helvetica,
Arial,
sans-serif;
overflow-x: hidden;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
}
.preload * {
animation: none !important;
}
img {
max-width: 100%;
height: auto;
}
.main__overlay {
z-index: 200;
}
.image-slider__overlay {
z-index: 1000;
}
.header {
z-index: 2000;
}
.header {
text-transform: uppercase;
padding: var(--size1) var(--size0);
opacity: 0.9;
position: sticky;
top: 0;
left: 0;
width: 100%;
background-color: #fff;
}
.image-slider {
position: relative;
}
.image-slider__img {
position: absolute;
top: 0;
left: 0;
animation-name: slide;
animation-duration: 3s;
}
.no-slide {
aspect-ratio: attr(width) / attr(height);
}
#keyframes slide {
from {
transform: translateX(100%);
}
to {
transform: translateX(0);
}
}
</style>
</head>
<body>
<body class="preload">
<header class="header">
<h1 class="header__logo">Earthen Karkhana</h1>
</header>
<div class="image-slider">
<div class="no-slide">
This div will be an image is the actual code. Image 1
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi odit, dolore omnis voluptates, accusantium
architecto eos nulla totam facere eum numquam temporibus error. Saepe aliquid asperiores veritatis sit
inventore repudiandae.
Quam ut praesentium reprehenderit necessitatibus ab voluptatibus esse laborum enim, veniam exercitationem quia
autem cum nihil et officiis itaque vero quasi distinctio. Quidem, ad a ipsum nihil incidunt ipsa libero!
</p>
</div>
<div class="image-slider__img">
This div will be an image is the actual code. Image 2
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi odit, dolore omnis voluptates, accusantium
architecto eos nulla totam facere eum numquam temporibus error. Saepe aliquid asperiores veritatis sit
inventore repudiandae.
Quam ut praesentium reprehenderit necessitatibus ab voluptatibus esse laborum enim, veniam exercitationem quia
autem cum nihil et officiis itaque vero quasi distinctio. Quidem, ad a ipsum nihil incidunt ipsa libero!
</p>
</div>
<div class="image-slider__img">
This div will be an image is the actual code. Image 3
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi odit, dolore omnis voluptates, accusantium
architecto eos nulla totam facere eum numquam temporibus error. Saepe aliquid asperiores veritatis sit
inventore repudiandae.
Quam ut praesentium reprehenderit necessitatibus ab voluptatibus esse laborum enim, veniam exercitationem quia
autem cum nihil et officiis itaque vero quasi distinctio. Quidem, ad a ipsum nihil incidunt ipsa libero!
</p>
</div>
<div class="image-slider__img">
This div will be an image is the actual code. Image 4
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi odit, dolore omnis voluptates, accusantium
architecto eos nulla totam facere eum numquam temporibus error. Saepe aliquid asperiores veritatis sit
inventore repudiandae.
Quam ut praesentium reprehenderit necessitatibus ab voluptatibus esse laborum enim, veniam exercitationem quia
autem cum nihil et officiis itaque vero quasi distinctio. Quidem, ad a ipsum nihil incidunt ipsa libero!
</p>
</div>
</div>
<section class="projects__main">
<h2 class="projects-link--heading body_text">
Projects
</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Sequi odit, dolore omnis voluptates, accusantium
architecto eos nulla totam facere eum numquam temporibus error. Saepe aliquid asperiores veritatis sit inventore
repudiandae.
Quam ut praesentium reprehenderit necessitatibus ab voluptatibus esse laborum enim, veniam exercitationem quia
autem cum nihil et officiis itaque vero quasi distinctio. Quidem, ad a ipsum nihil incidunt ipsa libero!
Autem reiciendis fugit quis, perspiciatis nihil sit aliquam impedit dicta placeat veritatis culpa voluptate nisi
aut consectetur unde, alias et fugiat quisquam dolor distinctio eos dolore non error! Id, optio.
Omnis excepturi delectus inventore ullam harum accusamus sed consequatur autem quo obcaecati mollitia corrupti
amet, eaque veritatis, sit dolorum voluptates id atque rem, ipsam officia? Architecto magni dignissimos sint
dolorem!
Doloremque enim nobis eum esse nihil. Fugiat nesciunt obcaecati omnis. Doloribus harum deserunt sapiente omnis
quasi aut voluptatum consequatur perferendis, tempora nulla blanditiis labore vitae provident repellendus,
eveniet sit quas.
Nemo, quos perspiciatis modi repudiandae delectus doloremque. Vero dolores blanditiis itaque consequatur minus
distinctio, sapiente corporis, suscipit ratione tenetur animi sit eius quod dolorem nobis sed pariatur tempora
natus ea.
Quam sequi distinctio adipisci dolor? Asperiores exercitationem eveniet eum architecto voluptates, tempore saepe
sint eius quisquam odit veritatis debitis eligendi ab impedit, officia nam! Libero tenetur ad consequuntur eos
natus.
Corporis pariatur eius velit ad sequi facere impedit quia laboriosam quos? Eum, labore minima temporibus placeat
sunt totam neque, quod harum facilis reiciendis doloribus aliquid dolor saepe distinctio expedita sint.
Repellat, ipsam! Omnis nihil maiores amet excepturi velit, deleniti minus voluptatibus quasi vel, magni aperiam
veritatis non asperiores, nisi dolorum hic eligendi ipsa? Omnis id esse hic non sed est!
Qui accusantium dignissimos natus corporis asperiores, perferendis eveniet ab et, consequuntur vitae officiis
nulla consequatur obcaecati magni corrupti nihil neque nam iste quidem! Libero eos est, beatae error praesentium
eligendi!
</p>
</section>
<script>
"use strict";
const slideImages = Array.from(document.querySelectorAll(".image-slider__img"));
// Wait for page to load before starting slideshow
window.addEventListener('load', (e) => {
document.querySelector("body").classList.remove("preload");
// slideshow should only run on index page
if (document.querySelectorAll(".image-slider__img").length == 0) return;
// Static image not required to be visible once slide images are loaded in
setTimeout(() => document.querySelector(".no-slide").style.opacity = 0, 8000);
slideShow();
});
function slideShow() {
slideImages.forEach((img, index) => {
img.style.display = "none";
});
console.log(slideImages);
let animationInterval = setInterval(startSlideShow, 5000);
}
function startSlideShow() {
console.log('starting slideshow');
const img = slideImages.shift();
img.style.zIndex = 0
slideImages.push(img);
slideImages[0].style.zIndex = 10;
slideImages[0].style.display = "block";
removePreviousImage(img);
}
function removePreviousImage(img) {
setTimeout(function () { img.style.display = "none" }, 3000);
}
</script>
</body>
</html>
If viewed in responsive mode in dev tools the page layout changes when the animation is running, but that does not happen on desktop mode.
In desktop mode, resizing the browser to match width of a mobile device does not trigger the problem.
I guess your browser doesnt support position : sticky; try to use another browsers like chrome .
‌‌‌‌‌‌
and I highly recommend You better to use "browser-prefixes" .
You can read about "browser-prefixes" in :
https://www.thoughtco.com/css-vendor-prefixes-3466867

How to use Jquery to dynamically hide text and add a collapse button?

I have a project to achieve that when the text exceeds 5 lines, the collapse button needs to be displayed to hide the extra text!
When the text is less than 5 lines, the collapse button is not displayed, but I don’t know how to accomplish this. Needs~ I hope I can get your help, thank you!
$('.show').click(function(){
$(this).toggleClass('rotate');
$('.content').toggleClass('show-all');
});
$('.content').click(function(){
$('.show').toggleClass('rotate');
$(this).toggleClass('show-all');
})
.content {
/* height: auto; */
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 5;
}
.content.show-all{
height:auto;
overflow:visible;
text-overflow: none;
transition: all 2s;
}
.more {
text-align: center;
transition: all .2s;
}
.show{
display: inline-block;
text-decoration: none;
color: #222;
transition: all .6s;
transform:rotate(0deg);
}
.rotate{
transform: rotate(180deg)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo">
<p class="content">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Suscipit odit fugit debitis, quibusdam esse eius ullam odio cupiditate cumque nostrum asperiores libero, sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt ugit debitis, quibusdam esse eius ullam odio cupiditate cumque nostrum asperiores libero, sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt
</p>
<div class="more">
V
</div>
</div>
You have to add line height for content to ccalculate the number of lines in your content
Please check following code snippet , I hope this answer will full fill your requirement
var targetElement = $('.content'); // get .content element as selector
var clickElement = $('.more'); // get click .more element as selector
var numberOfLines = 5; // set initial shown number of lines
var animationSpeed = 500; // set toggle animation speed of .content element
var contentLineHeight = parseFloat(targetElement.css('line-height')); // get .content line height without px
var contentOuterHeight = parseFloat(targetElement.outerHeight()); // get .content height without px
var totalLineCount = contentOuterHeight/contentLineHeight; // calculate total number of lines of the content
var initialDisplayContentHeight = contentLineHeight * numberOfLines; // set height for 5 lines of contnent
var initialDisplayContentHeightWithPixel = initialDisplayContentHeight + 'px'; // convert into px
// set initial height of .content element, if content length is more than 5 line
if(contentOuterHeight > initialDisplayContentHeight) {
// set height for content
targetElement.css('height',initialDisplayContentHeightWithPixel);
// show .more element
clickElement.show();
}
// show full content for .more element click (if content height is more than 5line)
clickElement.click(function(){
// get current height of .content
var targetDivCurrentHeight = parseFloat(targetElement.outerHeight());
// add rotate class for click element
$(this).toggleClass('rotate');
// check the content linmit and show the content
if (targetDivCurrentHeight != initialDisplayContentHeight) {
targetElement.animate({ height: initialDisplayContentHeight }, animationSpeed );
} else {
targetElement.animate({ height: contentOuterHeight }, animationSpeed );
}
});
.content {
/* height: auto; */
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 5;
line-height: 16px;
overflow: hidden;
}
.more {
text-align: center;
transition: all .2s;
display: none;
}
.show{
display: inline-block;
text-decoration: none;
color: #222;
transition: all .6s;
transform:rotate(0deg);
}
.rotate {
transform: rotate(180deg)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="demo">
<p class="content">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Suscipit odit fugit debitis, quibusdam esse eius ullam odio cupiditate cumque nostrum asperiores libero, sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt ugit debitis, quibusdam esse eius ullam odio cupiditate cumque nostrum asperiores libero, sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt sapiente aliquid animi? Saepe eligendi doloremque possimus. Velit sunt earum aliquam debitis quos eum atque nemo eius, hic quas doloremque facere et voluptatibus voluptatum eaque corrupti impedit ipsum beatae incidunt
</p>
<div class="more">
V
</div>
</div>

How to dynamically add links with jQuery [duplicate]

This question already has answers here:
Use JQuery to build an anchor
(5 answers)
how to add text link inside a div using jquery?
(3 answers)
Closed 1 year ago.
I am a program beginner and I am learning by myself now!
First of all, I am very sorry that my English is not very good, I will try to express it completely, thank you.
My question is, I am working on an effect to limit the number of words in a range, if the number of words is more than that it will hide and show a show more hyperlink that can be clicked into, but how can I add a link instead of a string at the end?
$(function(){
let len = 50;
$(".demo").each(function(i){
if($(this).text().length>len){
$(this).attr("title",$(this).text());
let text=$(this).text().substring(0,len-1)+" show more"
$(this).text(text);
}
});
});
.box {
width: 300px;
padding: 10px;
border: #ef5c28 2px solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<p class="demo">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.</p>
</div>
You can add any arbitrary html easily using jquery with code such as
$(this).append("<button type='button'>");
$("<button type='button'>").appendTo(this);
(this = each .demo inside the .each loop)
There's lots of different ways to do this, each with a different use. For example, this would be better built directly into the HTML so you don't get a FOUC (flash of unstyled content) where your full text is shown then hidden - but the question is specifically about adding with jquery.
To start with, it's probably easier to create what you want and then add it.
var btn = $("<button type='button'>");
$(this).append(btn);
this will keep a reference to the btn which you can manipulate later, eg
btn.click(function() { ...
Semantically, a hyperlink <a href= should "go" somewhere - for this you should use a button. You can make it look like a link with some css (found with a quick SO search).
$(function() {
let len = 50;
$(".demo").each(function(i) {
if ($(this).text().length > len) {
$(this).attr("title", $(this).text());
let text = $(this).text().substring(0, len - 1);
$(this).text(text);
var btn = $("<button type='button' title='click to show more'>show more</button>");
$(this).append(btn);
btn.click(function() {
// restore the text, which was stored earlier in the `title`
var demo = $(this).closest(".demo");
demo.text(demo.attr("title"));
// no longer need the button - inside the click handler `this` is now the button
$(this).hide();
});
}
});
});
.box {
width: 300px;
padding: 10px;
border: #ef5c28 2px solid;
}
/* https://stackoverflow.com/questions/1367409/how-to-make-button-look-like-a-link */
button {
background: none!important;
border: none;
padding: 0!important;
/*optional*/
font-family: arial, sans-serif;
/*input has OS specific font-family*/
color: #069;
text-decoration: underline;
cursor: pointer;
font-style:italic;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<p class="demo">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.
</p>
</div>
As an alternative, you can also do this with css and adding/removing a class on the parent .box:
$(function() {
$(".showmore").click(function() {
$(this).closest(".box").removeClass("min");
});
});
.box {
width: 300px;
padding: 10px;
border: #ef5c28 2px solid;
}
/* https://stackoverflow.com/questions/1367409/how-to-make-button-look-like-a-link */
button {
background: none!important;
border: none;
padding: 0!important;
/*optional*/
font-family: arial, sans-serif;
/*input has OS specific font-family*/
color: #069;
text-decoration: underline;
cursor: pointer;
font-style:italic;
}
.box.min p {
white-space: nowrap;
text-overflow: ellipsis;
overflow:hidden;
}
.box .showmore {
display:none;
}
.box.min .showmore {
display:block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box min">
<p class="demo">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.
</p>
<button type='button' class='showmore' title='click to show more'>show more</button>
</div>
There are a few things you need to do to create the "show more" link and have it function.
A couple options for the link itself: You can make it inline with the text by making the .demo class inside a <span> element, adding the link after it, then wrapping both in a <p> (see full code snippet). Another option is just add the link after your paragraph in the HTML as an anchor (or button, etc.):
<div class="box">
<p class="demo> <!-- your full text --> </p>
<a id="showMore"> show more</a>
</div>
Then, add the code to show the link, and create the function to show the original full text. You should store the full text in a variable, prior to hiding it with your substring so you can access it again after full the text is removed. You can style the #showMore in css as you please. Similar code can add a "hide more" element, too.
$(function() {
let len = 50;
$(".demo").each(function(i) {
// Store the original full text, so you can add it back
let fullText = $(this).text();
if ($(this).text().length > len) {
$(this).attr("title", $(this).text());
let text = $(this).text().substring(0, len - 1)
$(this).text(text)
// Show the "show more" link
$("#showMore").show();
// Add function to swap to full text and hide the link
$("#showMore").click(function() {
$("#showMore").hide();
$(".demo").text(fullText);
});
}
});
});
.box {
width: 300px;
padding: 10px;
border: #ef5c28 2px solid;
}
/* Add the styling for "show more" element */
#showMore {
display: inline;
color: #ef5c28;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box">
<!-- If you want the "show more link inline, make the full text inside a span and move the class from p to the span -->
<p><span class="demo">Lorem ipsum dolor sit amet consectetur adipisicing elit. Facere culpa expedita nam consequuntur, dignissimos explicabo quasi aperiam repudiandae quia saepe! Eaque, neque amet incidunt nesciunt dicta suscipit eveniet at, dolorem voluptates similique repudiandae esse velit ea voluptatibus vitae obcaecati ducimus itaque odit mollitia facere assumenda possimus aliquid consequuntur. Recusandae earum maiores unde adipisci quia, facere rem quos nobis explicabo expedita reiciendis deleniti consequuntur inventore hic rerum, delectus nostrum reprehenderit eius fugit aliquam dolores. Ab impedit quidem dignissimos, facere distinctio tempora explicabo, magnam nisi vel animi iusto eligendi. Vitae nostrum modi nam adipisci esse, quasi pariatur consequuntur soluta, deserunt qui cupiditate repudiandae provident nemo fugit nesciunt accusantium, aut sed ad? Repudiandae fuga veritatis aliquid vero voluptates porro, quis corrupti accusantium exercitationem molestiae nemo obcaecati? Obcaecati in quam natus quos eius enim itaque fugit hic distinctio quis maiores, laborum provident saepe ipsa reiciendis illum dolores nesciunt, ratione voluptatem repellendus, repellat omnis quae.
</span>
<a id="showMore"> show more</a>
</p>
</div>
With this: $(this).text().length
You're taking first 50 characters...
You want to get the text and and split it by spaces " " first.
let allWordsInArray = $(this).text().split(" ")
If the array is longer than 50 then add the link and truncate the array...
let finalText = ""
if (allWordsInArray.length > 50) {
finalText = allWordsInArray.slice(0, 50).join(" ") + "..." +"<a href='somelink'>sometext</a>";
}
else {
finalText = allWordsInArray.join(" ")
}
And finally write it out
$(yourCustomContainer).html(finalText)
You have your first 50 words + link...

Categories

Resources