jQuery - Each counting resetting issue - javascript

I'm trying to get the currentpage number using jQuery each function. This is how I am doing it
var CurrentPageView = 1;
var check = true;
var Bookmark = [];
var CurPage = 1;
$(function() {
$(window).scroll(function() {
if (check) {
var PagesPosition = [];
var CurrentWindowPosition = $(window).scrollTop();
var CurrentCenterWindowPos = CurrentWindowPosition + $(window).height() / 2;
$(".Page").each(function() {
var PagePos = $(this).offset().top;
if (PagePos / CurrentCenterWindowPos <= 1) {
CurPage = $(this).index() + 1;
}
});
$(".CurrPageNumber").val(CurPage);
CurrentPageView = CurPage;
}
});
});
And it is working pretty well. If i am scrolling up and down he changes and gives me the currentpage number. The problem happens if between those with the class page there is something like a span. When this happens the counter resets to 1..
I would like to know if there is a way to keep the counting working for every div with the class "A4 Portrait" even if inside a span.
So instead of the actual count
1
2
1
2
It would be
1
2
3
4

Try using the index in the list of .Page instead of the index in its parent:
$(".Page").each(function(i) {
var PagePos = $(this).offset().top;
if (PagePos / CurrentCenterWindowPos <= 1) {
CurPage = i + 1; // Use the index in the array.
}
});
$(".CurrPageNumber").val(CurPage);
CurrentPageView = CurPage;

Related

Multiple Morphs on Scroll

Struggling to get multiple SVGs to animate on scroll. I followed the CodePen and the first animation works fine, but the second doesn't. I need to be able to run like 4-5 of these on the homepage.
var scrollMorph1 = new TimelineLite({paused:true})
.to("#headerBottomMask",1, {morphSVG:"#headerBottomMask2"},0)
.to("#headerBottom01a",1, {morphSVG:"#headerBottom01b"},0)
.to("#headerBottom02a",1, {morphSVG:"#headerBottom02b"},0)
.to("#headerBottom03a",1, {morphSVG:"#headerBottom03b"},0)
.to("#headerBottom04a",1, {morphSVG:"#headerBottom04b"},0)
$(window).scroll(function() {
var scrolled = $(window).scrollTop();
var diff = 50;
var object1 = $('#header h1');
var topOfRange1 = object1.offset().top + diff;
if (scrolled > topOfRange1 ) {
scrollMorph1.play().timeScale(1);
} else {scrollMorph1.reverse().timeScale(1);}
});
var scrollMorph2 = new TimelineLite({paused:true})
.to("#clientsMask",1, {morphSVG:"#clientsMask2"},0)
$(window).scroll(function() {
var scrolled = $(window).scrollTop();
var diff = 50;
var object2 = $('#weare a');
var topOfRange2 = object2.offset().top + diff;
if (scrolled > topOfRange2 ) {
scrollMorph2.play().timeScale(1);
} else {scrollMorph2.reverse().timeScale(1);}
});
Code works fine. Wasn't targeting the Path, but rather the SVG's ID on the second one. Have to target the path.

Jquery function should also work with other elements

I'm trying to make this function working multiple times:
Currently works only with the h1 tag
how can I make it working for the <div class="logo"> as well? I don't want to repeat the function, I need a way to make the function working for various elements.
demo: http://jsfiddle.net/33Ec8/4/
JS:
// Get the divs that should change
function displayThese() {
var $heading = $('h1');
var h1top = $heading.position().top;
var h1bottom = h1top + $heading.height();
var h1left = $heading.position().left;
var h1right = h1top + $heading.width();
var divs = $('li').filter(function () {
var $e = $(this);
var top = $e.position().top;
var bottom = top + $e.height();
var left = $e.position().left;
var right = left + $e.width();
return top > h1bottom || bottom < h1top || left > h1right || right < h1left;
});
return divs;
}
(function fadeInDiv() {
var divs = displayThese();
var elem = divs.eq(Math.floor(Math.random() * divs.length));
if (!elem.is(':visible')) {
elem.prev().remove();
elem.animate({
opacity: 1
}, Math.floor(Math.random() * 1000), fadeInDiv);
} else {
elem.animate({
opacity: (Math.random() * 1)
}, Math.floor(Math.random() * 1000), function () {
window.setTimeout(fadeInDiv);
});
}
})();
$(window).resize(function () {
// Get items that do not change
var divs = $('li').not(displayThese());
divs.css({
opacity: 0.3
});
});
Your question isn't stated very clearly, so I would strongly suggest describing what the code should do vs what it does.
That said, here is a half-blind attempt at answering what I think you want.
You could pass in the selector as a parameter to displayThese.
function displayThese(selectorString)
{
var $elementsUnderWhichNothingShouldFade = $(selectorString);
...
}
then when you call displayThese, you can pass in any complex selector you like.
var divsToChange = displayThese('h1, div.logo')
Of course, you would need to add extra logic to test whether the image elements were underneath any of the resulting $elementsUnderWhichNothingShouldFade (which is a list of elements).

