Custom truncate function deletes all the initial text - javascript

I am working on a small Show more/Show less script in jQuery.
function ellipsizeTex(id) {
var el = document.getElementById(id);
var btn = $("#undo_truncate");
var wordArray = el.innerHTML.split(' ');
var initialHtml = el.innerHTML;
var lessText = function() {
while (el.scrollHeight > el.offsetHeight) {
wordArray.pop();
el.innerHTML = wordArray.join(' ') + '...';
}
btn.removeClass('hide-text').addClass('show-text').text("Show more");
}
var moreText = function() {
el.innerHTML = initialHtml;
el.style.height = "auto";
btn.removeClass('show-text').addClass('hide-text').text("Show less");
}
lessText();
btn.on('click', function(){
if($(this).hasClass('show-text')){
moreText();
} else {
lessText();
}
});
}
ellipsizeTex('truncared');
#truncared {
padding: 0 10px;
background: #fff;
height: 72px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<div class="subcategory-desc">
<div id="truncared">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab quis aperiam ducimus, ipsa neque, sit illum facilis quas voluptates minus corporis vitae sunt incidunt labore odit quaerat fuga deleniti ex dolores provident consequatur perferendis. Ipsum
dolores pariatur error voluptate voluptates libero eligendi impedit inventore vero, cupiditate earum obcaecati, minus, ullam reiciendis distinctio dignissimos.</p>
<p>Voluptatem asperiores exercitationem soluta ipsa magnam ex ipsam voluptatibus minima sequi non, modi vitae assumenda harum nobis mollitia, quis, sed nesciunt blanditiis aperiam ad tenetur totam deserunt, et? A nostrum eveniet, sit et dolores iure quod dolorem, commodi tenetur aspernatur maxime maiores ea fugit quaerat, eius beatae.</p>
</div>
<div class="text-center">
Mai mult
</div>
</div>
This script has a bug that I have hot been able to spot: after clicking on "Show more", the entire text shows, as intended but when clicking on the same button, with "Show less" as text this time, all that remains in the box is "..." ellipses.
What am I doing wrong?

In the moreText function, you're setting the element's height to auto :
el.style.height = "auto";
Revert this in the lessText function and you'll fix your bug.
el.style.height = null;
function ellipsizeTex(id) {
var el = document.getElementById(id);
var btn = $("#undo_truncate");
var wordArray = el.innerHTML.split(' ');
var initialHtml = el.innerHTML;
var init = function() {
while (el.scrollHeight > el.offsetHeight) {
wordArray.pop();
el.innerHTML = wordArray.join(' ') + '...';
}
btn.removeClass('hide-text').addClass('show-text').text("Show more");
}
var lessText = function() {
el.style.height = null;
el.innerHTML = wordArray.join(' ') + '...';
btn.removeClass('hide-text').addClass('show-text').text("Show more");
}
var moreText = function() {
el.innerHTML = initialHtml;
el.style.height = "auto";
btn.removeClass('show-text').addClass('hide-text').text("Show less");
}
init();
btn.on('click', function(event) {
event.preventDefault();
if($(this).hasClass('show-text')){
moreText();
} else {
lessText();
}
});
}
ellipsizeTex('truncared');
#truncared {
padding: 0 10px;
background: #fff;
height: 72px;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap.min.js"></script>
<div class="subcategory-desc">
<div id="truncared">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab quis aperiam ducimus, ipsa neque, sit illum facilis quas voluptates minus corporis vitae sunt incidunt labore odit quaerat fuga deleniti ex dolores provident consequatur perferendis. Ipsum
dolores pariatur error voluptate voluptates libero eligendi impedit inventore vero, cupiditate earum obcaecati, minus, ullam reiciendis distinctio dignissimos.</p>
<p>Voluptatem asperiores exercitationem soluta ipsa magnam ex ipsam voluptatibus minima sequi non, modi vitae assumenda harum nobis mollitia, quis, sed nesciunt blanditiis aperiam ad tenetur totam deserunt, et? A nostrum eveniet, sit et dolores iure quod dolorem, commodi tenetur aspernatur maxime maiores ea fugit quaerat, eius beatae.</p>
</div>
<div class="text-center">
Mai mult
</div>
</div>

Related

Content of div partially hidden behind header when the link to the div on same page is clicked

