I'm having issues increasing a variable by 1 every time I scroll. I successfully increase the variable by 1, but only once. This is the code I got. I need to increase the variable page.
$(document).ready(function () {
$(document).scroll(function (e) {
currentPage = 0;
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
++currentPage;
$.getJSON("../campus/Settings/TranslationSettings.ashx?command=show&page=" + currentPage + "&Lang=en", function (data) {
var items = [];
$.each(data.Keys, function (key, val) {
$("<ul/>", {
"class": "translateinfo",
html: "<li class='keystring'><span class='label'>text string:</span>" + val["text string"] + "</li>" + "<li class='autotranslate'><span class='label'>Automated translation:</span>" + val["automated translation"] + "</li>" + "<li class='functionnumber'><span class='label'>Function Number:</span>" + val["function number"] + "</li>" + "<li class='translateurl'><span class='label'>URL:</span>" + val["url"] + "</li>"
}).appendTo("#updatepanel");
});
});
}
});
});
Not sure if you copy/paste your entire code. But you're recreating currentPage everytime the user scroll
Working fiddle, I create the variable before the scroll loop.
var currentPage = 0;
$(document).scroll(function (e) {
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 10) {
++currentPage;
console.log(currentPage);
}
})
http://jsfiddle.net/dCr3Z/
Related
How to fix the error line of:
var targetTop = $('#' + page).offset().top;
I am trying last 3 months but still did not find a fix.
$(document).ready(function(){
$(window).scroll(function() {
$('.page').each(function () {
changePage(this.id);
});
});
});
function changePage (page) {
var position = $(window).scrollTop();
var targetTop = $('#' + page).offset().top;
var targetBottom = targetTop + $('#' + page).height();
if (position >= targetTop && position < targetBottom && !$('#' + page).hasClass('active')) {
console.log('id: ' + page);
$('.page').removeClass('active');
$('#' + page).addClass('active');
$('iframe').attr('src', '<?=SITE_URL?>upload_files/collection/TS.pdf#page=' + page[page.length - 1]+'&zoom=45&toolbar=0&navpanes=0');
}
}
$('#' + page) doesn't return any elements, which means $('#' + page).offset() returns undefined.
You can't get the .top property of undefined.
Apparently, the selector created with '#' + page is incorrect.
The cause is probably a undefined id in changePage(this.id);.
I'm using jQuery Justified gallery with the inbuilt infinite scroll plugin.
http://miromannino.github.io
This may be stupid question but how can i load the images dynamically with PHP.
I know how to do it with the below infinity scroll plugin but this plugin doesn't work with the infinity scroll plugin.
http://www.infinite-scroll.com/
Code
$('#gallery').justifiedGallery({rowHeight:120});
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
for (var i = 0; i < 5; i++) {
$('#gallery').append('<a>' +
'<img src="http://path/to/image" />' +
'</a>');
}
$('#gallery').justifiedGallery('norewind');
}
});
$('#gallery').justifiedGallery({rowHeight:120});
$(window).scroll(function(){
if($(window).scrollTop() + $(window).height() == $(document).height()){
//jquery ajax for dynemic loading images
$.ajax({
type:'post',//method can bet get,post
url:'yourPHPFile.php',//url of your php file
data:{"key":value},//if you want to send some data for query
success:function(result){ //function call when successful response from server
var PhpImageArray=JSON.parse(result);
$.each(PhpImageArray, function(index, item) {
$('#gallery').append('<a>' +
'<img src="http://path/to/image"'+item.image+' />' +
'</a>');
});
}
});
$('#gallery').justifiedGallery('norewind');
}
});
phpfile.php
<?php
//array contain image object as
$img_array=array();
//your database query
$query=mysqli_query($DB_connect,"select imageName from ImageTable");
while($img=mysqli_fetch_array($query))
{
//object name with "image"
$obj["image"]=$img["imageName"];
//push object to arraay
array_push($img_array,$obj);
}
//convert array in to json format for javascript use
echo json_encode($img_array);
?>
You could count the amount of images by using Javascript
var offset = $('#gallery').children().length
Then you could make an ajax call to a given route (e.g /giveImages) which returns an JSON-Array containing the image URL's
$.get('/giveImages?offset=' + offset, function(data) {
// data = [
// 'http://foo.com/image/3.jpg',
// 'http://foo.com/image/4.jpg',
// 'http://foo.com/image/5.jpg'
// ]
// APPEND STUFF HERE AND justifyGallery
})
Full example:
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
var offset = $('#gallery').children().length
$.get('/giveImages?offset=' + offset, function(data) {
for(var i = 0; i < data.length; i++) {
$('#gallery').append(
'<a>' +
'<img src="' + data[i] + '" />' +
'</a>'
)
$('#gallery').justifiedGallery('norewind')
}
})
}
}
So I have a several tables with several rows and columns. Since the information is huge I want to keep the table headers fixed on top when scrolling.
When the one header comes, the previous one will hide and the current one will stay fixed.
This is the js code I have so far:
function makeTableHeadersSticky(tableId) {
var thArr = $(tableId + " th");
var thWidthsArr = [];
var calcWidth = 0;
$(tableId + " th").each(function(){
calcWidth = $(this).css("width");
thWidthsArr.push(calcWidth);
});
var pos = $(tableId).offset();
var thTop = pos.top + "px";
var count = 0;
$(tableId + " tr:first-child > th").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
count = 0;
$(tableId + " tr:last-child > td").each(function(){
$(this).css("width", thWidthsArr[count]);
count++;
});
$(window).scroll(function() {
//var firstRow = $(tableId + " tr:first-child").offset();
var lastRow = $(tableId + " tr:last-child").offset();
var w = $(window);
//console.log("(first,last): ("+(firstRow.top-w.scrollTop())+","+(lastRow.top-w.scrollTop())+")");
if(($(window).scrollTop() > pos.top) && (lastRow.top-w.scrollTop() >= 0)) {
$(tableId + " tr:first-child").css("position", "fixed");
$(tableId + " tr:first-child").css("top", "0px");
$(tableId + " tr:first-child").css("left", "9px");
} else {
$(tableId + " tr:first-child").css("position", "static");
$(tableId + " tr:first-child").css("top", thTop);
}
});
}
makeTableHeadersSticky("#myTable");
If you see on my code I played with the positions of the table and the last row of the table to see where the table is. This way I can set the header position as fixed or static.
Here is my jsfiddle
Everything works just fine here. You just omitted to call the makeTableHeadersSticky function for the second table :
makeTableHeadersSticky("#myTable2");
demo
I'm using the .each function to hide/show columns of a table. But the problem is that the code is very slow in IE. After searching on internet I saw that could be because of my .each() function and $(this).
For more information why I'm using this code, you can look at this post: Hide/show column
This is my old code:
include JQuery.min.js on page
javascript:
$(function () {
$('table th').each(function (_id, _value) {
if(_id > 2){
if($(this).find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($(this).find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$(this).find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(_id + 1) + '),table th:nth-of-type(' + parseInt(_id + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
});
});
HTML:
<div id="togglers">Show/Hide columns<br/></div>
I tried to convert my javascript with this code (Source: jQuery very slow in IE), but I think there is still a problem with my i(or _id) and _value...
$(function () {
var items = $('table th');
var $currentItem;
for (var i = 0, j = items.length; i < j; i++) {
$currentItem = $(items[i]); // in place of $(this)
function (i, _value) {
if(i > 2){
if($currentItem.find("a").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("a").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
else{
if($currentItem.find("div").text()){
$('<span class="ShowHide"><div style="width:175px; display: inline-block;">- '+$currentItem.find("div").text()+'</div></span>').appendTo($("#togglers")).click(function (e) {
$('table td:nth-of-type(' + parseInt(i + 1) + '),table th:nth-of-type(' + parseInt(i + 1) + ')').toggle();
e.preventDefault();
});
}
}
}
}
}
});
It's possible that I need to use other code. Any suggestion is welcome! Tnx.
Performance issue has nothing to do with .each. DOM is tens of times slower than any way to iterate collection you choose.
Instead of iterating table on every toggle you can make CSS do it for you. Demo.
$(function() {
var togglers = $('#togglers'), //cache toggler ref
addToggler = function(idx, text) {
togglers.append('<span class="toggler" data-id="'
+ idx + '">' + text + '</span>');
},
table = $('#table'), //cache table ref
columns = 0;
//generate styles for 100 columns table :)
(function generateStyleSheet(len){
var styles = [], i = 0;
for(; i < len; i++) {
styles.push('.hide-' + i + ' .column-' + i + ' {display: none;}') ;
}
$('<style>' + styles.join('\n') + '</style>').appendTo(document.body);
}(100))
//bind on click once using event delegation
togglers.on('click', '.toggler', function(e){
var id = $(e.target).toggleClass('pressed').data('id');
table.toggleClass('hide-' + id);
});
//generate all togglers and count em
table.find('th').each(function(idx, header){
header = $(header);
addToggler(idx, header.text()); //make toggler
header.addClass('column-' + idx); //add class column-i
columns++;
});
//add column-i class to tds
table.find('td').each(function(idx, td) {
$(td).addClass('column-' + (idx%columns));
});
});
As the below demo, When I drag the mouse to the Week and I can't scroll to see the final <li> in the HTML's block and this might not run smoothly as well. I don't know what's wrong here, please take a look on it and let me know to how modify this.
Demo
HTML:
<div class="yearly">2014
<div class="container">
<ul class="ca-menu"></ul>
</div>
</div>
Javascript:
$(document).ready(function () {
$(".yearly").mouseover(function () {
var num_month = 48;
var current_year = 2014;
for (i = num_month; i >= 1; i--) {
$(".ca-menu").after("<li class='weekly'><a href='/Lists/ChartIndex.aspx?Week=" + i + "&Year=" + current_year + "'>Week " + i + "</a></li>");
}
})
.mouseout(function () {
$(".weekly").hide();
});
});
The reason you are not being able to scroll to the bottom is because when you hover over the <li> links, mouseover event is repeatedly called.
Try this
$(document).ready(function(){
$(".yearly").hover(function () {
console.log('yahh');
var num_month = 48;
var current_year = 2014;
for (i = num_month; i >= 1; i--) {
$(".ca-menu").after("<li class='weekly'><a href='/Lists/ChartIndex.aspx?Week=" + i + "&Year=" + current_year + "'>Week " + i + "</a></li>");
}
},
function () {
$(".weekly").hide();
});
});
This is because you keep on creating the <li> when your mouse move over.
make your <li> list outside the mouse over function. Then just show and hide it with respective mouse event:
$(document).ready(function () {
var num_month = 48;
var current_year = 2014;
for (i = num_month; i >= 1; i--) {
$(".ca-menu").after("<li class='weekly'><a href='/Lists/ChartIndex.aspx?Week=" + i + "&Year=" + current_year + "'>Week " + i + "</a></li>");
}
$(".weekly").hide();
$(".yearly").mouseover(function () {
$(".weekly").show();
})
.mouseout(function () {
$(".weekly").hide();
});
});
JSfiddle