Cycling through elements with jQuery - javascript

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.

Related

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 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...

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();
});

JS keeps redirecting me to a null page

I have this js script that will make the page fade in when the user enters, and fades out when the user clicks a link to another page. It works, but somehow I have my anchor links within the page and whenever I click the links, it takes me to the anchor and within a few seconds it redirects me to a null page like localhost/website/null
here's the code:
jQuery('body').css('display', 'none');
jQuery(document).ready(function() {
jQuery('body').fadeIn();
jQuery('a').on('click', function(event) {
var thetarget = this.getAttribute('target')
if (thetarget !="_blank" ) {
var thehref = this.getAttribute('href')
event.preventDefault();
jQuery('body').fadeOut(function(){
window.location = thehref
});
}
});
});
setTimeout(function() {
jQuery('body').fadeIn();
}, 1000)
I'm not understanding the problem -- maybe there isn't an issue? Refer to the snippet below?
Meta/Sidenote: SO needs a better way of creating snippets for comments -- this shouldn't be an answer, but there's no better way to supply a SO-generated demo.
jQuery('.container').css('display', 'none');
jQuery(document).ready(function($) {
var $container = $('container').fadeIn();
$('a').on('click', function(e) {
var _target = this.getAttribute('target');
if (_target != "_blank") { // (e.g., null, '_self')
var _href = this.getAttribute('href');
e.preventDefault();
$('.container').fadeOut(function() {
window.location = _href;
});
}
});
});
setTimeout(function() {
jQuery('.container').fadeIn();
}, 1000)
.container {
background: #09c;
padding: 1em;
height: 100%;
width: 100vw;
}
a:nth-child(2n)::after {
content: "\A";
white-space: pre;
}
body {
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<div class="container">
_self (external link)
_self (internal link)
_blank (external link)
_blank (internal link)
No target (external link)
No target (internal link)
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse, reprehenderit, nostrum. Tempora totam, iusto, inventore cupiditate hic quam quas explicabo dolore mollitia eius ullam rerum minus placeat nobis in debitis magni non, dolor aut libero
dignissimos fugiat. Sed laboriosam itaque necessitatibus hic excepturi, perferendis, exercitationem cumque incidunt asperiores labore dolor.</p>
<p>Minus velit rerum, reiciendis perspiciatis pariatur accusamus, magni voluptatibus, voluptatem fugit optio libero quidem! Nostrum pariatur eveniet ipsum obcaecati aperiam deleniti hic quam facilis reprehenderit dolor ipsam suscipit, quidem laboriosam
impedit fugiat sit dignissimos delectus qui. Suscipit necessitatibus natus omnis eveniet molestiae nostrum aut culpa, tempora, voluptatibus modi eius nisi.</p>
<p>Illo quo, iure doloremque unde ullam iste. Fuga ullam dicta voluptate, odio sint molestiae expedita sequi, placeat omnis porro. Blanditiis ut, laboriosam nobis necessitatibus esse ipsam, magnam facilis in placeat delectus quidem eos laborum, illum
similique fugiat nesciunt doloremque ratione unde vel fugit excepturi dolor minima, amet tenetur. Tempora, eveniet.</p>
<p>Aliquam ex assumenda eum perspiciatis odio suscipit nemo in delectus. Iste in, ipsam iure deserunt, explicabo ipsum maxime. Praesentium, vitae, quos quia sed doloribus laboriosam. Architecto sapiente totam quisquam esse saepe asperiores provident
voluptatibus aperiam, similique sunt fugit cupiditate beatae aspernatur laborum, eius quas ab tempore consequatur officiis vero! Fugiat.</p>
<p>Explicabo minima necessitatibus soluta odio, sunt saepe aspernatur quasi molestiae cum? Nulla eveniet ad accusantium sed sapiente quod ea soluta repellendus culpa, ut deleniti dolore. Porro amet, quasi dignissimos provident modi nihil rerum quis explicabo,
voluptatem illo assumenda itaque. Maxime sequi asperiores enim tempora maiores dolor. Nihil quidem repudiandae asperiores!</p>
<p>Dicta facere at dolorum ut veritatis recusandae praesentium nesciunt illo, omnis doloremque labore repellendus soluta officia distinctio aperiam pariatur minus quia placeat enim, amet, quae repellat reiciendis nihil magni. Ad expedita dolores cupiditate
debitis dolore? Unde vitae inventore provident reiciendis adipisci dolorum ad ipsa possimus excepturi, mollitia nobis. Perspiciatis, voluptate.</p>
<p>Officia minima nulla delectus neque sapiente in voluptates iste facere dolorum sequi, animi fuga illo enim alias explicabo, culpa? Quaerat nesciunt animi, eius assumenda quidem sunt saepe nam suscipit voluptate eaque, laborum minus expedita nostrum
praesentium iusto eveniet officia ab tempore eos at. Dolores minus qui fugit, temporibus sequi tempora!</p>
<a id="foo" name="foo">ID:foo</a>
</div>
</body>

How to compensate for loop performance differences among browsers

I have this typewriter script which uses timeout in a self-referencing function to add a character to element.
The problem is that is takes longer on firefox than in chrome and I want it to complete within the same duration across all browsers.
Chrome: Performed in: 3.167695
Firefox: Performed in: 4.10383
var start = performance.now();
txt = $('#text').html();
typeWriter(txt,0);
function typeWriter(text, n) {
if (n < (text.length)) {
$('#text').html( text.substring(0, n+=2) );
setTimeout(function() {
typeWriter(text, n);
}, 1);
}else{
var end = performance.now();
$('body').append('<h4>Performed in: ' + (end - start)/1000);
}
}
#text{
font-size:10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet illo rem, id nemo, animi repellendus ullam error ratione molestias, praesentium temporibus. Repudiandae dolorum consequuntur at tenetur, beatae debitis dolore dicta animi omnis quo, laborum quos? Veritatis quas provident iste adipisci deserunt excepturi a, suscipit neque soluta error impedit animi. Exercitationem aliquid reprehenderit excepturi. Nisi placeat unde, iste veniam? Molestias, soluta et corrupti possimus deleniti magni tenetur! Ut ab, dolores dicta temporibus amet debitis harum dignissimos, nisi neque cum assumenda accusamus minima quod deserunt veniam suscipit tempore eligendi labore. Eum ut, quod repellat adipisci distinctio sit nobis cum iure porro quasi! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem harum repellat vitae atque ipsa cumque sed iste adipisci omnis, ad magnam numquam amet, totam, autem ab quis maxime ea, ducimus nulla sunt assumenda aliquam distinctio. Quam sit ducimus, amet esse sunt consectetur facilis praesentium, soluta fugiat vero alias vel. Aspernatur amet ea odit hic voluptatum, doloremque rem cumque dolore accusamus quia enim praesentium, officia deserunt reprehenderit ex debitis. Provident eos voluptate quibusdam, esse atque porro, nisi sunt amet fugit, distinctio beatae! Sed atque voluptatum ullam illum perspiciatis aut mollitia! Cumque voluptatum rerum, accusantium, ad placeat culpa voluptatibus distinctio aspernatur laudantium.</div>
Should I use the timer to figure out how many characters to add per cycle? What's the best way to fix this?
Use requestAnimationFrame - you can then set a pretty accurate elapsed time - in the example I use 3 seconds
the wait is 1000/60 - because requestAnimationFrame runs at 60fps
the code could easily just be
var count = txt.length 3 / 60;
Where the 3 is the number of seconds you want this to take, and remove the var wait and elapse - I've only included the code like this to help see what's happening
var start = performance.now();
var txtEl = document.getElementById('text');
var txt = txtEl.textContent;
var wait = 1000/60;
var elapse = 3000;
var count = txt.length * wait / elapse;
var typeWriter = function (text, n) {
if (n < (text.length)) {
txtEl.textContent= text.substr(0, n+=count);
requestAnimationFrame(function() {
typeWriter(text, n)
});
} else {
var end = performance.now();
document.body.insertAdjacentHTML('beforeEnd', '<h4>Performed in: ' + (end - start)/1000);
}
}
typeWriter(txt, 0);
#text{
font-size:10px;
}
<div id="text">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eveniet illo rem, id nemo, animi repellendus ullam error ratione molestias, praesentium temporibus. Repudiandae dolorum consequuntur at tenetur, beatae debitis dolore dicta animi omnis quo, laborum quos? Veritatis quas provident iste adipisci deserunt excepturi a, suscipit neque soluta error impedit animi. Exercitationem aliquid reprehenderit excepturi. Nisi placeat unde, iste veniam? Molestias, soluta et corrupti possimus deleniti magni tenetur! Ut ab, dolores dicta temporibus amet debitis harum dignissimos, nisi neque cum assumenda accusamus minima quod deserunt veniam suscipit tempore eligendi labore. Eum ut, quod repellat adipisci distinctio sit nobis cum iure porro quasi! Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolorem harum repellat vitae atque ipsa cumque sed iste adipisci omnis, ad magnam numquam amet, totam, autem ab quis maxime ea, ducimus nulla sunt assumenda aliquam distinctio. Quam sit ducimus, amet esse sunt consectetur facilis praesentium, soluta fugiat vero alias vel. Aspernatur amet ea odit hic voluptatum, doloremque rem cumque dolore accusamus quia enim praesentium, officia deserunt reprehenderit ex debitis. Provident eos voluptate quibusdam, esse atque porro, nisi sunt amet fugit, distinctio beatae! Sed atque voluptatum ullam illum perspiciatis aut mollitia! Cumque voluptatum rerum, accusantium, ad placeat culpa voluptatibus distinctio aspernatur laudantium.</div>
Firefox: 3.022785
Chrome: 3.022000
Close enough for gubmint work, would you say?
SetTimeout is an asynchronus call whatever time you specified in setTimeout does not mean it will be executed exactly after that time. Whenever you do
setTimeout()
It request will be stored on stack and it will be able to execute AFTER that time. After doenot means as soon as. so we do not have any control on that.
Now question is that what is difference between two browsers? Chrome uses v8 javascript engine and firefox uses spidermonkey. So it is like you are asking two persons to do same task in same time.(correct me if i am wrong)

Categories

Resources