I need the contents of <div a id="contentAbout">to fully appear when I click on the btnAbout link after scrolling down to the bottom of the page it is on, but when the link is clicked, and page jumps back to the top, the top part of the content is hidden (by a few lines) behind the <header> element, which is and needs to always remain in position at the top of the page (as per position: sticky; in the css). I need the top part of the contentAbout div to show under the header. I use plain javascript to display each div block as and when the links or buttons are clicked. This problem occurs regardless if it a link with an anchor to the div on the same page or a button with no anchor link that just executes the javascript to display the block. I believe the issue lies in the css, but not sure where or what to research to resolve this issue. Using Chrome.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="./style.css" type="text/css" rel="stylesheet" />
<script src="./script.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<div id="content-wrapper">
<header>
<nav class="nav">
<h1>website name | <span id="contentHeading"></span></h1>
<a href="index.html#contentAbout" id="btnAbout" name="btnNav" value="about"
onclick="contentAbout();">about</a>
<input type="button" id="btnPortfolio" name="btnNav" value="portfolio" onclick="contentPortfolio();" />
<input type="button" id="btnResume" name="btnNav" value="resume" onclick="contentResume();" />
<input type="button" id="btnContact" name="btnNav" value="contact" onclick="contentContact();" />
<input type="button" id="btnBlog" name="btnNav" value="blog" onclick="contentBlog();" />
</nav>
</header>
<main>
<div id="hidden"></div>
<div a id="contentAbout">
Lorem ipsum dolor, sit amet consectetur adipisicing elit. Et pariatur doloribus nemo temporibus dolor
earum iure. Consequuntur consectetur inventore aperiam quae sed, quis doloremque fugit iste placeat
dignissimos fuga, saepe nemo, maiores ipsum aliquid voluptas? Ut ea ex iusto. Asperiores eligendi
assumenda corporis aspernatur laborum animi quas impedit. Molestias quos fugit, exercitationem sequi
blanditiis, dolores maxime numquam illo nesciunt delectus nihil quis est quia sit facilis quod. Officia
ipsam minima voluptatibus distinctio esse cum repellendus obcaecati? Tempore consectetur blanditiis
alias sequi aspernatur sunt architecto recusandae ratione, numquam aperiam quasi sit asperiores delectus
praesentium minima quo voluptates nihil reprehenderit. Fugiat nulla assumenda laudantium reiciendis
enim? Ut iste, magni voluptates, aut quo earum obcaecati nemo voluptas enim nam voluptatem impedit vero
debitis quasi similique. Nam eveniet est aperiam magni odit necessitatibus architecto a nobis deleniti
saepe quas fugit numquam sed cumque, culpa molestias ratione temporibus exercitationem, ex sapiente!
Optio iste laboriosam dolores repellat eveniet, id enim rem provident porro est corporis minima nulla
mollitia ex cum quidem neque? Omnis quas tempora vel odio. Commodi, reiciendis iure! Voluptatibus,
sequi. Impedit ad sed est aperiam laboriosam eligendi veniam nobis perspiciatis optio labore sapiente
cum quos tenetur minus, ipsam ducimus quod eius eum qui. Aut tempora, excepturi dignissimos delectus
voluptate consequatur qui! Consequatur, saepe modi quo, ipsam sunt eum tempora aperiam, nemo tenetur
totam possimus repellendus ex minus laudantium! Accusamus fugiat id aliquam, quos eos exercitationem
dolor, officia ea officiis enim libero ab dolores adipisci eligendi iure labore nam. Nobis, totam
voluptatem! Itaque adipisci, explicabo corporis perspiciatis provident at doloremque nesciunt odio
facilis error maiores culpa nemo vitae, exercitationem dolorum facere officia sequi optio enim et alias!
Nihil suscipit delectus libero, repellendus rem quas eius neque cum vel esse tempora incidunt sed earum,
veritatis voluptate fugiat praesentium rerum perspiciatis alias voluptatibus dicta. Id debitis eos,
excepturi delectus deleniti ad omnis consequuntur reiciendis reprehenderit molestiae eligendi ratione et
ipsa, cumque similique incidunt voluptas magnam, iure quas dolorum aliquid? Quia culpa doloremque
nostrum eligendi consequatur iste similique hic qui eos illum non commodi numquam beatae deserunt, odio
facere deleniti consectetur? Enim dignissimos at dolore eum, velit, nesciunt culpa ad fugit sunt
corrupti asperiores obcaecati! Ex in molestias itaque! Autem necessitatibus modi debitis, deserunt
quisquam quasi sapiente molestiae eaque et dolores sint voluptas, amet quod sed. Eaque numquam porro
molestiae quae consequuntur commodi harum, non impedit veniam beatae vitae reiciendis, nulla aut libero!
Mollitia cupiditate, minus corporis temporibus neque quisquam itaque unde consequuntur maiores eum
pariatur esse culpa odit nobis voluptates architecto harum impedit ducimus iste earum tenetur nesciunt
veritatis! Modi officiis voluptas eaque repudiandae suscipit aut ipsa itaque. Facilis perspiciatis
eligendi a blanditiis rem earum omnis suscipit voluptate nisi minima laudantium perferendis est aperiam,
hic similique doloribus. Necessitatibus blanditiis magnam nostrum ipsa aliquid voluptates molestiae
aperiam. Ullam, consectetur, minus atque deserunt consequatur libero possimus quaerat repellat veniam
officia magni quos, est perferendis sunt cupiditate dolores nulla aspernatur iste? Quas cum, magnam
possimus eveniet quisquam sapiente vel hic sit cupiditate, recusandae iste atque quam aperiam veniam
temporibus voluptatum assumenda ut eius est odio, perspiciatis nisi commodi. Eos mollitia rem dolores
voluptatum optio nihil corrupti doloremque numquam. Iure ratione inventore eaque? Numquam ducimus id
porro tempora sapiente laborum voluptate recusandae soluta. Iste placeat ipsa officia autem sequi
consequuntur commodi, quibusdam maxime debitis facere animi temporibus pariatur veritatis molestiae enim
reiciendis tempora omnis aspernatur ea ullam atque error vel vero? Cum quibusdam, illum, quam
perspiciatis sunt earum maiores itaque est, repellendus minima et. Laboriosam, nulla facere esse nihil
ut dolore rerum odit asperiores? Quam quo amet alias sit fugiat repellendus sed, iusto voluptatibus,
assumenda nihil eaque aperiam laudantium quasi expedita error autem ullam, impedit quidem odit quas
delectus quos provident. Provident, ea iusto alias, libero qui iste voluptatum laborum saepe rerum
veniam sit dolorum, quam nemo minus ratione nesciunt eaque eius. Dolores iusto suscipit eius fuga ut
nemo libero quam, aperiam alias facere magnam, necessitatibus iure cupiditate voluptas? Ducimus nihil
assumenda quam fugit ea pariatur sint, fuga reprehenderit incidunt neque, qui animi alias iure? Harum
fuga aperiam, voluptatibus est adipisci reprehenderit quos assumenda ipsam, saepe ad nisi ut alias
molestias voluptas at facilis quod maiores ratione dolorum eos aliquid iure! Ut itaque repellat,
doloribus deleniti quaerat voluptas, cupiditate aperiam eum error sunt vel quis iusto inventore iste
sint esse. Deleniti natus impedit sunt, assumenda et atque earum minus fugiat excepturi consectetur
harum tenetur eos eum labore eaque dolorum quaerat omnis sequi maxime! Incidunt, dignissimos expedita?
Eum, non ducimus deserunt quod veritatis minus sunt animi ab nostrum dolorem impedit sint officia
tempora alias obcaecati perspiciatis hic quisquam molestias! Expedita itaque praesentium cupiditate
possimus rem earum optio natus ut. Nobis voluptatum inventore ex, laborum a voluptates dolorum ullam
corrupti, voluptatem nostrum voluptate. A error eveniet, natus veritatis illo eos accusantium labore
repudiandae exercitationem ex modi omnis eligendi mollitia dignissimos ipsam deserunt obcaecati soluta
molestias dolores rerum velit porro. Aperiam totam inventore, accusantium molestiae ex assumenda dolore
ratione molestias vel. Modi molestias harum, id distinctio labore eius deserunt rerum illo, magni esse
quis quibusdam sit sed. Nisi facilis quibusdam ullam veniam aliquam quae labore unde a, dignissimos
rerum magnam esse. Ipsam temporibus dolorum error adipisci suscipit iusto? Nemo illo velit molestias et
at esse nisi. Dolore explicabo, ut nemo earum repellendus, pariatur, inventore eligendi nobis provident
corrupti delectus! Veniam voluptate ratione deserunt modi blanditiis corporis aliquid, nisi facilis ex
similique dolorum magnam! Explicabo provident voluptatum, enim ipsam ullam adipisci amet suscipit veniam
in consectetur voluptates dolorum repellendus deleniti facilis. Debitis molestiae rem, facere eaque
doloremque perferendis voluptas sed molestias sint ipsam odit eius placeat, libero, tempora numquam
illum iure? A debitis sint in veritatis, atque adipisci distinctio quaerat eligendi cupiditate
recusandae labore quod minima tempora, voluptates fugiat! Nostrum est consequatur ullam corporis,
recusandae atque, obcaecati quibusdam totam quae similique in minus error. Voluptate unde adipisci neque
molestias illum debitis. Aliquam, assumenda? Quisquam commodi consequuntur pariatur reprehenderit minus
harum sunt labore accusantium quibusdam! Aliquid iusto quaerat architecto culpa aliquam mollitia
pariatur, assumenda nostrum suscipit fugit modi perspiciatis beatae accusantium quis voluptatum, alias
explicabo unde.
</div>
<div id="contentPortfolio">
Here are my projects.
</div>
<div id="contentResume">
My work experience.
</div>
<div a id="contentContact">
My email.
</div>
<div a id="contentBlog">
Here are blog post listings
</div>
</main>
<footer>
© all rights reserved
<div id="nav2" class="nav">
[terms]
[privacy]
[disclaimer]
[webmaster]
</div>
</footer>
</div>
</body>
</html>
CSS:
#content-wrapper {
margin-right: auto;
margin-left: auto;
max-width: 960px;
text-align: justify;
align-content: center;
}
header {
left: 0;
right: 0;
margin: 0 auto;
position: sticky;
text-align: center;
top: 0;
background: white;
padding-bottom: 1rem;
display: block;
}
main {
display: block;
padding-top: 1rem;
}
#contentAbout, #contentPortfolio, #contentResume, #contentContact, #contentBlog {
display: none;
}
footer {
left: 0;
right: 0;
bottom: 0;
position: fixed;
text-align: center;
background: white;
padding-bottom: 1rem;
display: block;
}
Javascript:
function contentAbout() {
if (document.getElementById("btnAbout").click) {
document.getElementById('contentHeading').innerHTML = "About";
document.getElementById('contentAbout').style.display = "block";
document.getElementById('contentPortfolio').style.display = "none";
document.getElementById('contentResume').style.display = "none";
document.getElementById('contentContact').style.display = "none";
document.getElementById('contentBlog').style.display = "none";
}
}
function contentPortfolio() {
if (document.getElementById("btnPortfolio").click) {
document.getElementById('contentHeading').innerHTML = "Portfolio";
document.getElementById('contentPortfolio').style.display = "block";
document.getElementById('contentAbout').style.display = "none";
document.getElementById('contentResume').style.display = "none";
document.getElementById('contentContact').style.display = "none";
document.getElementById('contentBlog').style.display = "none";
}
}
function contentResume() {
if (document.getElementById("btnResume").click) {
document.getElementById('contentHeading').innerHTML = "Resume";
document.getElementById('contentResume').style.display = "block";
document.getElementById('contentAbout').style.display = "none";
document.getElementById('contentPortfolio').style.display = "none";
document.getElementById('contentContact').style.display = "none";
document.getElementById('contentBlog').style.display = "none";
}
}
function contentContact() {
if (document.getElementById("btnContact").click) {
document.getElementById('contentHeading').innerHTML = "Contact";
document.getElementById('contentContact').style.display = "block";
document.getElementById('contentAbout').style.display = "none";
document.getElementById('contentPortfolio').style.display = "none";
document.getElementById('contentResume').style.display = "none";
document.getElementById('contentBlog').style.display = "none";
}
}
function contentBlog() {
if (document.getElementById("btnBlog").click) {
document.getElementById('contentHeading').innerHTML = "Blog";
document.getElementById('contentBlog').style.display = "block";
document.getElementById('contentAbout').style.display = "none";
document.getElementById('contentPortfolio').style.display = "none";
document.getElementById('contentResume').style.display = "none";
document.getElementById('contentContact').style.display = "none";
}
}
I saw that when I scroll the content of a div & then change the tabs the content of a div is hidden because window was scrolled to a position & the scroll position of window remained same even when I changed the tabs so the content appeared to be partially hidden.
to fix that you can add this in all the functions you call on clicking the buttons :
window.scroll({
top: 0,
left: 0,
behavior: "smooth"
});
for example :
function contentAbout() {
if (document.getElementById("btnAbout").click) {
document.getElementById("contentHeading").innerHTML = "About";
document.getElementById("contentAbout").style.display = "block";
document.getElementById("contentPortfolio").style.display = "none";
document.getElementById("contentResume").style.display = "none";
document.getElementById("contentContact").style.display = "none";
document.getElementById("contentBlog").style.display = "none";
window.scroll({
top: 0,
left: 0,
behavior: "smooth"
});
}
}
Just a opinion :
Instead of calling different functions when you click those buttons , you can make 1 function like this :
function tabChange(value) {
switch (value) {
case "about":
document.getElementById("contentHeading").innerHTML = "About";
document.getElementById("contentAbout").style.display = "block";
document.getElementById("contentPortfolio").style.display = "none";
document.getElementById("contentResume").style.display = "none";
document.getElementById("contentContact").style.display = "none";
document.getElementById("contentBlog").style.display = "none";
break;
case "portfolio":
document.getElementById("contentHeading").innerHTML = "Portfolio";
document.getElementById("contentPortfolio").style.display = "block";
document.getElementById("contentAbout").style.display = "none";
document.getElementById("contentResume").style.display = "none";
document.getElementById("contentContact").style.display = "none";
document.getElementById("contentBlog").style.display = "none";
break;
case "contact":
document.getElementById("contentHeading").innerHTML = "Contact";
document.getElementById("contentContact").style.display = "block";
document.getElementById("contentAbout").style.display = "none";
document.getElementById("contentPortfolio").style.display = "none";
document.getElementById("contentResume").style.display = "none";
document.getElementById("contentBlog").style.display = "none";
break;
case "resume":
document.getElementById("contentHeading").innerHTML = "Resume";
document.getElementById("contentResume").style.display = "block";
document.getElementById("contentAbout").style.display = "none";
document.getElementById("contentPortfolio").style.display = "none";
document.getElementById("contentContact").style.display = "none";
document.getElementById("contentBlog").style.display = "none";
break;
case "blog":
document.getElementById("contentHeading").innerHTML = "Blog";
document.getElementById("contentBlog").style.display = "block";
document.getElementById("contentAbout").style.display = "none";
document.getElementById("contentPortfolio").style.display = "none";
document.getElementById("contentResume").style.display = "none";
document.getElementById("contentContact").style.display = "none";
break;
default:
break;
}
window.scroll({
top: 0,
left: 0,
behavior: "smooth"
});
}
& then on the html do like this :
<input type="button" id="btnAbout" name="btnNav" value="about" onclick="tabChange('about')" />
<input type="button" id="btnPortfolio" name="btnNav" value="portfolio" onclick="tabChange('portfolio')" />
<input type="button" id="btnResume" name="btnNav" value="resume" onclick="tabChange('resume');" />
<input type="button" id="btnContact" name="btnNav" value="contact" onclick="tabChange('contact');" />
<input type="button" id="btnBlog" name="btnNav" value="blog" onclick="tabChange('blog');" />
Hope this helps 🤞 Codepen link