get interval ID from else statement when set in IF

I am attempting to create a responsive slider, that will change to a simple set of dot points when in mobile mode (< 940).
The issue I am facing is in my else statement I am unable to clearintervals that were made in the if statement, because t comes up as undefined. I have resorted to using
for (var i = 1; i < 99999; i++) window.clearInterval(i); to clear the interval which works, but I don't like it because it's ugly and cumbersome, is there another way of accomplishing this?
$(document).ready(function() {
function rePosition() {
//get responsive width
var container_width = $('.container').width();
//Slider for desktops only
if(container_width >= 940) {
//get variables
var slide_width = $('.slider_container').width();
var number_of_slides = $('.slider_container .slide').length;
var slider_width = slide_width*number_of_slides;
//set element dimensions
$('.slide').width(slide_width);
$('.slider').width(slider_width);
var n = 1;
var t = 0;
$('.slider_container').hover(function() {
clearInterval(t);
}, function() {
t = setInterval(sliderLoop,6000);
});
var marginSize = i = 1;
//Called in Doc Load
function sliderLoop(trans_speed) {
if (trans_speed) {
var trans_speed = trans_speed;
}
else
{
var trans_speed = 3000;
}
if (i < number_of_slides) {
marginSize = -(slide_width * i++);
}
else
{
marginSize = i = 1;
}
$('.slider').animate({ marginLeft: marginSize }, trans_speed);
}
t = setInterval(sliderLoop,6000);
$('.items li').hover(function() {
$('.slider').stop();
clearInterval(t);
var item_numb = $(this).index();
i = item_numb;
sliderLoop(500);
}, function() {
t = setInterval(sliderLoop,6000);
});
}
else
{
for (var i = 1; i < 99999; i++)
window.clearInterval(i);
$('.slider').stop(true, true);
$('.slider').css('margin-left', '0px');
//rearrange content
if($('.slider .slide .slide_title').length < 1) {
$('.items ul li').each(function() {
var item_numb = $(this).index();
var content = $(this).text();
$('.slider .slide:eq(' + item_numb + ')').prepend('<div class="title slide_title">' + content + '</div>')
});
}
}
}
rePosition();
$(window).resize(function() {
rePosition();
});
});
Teemu's comment is correct. I'll expand on it. Make an array available to all of the relevant code (just remember that globals are bad).
$(document).ready(function() {
var myIntervalArray = [];
Now, whenever you create an interval you will need to reference later, do this:
var t = setInterval();//etc
myIntervalArray.push(t); //or just put the interval directly in.
Then to clear them, just loop the array and clear each interval.
for (var i=0; i<myIntervalArray.length; i++)
clearInterval(myIntervalArray[i]);
}
Umm, wouldn't t only be defined when the if part ran... as far as I can tell, this is going to run and be done... the scope will be destroyed. If you need to maintain the scope across calls, you'll need to move your var statements outside of reposition(), like so:
$(document).ready(function() {
var t = 0;
...
function rePosition() { ... }
});

jQuery add row number as class on the divs on current row

I need to make jquery fill all the rows in a layout as the first row in the fiddle
not sure if I explained well enough but the fiddle should clear out what I want.
first five divs have width changed a bit to make sure the row is filled, but I can't make the rest of rows fill the container
basically I want to justify all the divs by increasing their widths
http://jsfiddle.net/SG9Vx/
so far I have this function, modified from here: jQuery Find number of items per row in floated li's:
var lisInRow = 0;
$('#posts div').each(function() {
if($(this).prev().length > 0) {
if($(this).position().top != $(this).prev().position().top) return false;
lisInRow++;
$(this).addClass("row1");
}
else {
lisInRow++;
$(this).addClass("row1");
}
});
var itemNumber = $(".row1").length
var widthRow = 0;
$('.row1').each(function() {
widthRow += $(this).outerWidth( true );
});
var widthContainer = $("#posts").width();
var remaining = widthContainer - widthRow;
leftMargin = Math.floor(remaining / itemNumber);
$(".row1").each(function(){
var addedwidth = $(this).width() + leftMargin;
$(this).width(addedwidth);
});
What I do for the first row is calculate what's left of the container, divide it by number of items on the row, and add the result to the width of each item on the row.
If I understood what you're trying to do, I made some small changes to the code
var lisInRow = 0;
var lisInRow2 = 0;
var row = 0;
$('div div').each(function() {
if($(this).prev().length > 0) {
if($(this).position().top != $(this).prev().position().top) row++;
lisInRow++;
$(this).addClass("row"+row);
//console.log($(this).prev().length)
}
else {
lisInRow++;
$(this).addClass("row0");
}
});
for(var i=0;i<=row;i++){
var itemNumber = $(".row"+i).length
console.log(row);
var widthRow = 0;
$(".row"+i).each(function() {
widthRow += $(this).outerWidth( true );
});
var widthContainer = $("#posts").width();
var remaining = widthContainer - widthRow;
leftMargin = Math.floor(remaining / itemNumber);
$(".row"+i).each(function(){
var addedwidth = $(this).width() + leftMargin;
$(this).width(addedwidth);
$(this).find("img").width(addedwidth);
});
}
Here you have it:
http://jsfiddle.net/SG9Vx/3/
Here's a simplified version of what I think you're trying to achieve:
var lisInRow = 0;
$('div div').each(function() {
if($(this).prev().length > 0) {
if($(this).position().top != $(this).prev().position().top){
lisInRow++;
}
$(this).addClass("row" + lisInRow);
}
});
Fiddle: http://jsfiddle.net/568mP/

Getting Javascript/jQuery scrolling function to work on successive divs

I'm currently trying to implement functionality similar to infinite/continuous/bottomless scrolling, but am coming up with my own approach (as an intern, my boss wants to see what I can come up with on my own). So far, I have divs of a fixed size that populate the page, and as the user scrolls, each div will be populated with an image. As of now, the function I've written works on the first div, but no longer works on successive divs.
$(window).scroll(function () {
var windowOffset = $(this).scrollTop();
var windowHeight = $(this).height();
var totalHeight = $(document).height();
var bottomOffset = $(window).scrollTop() + $(window).height();
var contentLoadTriggered = new Boolean();
var nextImageCount = parseInt($("#nextImageCount").attr("value"));
var totalCount = #ViewBag.totalCount;
var loadedPageIndex = parseInt($("#loadedPageIndex").attr("value"));
var calcScroll = totalHeight - windowOffset - windowHeight;
$("#message").html(calcScroll);
contentLoadTriggered = false;
if (bottomOffset >= ($(".patentPageNew[id='" + loadedPageIndex + "']").offset().top - 1000)
&& bottomOffset <= $(".patentPageNew[id='" + loadedPageIndex + "']").offset().top && contentLoadTriggered == false
&& loadedPageIndex == $(".patentPageNew").attr("id"))
{
contentLoadTriggered = true;
$("#message").html("Loading new images");
loadImages(loadedPageIndex, nextImageCount);
}
});
This is the image-loading function:
function loadImages(loadedPageIndex, nextImageCount) {
var index = loadedPageIndex;
for(var i = 0; i < nextImageCount; i++)
{
window.setTimeout(function () {
$(".patentPageNew[id='" + index + "']").html("<img src='/Patent/GetPatentImage/#Model.Id?pageIndex=" + index + "' />");
index++;
var setValue = index;
$("#loadedPageIndex").attr("value", setValue);
}, 2000);
}
}
I was wondering what may be causing the function to stop working after the first div, or if there might be a better approach to what I'm attempting?
EDIT: It seems that loadedPageIndex == $(".patentPageNew").attr("id") within the if statement was the culprit.
#ViewBag.totalCount; is not a JavaScript, it's .NET, so your script probably stops after encountering an error.
Also: ".patentPageNew[id='" + loadedPageIndex + "']" is inefficient. Since IDs must be unique, just query by ID instead of by class name then by ID.

Categories

Resources