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