Finding element by visible or hidden not works

I am trying to find a element(button) either visible to view or hidden. but not works.
var newfun = function(){
var element = document.getElementById('parent');
var button = document.getElementById('button');
element.addEventListener('scroll', function(){
if((element.scrollTop + button.offsetHeight) > button.offsetTop ){
console.log('on visible');
return;
}
console.log('hidden');
});
}
newfun();
*{
padding:0;
margin:0;
}
.parent{
height:100px;
overflow-y:auto;
border:2px solid red;
}
<div id="parent" class="parent">
will type some info
<div>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptates praesentium similique pariatur at. Iste rem ratione veritatis officiis aliquid modi provident asperiores, ex porro quibusdam maiores impedit dolorum sit deserunt!</div>
<div>Et officiis earum, possimus doloribus harum odio aut enim, doloremque, culpa eaque ipsum. Dicta in hic quibusdam autem, excepturi. Unde fugiat nesciunt dolores animi repellendus, exercitationem, magnam iusto incidunt distinctio.</div>
<div>Minus dignissimos similique voluptas cum alias praesentium eos, inventore voluptatum est. Harum officia quo, maxime facere, explicabo ratione, voluptates inventore incidunt numquam cum sunt eos architecto, vero soluta saepe amet?</div>
<div>Enim quaerat ipsam inventore laboriosam odit eum rerum, magni aperiam. Mollitia, ratione, ex. Quidem iusto enim nobis quisquam impedit autem, commodi voluptates quaerat ipsam optio temporibus consequuntur, eos, voluptatibus deleniti.</div>
<div>Atque deserunt facilis consequatur quae eaque accusantium inventore ducimus voluptatem eius animi harum excepturi, reprehenderit earum minus distinctio hic tenetur enim veniam corrupti, blanditiis possimus doloribus qui! Voluptates, consectetur nostrum.</div>
<p>
<button id="button">
Click me
</button>
</p>
</div>
Demo
It happens because you use top border of your parent container to detect button visibility. To fix this you should add your parent height to your parent scroll.
scrollTop returns scroll amount from top border. You can check is button visible inside parent container using next code:
var newfun = function(){
var element = document.getElementById('parent');
var button = document.getElementById('button');
element.addEventListener('scroll', function(){
if(checkVisibility(button, element)){
console.log('on visible');
return;
}
console.log('hidden');
})
}
function checkVisibility(elm, parent) {
var boundingRect = elm.getBoundingClientRect();
var parentHeight = parent.offsetHeight;
return !(boundingRect.bottom < 0 || boundingRect.top - parentHeight >= 0);
}
newfun();
This is what you need. Consider your div offsetHeight which is 104 including borders pixels.
var newfun = function(){
var element = document.getElementById('parent');
var button = document.getElementById('button');
element.addEventListener('scroll', function(){
if(((element.scrollTop + element.offsetHeight + button.offsetHeight) > button.offsetTop)
&& (button.offsetTop + button.offsetHeight) > element.scrollTop
){
console.log('on visible');
return;
}
console.log('hidden');
})
}
newfun();

