Getting Javascript/jQuery scrolling function to work on successive divs - javascript

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.

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 - Each counting resetting issue

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;

How to scroll to the selected form field when key board shown in android app with javascript or jQuery?

I used this code to window scroll top in android app. but its scrolling total body. not till to selected form field. I want scroll till to selected form field.
here is my code
var is_keyboard = false;
var is_landscape = false;
var initial_screen_size = window.innerHeight;
window.addEventListener("resize", function() {
var currentHeight = window.innerHeight;
is_keyboard = (window.innerHeight < initial_screen_size);
is_landscape = (screen.height < screen.width);
var keyboardSize = (initial_screen_size - currentHeight);
if (keyboardSize > 0) {
alert("Keyboard is shown! Size is: " + keyboardSize);
} else {
alert("Keyboard is closed!");
}
alert('Screen resized. currentHeight: ' + currentHeight + " - OriginalHeight: " + initial_screen_size);
}, false);
To scroll to selected field you need to set a class or id on that element on capturing the event you need to check the flag on that element and then
find the offset and scroll the document to it.
Hope this helps
if (scroll_flag == ' scroll1'){
var fooOffset = $('#gift').offset(),
destination = fooOffset.top;
console.log(destination);
$(document).scrollTop(destination);
}

Resetting jquery varible to lowest possible value that doesn't exist

This script generate divs with cloud images that fly from left to right with random height and intervals. It generally works but it keeps incrementing divs "id" infinitely. I can't figure out how to reset the counter being safe that never two identical "id"s will exist in the same time.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
function cloud(type,time,nr){
$("#sky").append("<div id=\"cloudFL"+nr+"\" class=\"cloud"+type+"\" ></div>");
setTimeout(function() {
$("#cloudFL"+nr).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
var tx = 0;
setInterval(function(){
cloud(1,t1,nr);
nr++;
var n = $( "div.cloud1" ).length;
$( "span" ).text( "There are " + n +" n and "+ tx +" tx")
if(tx < n){tx = n}
else(tx = 1)
},500);
};
wave()};
cloudgenerator()
In the bottom, there is an instruction that checks if number of divs is starting to drop and presents those values in span for debugging.
Quick and easy solutionYou could loop through the id's in JQuery, starting from the lowest number, until you find a JQuery selector that yields 0 results...
var newid = 0;
var i = 1;
while(newid == 0) {
if( $('#cloudFL' + i).length == 0 ) { newid = i; }
else { i++; }
}
JSFIDDLE DEMO
Alternative solution (scalable)
Given that you may have many clouds onscreen at one time, you could try this alternative approach.
This approach creates an array of 'used ids' and the wave function then checks if any 'used ids' are available before creating a new id for the cloud function. This will run quite a bit more efficiently that then above 'quick fix solution' in situations where many clouds appear on screen.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
var spentids = [];
function cloud(type,time,id){
$("body").append('<div id="' + id + '" class="cloud' + type + '" >' + id + '</div>');
setTimeout(function() {
$('#'+id).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){
spentids.push( $(this).attr('id') );
$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
setInterval(function(){
if(spentids.length == 0) {
cloud(1,t1,"cloudFL" + nr);
nr++;
} else {
spentids = spentids.sort();
cloud(1,t1,spentids.shift());
}
},500);
};
wave()};
cloudgenerator()
JSFIDDLE DEMO - ALTERNATIVE
Why not get the timestamp and add this to your id?
If you donĀ“t need the ids i would stick to #hon2a and just add the styling to the class and remove the ids.
And another solution:
You could make a check if ID xyz is used. Like this e.g.
var cloudCount = jQuery('.cloud20000').length + jQuery('.cloud50000').length + 10;
for(var i = 0; i <= cloudCount; i++) {
if(jQuery('#cloudFL' + i).length <= 0) {
nr = i;
return false;
}
}
cloud(1,t1,nr);

javascript randomly fails to sort items, no error

For some reason Javascript stops working randomly.
Code that is dealing with height problem:
$(document).ready(function()
{
/*setEqualHeight($("ul#product_list li"));*/
//alert("some text");
/*setEqual($("ul#product_list"));*/
//var i = 2;
//alert($('ul#product_list li:nth-child('+ (i + 2) +')').height()); //this is correct way to get value*/
var elements = $('ul#product_list li').length; //this is correct way to get value
/*var liekana = elements % 3;
elements = elements - liekana;
alert(elements);*/
for(var i = 1; i <= elements; i = i + 3)
{
var first = $('ul#product_list li:nth-child('+ (i) +')').height();
var second = $('ul#product_list li:nth-child('+ (i + 1) +')').height();
var third = $('ul#product_list li:nth-child('+ (i + 2) +')').height();
var tallest = 0;
if (first > second)
if (first > third)
{
tallest = first;
}
else
{
tallest = third;
}
else
if (second > third)
{
tallest = second;
}
else
{
tallest = third;
}
$('ul#product_list li:nth-child('+ (i) +')').height(tallest);
$('ul#product_list li:nth-child('+ (i + 1) +')').height(tallest);
$('ul#product_list li:nth-child('+ (i + 2) +')').height(tallest);
/*if (!third)
alert("yra");*/
}
});
Failing URL: http://piguskompiuteris.lt/6_asus
Normal render URL: http://piguskompiuteris.lt/16-lenovo
Any suggestions how to solve this problem would be greatly appreciated. Thanks
UPDATE 2. I have rewriten javascript code... I still get the same random errors, sometimes grid collapses. I am not sure what is the cause.
Possible causes:
1) Height attribute is too small and doesn't include height + padding + margin + border
2) There is something wrong with function placement (currently not in header) or calling it $(document).ready(function()
I have checked your site. And found this solution use it:
columns.height(tallestcolumn);
Replace above code with the following code:
columns.css("min-height", tallestcolumn+" !imporatant");
This will work for you.
Sorting script works.
To fix script use:
$(window).load(function() {});
Out instead of:
$(document).ready(function() {});

Categories

Resources