Sticky headers following their backgrounds on scroll - pure JS

I am a beginner in JS. And I've got a task to create a column consisting of several blocks. Each block should have its header. Each header should be of a different color. On scroll when the next header reaches the top, it should stick to the top and change the background color of the preceding header to the color of the header that recently came to the top. How can I do this using pure JS and taking into account responsiveness and adopting to landscape direction?
sample gif
Thank you
UPD: So far, I've got the following code done. When I run it on my laptop it goes more or less fine. But as soon as I resize the window the sticky header escapes to the right. What is the secret that I missed there?
! function(name, definition) {
if (typeof module != 'undefined' && module.exports) module.exports = definition();
else if (typeof define == 'function') define(definition);
else this[name] = definition();
}('sticky', function() {
return function sticky(el, top, options) {
var requiredOriginalStyles = ['position', 'top', 'left', 'z-index'];
var requiredTop = top || 0;
var originalRect = calcRect(el);
var styles = {
position: 'fixed',
top: requiredTop + 'px',
left: originalRect.left + 'px',
// width: originalRect.width + 'px',
'z-index': 9999
}
if (options && options.enforceWidth) {
styles.width = originalRect.width + 'px';
}
var originalStyles = {}
requiredOriginalStyles.forEach(function(key) {
originalStyles[key] = el.style[key];
});
var onscroll;
if (window.onscroll) {
onscroll = window.onscroll;
}
window.onscroll = function(event) {
if (getWindowScroll().top > originalRect.top - requiredTop) {
for (key in styles) {
el.style[key] = styles[key];
}
} else {
for (key in originalStyles) {
el.style[key] = originalStyles[key];
}
}
onscroll && onscroll(event)
}
}
function calcRect(el) {
var rect = el.getBoundingClientRect();
var windowScroll = getWindowScroll()
return {
left: rect.left + windowScroll.left,
top: rect.top + windowScroll.top,
width: rect.width,
height: rect.height
}
}
function getWindowScroll() {
return {
top: window.pageYOffset || document.documentElement.scrollTop,
left: window.pageXOffset || document.documentElement.scrollLeft
}
}
});
var headers = document.querySelectorAll('.header')
Array.prototype.forEach.call(headers, function(header) {
sticky(header);
});
body {
height: 2000px;
margin: 0px;
background: #fff;
color: #333;
font: 14px/2 Roboto, Verdana, sans-serif;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
section:first-child {
margin-top: 50px;
}
.header--initial {
background: yellow linear-gradient(to right, grey, transparent, grey);
}
.header--main-start {
background: grey linear-gradient(to right, grey, yellow);
}
.header--main-end {
background: yellow linear-gradient(to right, yellow, grey);
}
.header--final {
background: grey linear-gradient(to right, yellow, transparent, yellow);
}
p {
padding: 10px;
}
.header {
width: 50%;
height: 50px;
margin: auto;
background-color: #333;
}
.placeholder {
height: 300px;
width: 50%;
margin: auto;
overflow: auto;
}
<section>
<div class="header header--initial"></div>
<div class="placeholder">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum veritatis dolorem ducimus atque cumque accusantium accusamus aliquam excepturi nulla illo corrupti vitae repellendus quod, molestias esse est nisi, omnis odit.</p>
<p>Soluta autem, aut voluptate quo debitis quidem exercitationem quisquam nostrum accusamus aliquam perspiciatis nobis dolores est dolorum provident! Asperiores explicabo fugit, unde eveniet ut nesciunt autem molestiae nam totam fuga.</p>
<p>Vel nisi a dolorem itaque eaque mollitia ipsum repellat modi placeat, eveniet consectetur officia veniam ab esse, adipisci quia unde excepturi consequuntur expedita quas! Sed porro sunt soluta totam delectus!</p>
</div>
</section>
<section>
<div class="header header--main-start"></div>
<div class="placeholder">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laborum qui quidem rem ducimus, labore, id praesentium error quasi nobis saepe illo consequuntur voluptatum dolores illum facere, itaque dicta eveniet, quod.</p>
<p>Expedita dolore vel odit est nemo quis nihil ipsam quo vitae repellendus ex optio illo magnam quidem a ullam dolores reiciendis facilis deserunt eligendi cum, sit eaque? Et, nam odio!</p>
</div>
</section>
<section>
<div class="header header--main-end"></div>
<div class="placeholder">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Earum distinctio nobis excepturi sunt voluptates, saepe nam error laudantium velit autem quaerat placeat quisquam est dolore cum quidem, in ad sit!</p>
<p>Ex impedit deserunt, quibusdam ipsam blanditiis sunt tempore ab aut? Cum assumenda iure minus fugiat, rem nemo alias voluptatem, ad neque temporibus blanditiis aliquam earum praesentium vero labore ducimus, a.</p>
<p>Velit, suscipit officiis. Praesentium, explicabo similique maiores repellendus. Cupiditate voluptate corporis nisi doloremque aspernatur, autem aut officia. Eaque deleniti alias, modi dolorem quod qui debitis illo. Aut, ipsam. Hic, autem.</p>
<p>Maiores consequatur, aliquid possimus quae asperiores corporis repudiandae! Quod id iure at dolorem consectetur, sed, debitis libero perspiciatis, numquam ea, fugit repudiandae sunt consequatur. Harum optio ut doloribus distinctio adipisci!</p>
</div>
</section>
<section>
<div class="header header--final"></div>
<div class="placeholder">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sunt quisquam doloribus, commodi mollitia saepe nesciunt esse animi totam beatae facere tenetur veniam quas expedita iusto ipsa provident hic! Minima, repellendus.</p>
<p>Accusamus voluptatibus laudantium commodi nostrum obcaecati impedit atque doloremque officiis? Iste necessitatibus, aperiam. Vitae facilis ipsam vel, sequi perspiciatis fugit, dolores expedita quaerat reiciendis beatae iste hic molestias cumque! Necessitatibus!
</p>
<p>Cum, dolore. Dolore corporis voluptas consequatur ratione fuga, laboriosam quisquam qui corrupti ut, in nam pariatur iste blanditiis nulla autem praesentium, optio maxime. Consequuntur vitae nemo eius similique, fugiat saepe.</p>
<p>Recusandae iure iusto ut vero dolorum, hic quos libero nostrum esse enim laudantium velit modi culpa, consequatur vel officiis exercitationem quod repellat, voluptas impedit nesciunt beatae similique itaque distinctio? Sapiente.</p>
</div>
</section>
Try making your <body> element have an onresize attribute that updates the styles of the dropdown:
<body onresize="updHead()">

Append on responsive

I moved my element from .copyfilterArea to .copyfilter .container-margin to responsive, if my resolution is less than 768px then move my element.. it's okay so far, function is working properly, but if my resolution is bigger than 768px then put my div back to original location. only this section I couldn't do, how can I change my code to put the div back to the original location ? I tried append but nothing change
$(function () {
var flag;
$(window).resize(function () {
var bodyWidth = $(window).width();
console.log(bodyWidth)
if (flag !== false && bodyWidth < 768) {
//move the element to new location
$('.copyFilterArea').appendTo('.copyFilter .container-margin');
flag = false;
} else if (flag !== true && bodyWidth >= 768) {
//put it back to original location
console.log('more')
flag = true;
}
}).resize();
});
.copyFilter .container-margin{
padding:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="copyFilterArea">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo itaque voluptates quasi incidunt atque aliquam neque ducimus quibusdam quo fuga provident blanditiis sint saepe, culpa ipsam a quae magnam pariatur quidem ad. Numquam repudiandae rerum aliquid, reiciendis minus ipsa nostrum esse quam deserunt in! Odit cum incidunt molestias tempora accusamus doloribus, quidem saepe, iusto assumenda ad. Consequuntur voluptatibus earum voluptate veniam aspernatur, sapiente, molestias, voluptates officia perspiciatis nesciunt ducimus maiores excepturi iure ratione magnam eligendi, quia quisquam porro. Nobis explicabo, voluptatibus nulla a delectus aut dolorum excepturi distinctio. Similique veniam maxime fugiat deleniti ipsam autem in itaque at magni blanditiis.</p>
</div>
<div class="copyFilter">
<div class="container-margin">
<h1>COPY CONTENT WİLL BE HERE</h1>
</div>
</div>
Use prependTo to place the text in the initial state:
$(function () {
var flag;
$(window).resize(function () {
var bodyWidth = $(window).width();
console.log(bodyWidth)
if (flag !== false && bodyWidth < 768) {
//move the element to new location
$('.copyFilterArea').appendTo('.copyFilter .container-margin');
flag = false;
} else if (flag !== true && bodyWidth >= 768) {
//put it back to original location
$('.copyFilterArea').prependTo('.copyFilter .container-margin');
console.log('more')
flag = true;
}
}).resize();
});
.copyFilter .container-margin{
padding:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="copyFilterArea">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo itaque voluptates quasi incidunt atque aliquam neque ducimus quibusdam quo fuga provident blanditiis sint saepe, culpa ipsam a quae magnam pariatur quidem ad. Numquam repudiandae rerum aliquid, reiciendis minus ipsa nostrum esse quam deserunt in! Odit cum incidunt molestias tempora accusamus doloribus, quidem saepe, iusto assumenda ad. Consequuntur voluptatibus earum voluptate veniam aspernatur, sapiente, molestias, voluptates officia perspiciatis nesciunt ducimus maiores excepturi iure ratione magnam eligendi, quia quisquam porro. Nobis explicabo, voluptatibus nulla a delectus aut dolorum excepturi distinctio. Similique veniam maxime fugiat deleniti ipsam autem in itaque at magni blanditiis.</p>
</div>
<div class="copyFilter">
<div class="container-margin">
<h1>COPY CONTENT WİLL BE HERE</h1>
</div>
</div>
If you facing any issue with append and remove particular element in DOM at runtime then alternative you can handle it with hide/show logic where your element duplicate as below:
$(function () {
var flag;
$(".subFilterArea").hide();
$(window).resize(function () {
var bodyWidth = $(window).width();
console.log(bodyWidth)
if (flag !== false && bodyWidth < 768) {
//move the element to new location
$(".mainFilterArea").hide();
$(".subFilterArea").show();
flag = false;
} else if (flag !== true && bodyWidth >= 768) {
//put it back to original location
$(".mainFilterArea").show();
$(".subFilterArea").hide();
flag = true;
}
}).resize();
});
.copyFilter .container-margin{
padding:20px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="copyFilterArea mainFilterArea">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo itaque voluptates quasi incidunt atque aliquam neque ducimus quibusdam quo fuga provident blanditiis sint saepe, culpa ipsam a quae magnam pariatur quidem ad. Numquam repudiandae rerum aliquid, reiciendis minus ipsa nostrum esse quam deserunt in! Odit cum incidunt molestias tempora accusamus doloribus, quidem saepe, iusto assumenda ad. Consequuntur voluptatibus earum voluptate veniam aspernatur, sapiente, molestias, voluptates officia perspiciatis nesciunt ducimus maiores excepturi iure ratione magnam eligendi, quia quisquam porro. Nobis explicabo, voluptatibus nulla a delectus aut dolorum excepturi distinctio. Similique veniam maxime fugiat deleniti ipsam autem in itaque at magni blanditiis.</p>
</div>
<div class="copyFilter">
<div class="container-margin">
<h1>COPY CONTENT WİLL BE HERE</h1>
<div class="copyFilterArea subFilterArea">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo itaque voluptates quasi incidunt atque aliquam neque ducimus quibusdam quo fuga provident blanditiis sint saepe, culpa ipsam a quae magnam pariatur quidem ad. Numquam repudiandae rerum aliquid, reiciendis minus ipsa nostrum esse quam deserunt in! Odit cum incidunt molestias tempora accusamus doloribus, quidem saepe, iusto assumenda ad. Consequuntur voluptatibus earum voluptate veniam aspernatur, sapiente, molestias, voluptates officia perspiciatis nesciunt ducimus maiores excepturi iure ratione magnam eligendi, quia quisquam porro. Nobis explicabo, voluptatibus nulla a delectus aut dolorum excepturi distinctio. Similique veniam maxime fugiat deleniti ipsam autem in itaque at magni blanditiis.</p>
</div>
</div>
</div>
$(function () {
var flag;
var $copyFilterArea = $('.copyFilterArea')
$(window).resize(function () {
var bodyWidth = $(window).width();
console.log(bodyWidth)
if (flag !== false && bodyWidth < 768) {
//move the element to new location
$copyFilterArea.appendTo($('.copyFilter .container-margin'));
flag = false;
} else if (flag !== true && bodyWidth >= 768) {
//put it back to original location
if($("body").children(".copyFilterArea").length<=0){
$copyFilterArea.prependTo($('body'))
}
console.log('more')
flag = true;
}
}).resize();
});

Cycling through elements with jQuery

I've got a little script to cycle forward and backward through some items. Here's a simplified pen which shows the same issue: http://codepen.io/2kp/pen/sLoEb
$(document).ready(function(){
var totalslides = $('p').length;
var currentslide;
var newslide;
$('.left').on('click', function() {
currentslide = $('p.active').index()+1;
if (currentslide == 1){
newslide = totalslides;
}
else {
newslide = currentslide-1;
}
$('p.active').removeClass('active');
$('p:nth-child('+newslide+')').addClass('active');
});
$('.right').on('click', function() {
currentslide = $('.slide.active').index()+1;
if (currentslide == totalslides){
newslide = 1;
}
else {
newslide = currentslide+1;
}
$('p.active').removeClass('active');
$('p:nth-child('+newslide+')').addClass('active');
});
});
The left button works fine, but the right button works just sometimes. On the real site, both left and right buttons work fine on everything except iPad. iPhone, Android and desktop are fine.
Really weird. Any help gratefully received.
Use .eq() instead of :nth-child. Also we can drop the need for an if block by using modulus (idea from this SO Answer):
$(function() {
var $slides = $('p.slide');
function transition(step) {
var $activeSlide = $('p.slide.active').removeClass('active');
var nextIndex = ($slides.index($activeSlide) + step) % $slides.length;
$slides.eq(nextIndex).addClass('active');
}
$('.left').on('click', $.proxy(transition, null, -1));
$('.right').on('click', $.proxy(transition, null, 1));
})();
button {
font-size: 32px;
}
.slide {
display: none;
}
.slide.active {
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="left">☜</button> <button class="right">☞</button>
<div class="slides">
<p class="slide active">1: Lorem ipsum dolor sit amet, consectetur adipisicing elit. A alias neque necessitatibus, deleniti natus est dolores aut earum maiores ullam quas quis mollitia nemo, tenetur magni. Veniam in porro perspiciatis.</p>
<p class="slide">2: Itaque impedit ratione, eveniet, quisquam voluptate perferendis eum accusantium! Quia mollitia dolor a nulla, tenetur nesciunt ex tempore officia autem modi sit molestiae veniam voluptates vero itaque beatae similique quidem.</p>
<p class="slide">3: Est libero consequuntur ipsum distinctio corporis doloremque sunt iure autem tenetur labore at voluptate quam, repudiandae alias asperiores unde iste. Perspiciatis laborum, culpa sit maxime nostrum consequuntur labore reprehenderit adipisci.</p>
<p class="slide">4: Error eveniet, modi a sunt animi quos accusamus ullam quibusdam earum doloribus, omnis dicta ut. Facilis laboriosam autem libero itaque accusantium explicabo blanditiis veritatis sint nesciunt obcaecati, deleniti! Alias, impedit?</p>
<p class="slide">5: Modi neque harum vero minima nemo, dolor dolorum veritatis fuga obcaecati vitae! Quo commodi temporibus obcaecati rem repudiandae vel assumenda nostrum alias. Debitis non esse culpa officiis eum exercitationem distinctio!</p>
</div>
I'm not sure why. Probably some kind of conflict with other parts of my script, but replacing nth-child() with eq() and adjusting the maths sorted out the issue on the iPad.

Categories

Resources