I have a page with filters on top and a toggle between tile view or map view.
Every time a filter is changed I perform a search with AJAX and change the view using Mustache.
On mobile the default view is the tile view with an icon on the bottom right to toggle the map.
When my view is on the tile view, I change a filter (so the search triggers and filtered tiles show up), i then toggle to the map view and it is max zoomed out, and only the bottom left corner is not greyed out. It looks like this:
When I load the page, and i immediately toggle to my map view, that is also the initial view I see. But if I then change my filters and perform the search again, the map will load correctly and works perfectly. But after switching to tiles, changing filters and going back to Map view, it breaks again.
This is the HTML holder for the map:
<div id="map_canvas"></div>
jQuery:
$(document).ready(function(){
'use strict';
curr_lang = $('#curr_lang').val();
initializeElements();
//Read the query parameters & set everything up according to it
setupConfig(radiusSlider);
//Setup the listeners for the freetext input search field
setupFreetextField();
setupInterestsField();
setupLocationField();
setupDaterangeField();
setupMorefiltersField();
});
function initializeElements() {
$(window).scroll(function() {
var volunteer = $('#map_canvas');
var offset = volunteer.offset();
top = offset.top;
state = $('.footer').offset().top;
var bottom = $('#map_canvas').offset().top;
if ($(window).scrollTop() + volunteer.height() + 134 > state) {
volunteer.removeClass('fixed');
volunteer.addClass('bottom');
} else if ($(this).scrollTop() + 58 > bottom) {
volunteer.addClass('fixed');
volunteer.removeClass('bottom');
} else {
volunteer.removeClass('fixed');
volunteer.removeClass('bottom');
}
//Enable search toggle menu icon
if ($(window).width() <= 768) {
var nav = $('.navbar-wrapper');
var navOffset = nav.offset();
var filters = $('.content-filters');
var filtersOffset = filters.offset().top;
var searchToggle = $('.search-filter-toggle');
if ($(window).scrollTop() > filters.height()) {
searchToggle.addClass('show');
} else {
searchToggle.removeClass('show');
filters.removeClass('mobile-filters');
}
}
});
if ($(window).width() <= 768) {
$('.search-filter-toggle').on('click',function(e) {
var filters = $('.content-filters');
filters.toggleClass('mobile-filters');
});
}
$(window).resize(function() {
var vacancyGrid = $('.vacancy-holder');
var mapGrid = $('.map-holder');
if ($(window).width() > 1227) {
vacancyGrid.removeClass('hide-mobile');
mapGrid.removeClass('show-mobile');
$('#mapview').removeClass('hide-mobile');
$('#gridview').removeClass('show-mobile');
$(document.body).removeClass('map');
}else if($(window).width() < 991){
}
});
$('#mapview').on('click',function(e) {
map.invalidateSize(false);
var vacancyGrid = $('.vacancy-holder');
var mapGrid = $('.map-holder');
vacancyGrid.addClass('hide-mobile');
vacancyGrid.removeClass('show-mobile');
mapGrid.addClass('show-mobile');
mapGrid.removeClass('hide-mobile');
$('#mapview').addClass('hide-mobile');
$('#mapview').removeClass('show-mobile');
$('#gridview').addClass('show-mobile');
$('#gridview').removeClass('hide-mobile');
$(document.body).addClass('map');
$("html, body").animate({ scrollTop: 0 });
});
$('#gridview').on('click',function(e) {
var vacancyGrid = $('.vacancy-holder');
var mapGrid = $('.map-holder');
vacancyGrid.addClass('show-mobile');
vacancyGrid.removeClass('hide-mobile');
mapGrid.addClass('hide-mobile');
mapGrid.removeClass('show-mobile');
$('#mapview').addClass('show-mobile');
$('#mapview').removeClass('hide-mobile');
$('#gridview').addClass('hide-mobile');
$('#gridview').removeClass('show-mobile');
$(document.body).removeClass('map');
$("html, body").animate({ scrollTop: 0 });
});
}
function setupMap(vacancies) {
//Destroy the map if it already exists
if (map != undefined) {
map.remove();
}
console.log("setting up the map...");
// this script enable displaying map with markers spiderfying and clustering using leaflet plugin
var vacArr = [];
var index = 0;
if (vacancies.length > 0) {
for (index = 0; index < vacancies.length; ++index) {
var vacancy = vacancies[index];
if (((vacancy.lat != 0) && (vacancy.lat !== undefined) && (vacancy.lat != null)) && ((vacancy.lng !=0) && (vacancy.lng !== undefined) && (vacancy.lat != null))) {
var vacurl = vacancy.detailurl;
var tempArr = [];
tempArr.push(vacancy.lng);
tempArr.push(vacancy.lat);
tempArr.push(vacurl);
tempArr.push(vacancy.name);
tempArr.push(vacancy.orgname);
vacArr.push(tempArr);
}
}
}
var tiles = L.tileLayer('//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
maxZoom: 18,
attribution: '© OpenStreetMap contributors, Points © 2012 LINZ'
});
map = L.map('map_canvas', {
center: L.latLng(51.260197, 4.402771),
zoom: 10,
layers: [tiles]
});
var mcg = L.markerClusterGroup({
chunkedLoading: true,
spiderfyOnMaxZoom: true,
showCoverageOnHover: true //zoomToBoundsOnClick: false
});
var boundsarray = [];
for (var i = 0; i < vacArr.length; i++) {
var detailText = res.ViewDetail;
var info ="<div id='infoId-' style=\"background:white\"> <h5>"+vacArr[i][3] +"</h5> <p class=\"marker_font\">"+vacArr[i][4]+"</p> "+detailText+"</p></div>";
var title=vacArr[i][3];
var marker = L.marker(new L.LatLng(vacArr[i][1], vacArr[i][0]), {
title: title
});
boundsarray.push([vacArr[i][1], vacArr[i][0]]);
mcg.on('clusterclick', function (a) {
if('animationend zoom level: ', map.getZoom() >13)
{
a.layer.spiderfy();
}
});
marker.bindPopup(info);
mcg.addLayer(marker);
}
//console.log(boundsarray);
map.fitBounds(boundsarray);
map.addLayer(mcg);
}
EDIT: I added the complete code after trying to add map.invalidateSize(); on the map toggle function. But it results in the same.
The setupMap() function is called at the end of my AJAX success method for searching. (The vacancies parameter is the result from my AJAX method and contains the information for the tiles and as well the lat/lon of the vacancy)
I had a same problem ( Uncompleted load ) and I tried it with setTimeout and it solved.
setTimeout(function () {
if (!myMap)
loadmap(); /*load map function after ajax is complitly load */
}, 1000);
setTimeout(function () {
if (myMap)
myMap.invalidateSize();
}, 1500);
I hope it helps;
I had a similar problem, it seems the tiles load, but are not positioned.
I found that loading the tiles inside the setTimeout rather than at map initialisation, even with a zero timeout, worked. e.g:
setTimeout(function () {
tiles.addToMap(map);
},0);
This delays the rendering of the tiles long enough to ensure other script do not interfere.
Possibly the mirage script from CloudFlare is a source of the problem, but I did not have access to change CloudFlare settings for this site.
Note, in my final implementation though, I included all the map code inside the timeout so as not to have the short but noticeable delay before the tiles are rendered.
Related
I have a UK county shape file (Multipolygon) using EPSG:4326 in my geoserver. I'm using open layers 3 to load this shape file in my application as below :
source = new ol.source.XYZ({url: '/gmaps?zoom={z}&x={x}&y={y}&Layers=UKCounties', crossOrigin: "anonymous"});
countiesLayer = new ol.layer.Tile({source: source});
map.addLayer(countiesLayer);
This works well. I have a requirement to get users current location which is done as
var coordinate = geolocation.getPosition();
I'm able to retrieve the correct lat & long here. Ex : Lat = 53.797534899999995, Lng = -1.5449. now I need to check which of the counties (polygon) these points are in using open layers 3 & Javascript.
Using Geoserver WFS, I'm able to get the bounding box of each of the counties as
$.each(features, function(index, eachFeature) {
var bbox = eachFeature.properties.bbox;
if (bbox != null) {
var bottomLeft = ([bbox[0], bbox[1]]);
var topRight = ([bbox[2], bbox[3]]);
var extent = new ol.extent.boundingExtent([bottomLeft, topRight]);
if (ol.extent.containsXY(extent1,lat,long)) {
alert("got the feature");
}
}
});
The issue is my code doesn't print the alert statement.I've also tried using
if (ol.extent.containsXY(extent,long,lat))
and
var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
if (ol.extent.containsXY(extent,XY[0],XY[1]))
if (ol.extent.containsXY(extent,XY[1],XY[0]))
But none of these print the alert. Is there anything wrong in this?
Before answering your question, I did not know the method of "ol.extent.containsXY".
I used my poor logic! I detected a feature if in a polygon by follwing :
transform feature and container(polygon) to coordinate [lon, lat]
detect the container if contain the feature
extent array rule [minLon, minLat, maxLon, maxLat]
code snippet: (my destinationPro:'EPSG:3857', sourcePro:'EPSG:4326')
QyGIS.prototype.isInner = function(featureExtent, containerExtent) {
var featureLonLat = ol.proj.transformExtent(featureExtent, destinationPro, sourcePro);
var containerLonLat = ol.proj.transformExtent(containerExtent, destinationPro, sourcePro);
// in my condition, the feature is a point, so featureLonLat[0] = featureLonLat[2], featureLonLat[1] = featureLonLat[3]. what's more extent have four value in a array so the loop length is 4
for (var i = 0; i < featureLonLat.length; i++) {
/* actually:
featureLonLat[0] < containerLonLat[0] || featureLonLat[0] > containerLonLat[2]
featureLonLat[1] < containerLonLat[1] || featureLonLat[1] > containerLonLat[3]
featureLonLat[2] < containerLonLat[0] || featureLonLat[2] > containerLonLat[2]
featureLonLat[3] < containerLonLat[1] || featureLonLat[3] > containerLonLat[3]
*/
if (featureLonLat[i] < containerLonLat[i % 2] || featureLonLat[i] > containerLonLat[i % 2 + 2]) {
return false;
}
}
return true;
};
QyGIS.prototype.getInnerFeatures = function(layerName, extent) {
var self = this;
var layer = self.getLayer(layerName);
if (layer) {
var source = layer.getSource();
var features = source.getFeatures();
for (var i = 0; i < features.length; i++) {
var curFeatureExtent = features[i].getGeometry().getExtent();
if (self.isInner(curFeatureExtent, extent)) {
console.log(features[i].get('name') + 'in area');
}
}
}
};
At last, sorry for my poor english if my answer confuse you .
I had to use
var XY = ol.extent.applyTransform(extent, ol.proj.getTransform("EPSG:3857", "EPSG:4326"));
instead of
var XY = ol.proj.transform([long, lat], 'EPSG:4326', 'EPSG:3857');
and it works.
I am busy writing a simple map implementation using leaflet however I have hit a bit of a snag. I am trying to setup my map and have added a custom control to show labels (which will show the popups) based on the selection of a checkbox.
My custom control is like so:
var checkBoxControl = L.Control.extend({
options: {
position: 'topright'
},
onAdd: function (map) {
var container = L.DomUtil.create('input', 'leaflet-control');
container.style.backgroundColor = 'white';
container.id = 'labels_checkbox';
container.style.width = '30px';
container.style.height = '30px';
container.label = "Labels";
container.type = 'checkbox';
container.onclick = function () {
var checkBox = $("#labels_checkbox");
var checkBoxValue = checkBox[0];
var labelsChecked = checkBoxValue.checked;
var bounds = mymap.getBounds();
for (var i = 0; i < markers.length; i++) {
marker = markers[i].mark;
if (bounds.contains(marker.getLatLng())) {
var previewLabel = markers[i].previewLabel;
if (labelsChecked == true) {
console.log('previewLabel', previewLabel);
mymap.addLayer(previewLabel).fire('popupopen');
} else {
previewLabel.close();
}
}
}
};
return container;
}
});
I can see as per my console that it is fetching all the surrounding markers however the map won't open those markers?
Is there a way for me to open a popup without binding it to a marker?
Thanks
You have to change L.Map behaviour to prevent automatic closing of popups.
It is discussed here.
// prevent a popup to close when another is open
L.Map = L.Map.extend({
openPopup: function (popup, latlng, options) {
if (!(popup instanceof L.Popup)) {
var content = popup;
popup = new L.Popup(options).setContent(content);
}
if (latlng) {
popup.setLatLng(latlng);
}
if (this.hasLayer(popup)) {
return this;
}
// NOTE THIS LINE : COMMENTING OUT THE CLOSEPOPUP CALL
//this.closePopup();
this._popup = popup;
return this.addLayer(popup);
}
});
See this example
I've got real time gps positions for a few cars and I want to create a map with updating markers. My code works but it doesn't "update" the markers, instead it adds new objects with new coordinates to the leaflet map. After few minutes my map is full of markers. What I'm doing wrong? Here is my basic concept.
var intervalV = document.getElementById("intervalValue").value * 1000;
document.getElementById("setIntervalButton").onclick = startData;
function startData() {
DataInterval = window.setInterval(getNewData, intervalV);
};
function getNewData() {
$.getJSON(server, {
fun : "GetGpsData",
userId : "user",
sessionId : $("#sessionId").val()
}, fillMap);
}
function fillMap(json) {
for (var i = 0; i < json.devicesData.length; i++) {
var positions = json.devicesData[i].positions.length;
var devicepostiion;
if (json.devicesData[i].connected == false
) {
var devicepostion = L.marker([json.devicesData[i].positions[positions - 1].lat, json.devicesData[i].positions[positions - 1].lon], {
icon : offlineCarIcon
}, {
draggable : false
}).addTo(map);
} else {
devicepostion = new L.marker(, {
icon : onlineCarIcon
});
devicepostion.addTo(map).setLatLng([json.devicesData[i].positions[positions - 1].lat, json.devicesData[i].positions[positions - 1].lon]).update();
}
}
}
};
If your goal is to update markers with a new visual appearance and location if they already exist on the map...then you should be using .setIcon and .setLatLng on the existing marker instead of making a new one.
Your current code makes new markers in both cases.
Here your code updated to work as you want. As #snkashis pointed out, you do not need to create a new marker each time
var devicePosition = -1;
function fillMap(json) {
for (var i = 0; i < json.devicesData.length; i++) {
var data = json.devicesData[i];
if (data.positions) {
var index = data.positions.length - 1;
if (data.positions[index].lat && data.positions[index].lon) {
var latLng = L.latLng(parseFloat(data.positions[index].lat), parseFloat(data.positions[index].lon));
if (devicePosition === -1) {
var devicePosition = L.marker(latLng, {draggable : false})
.addTo(map);
} else {
devicePosition.setLatLng(latLng)
.update();
}
// Optional if you want to center the map on th marker
// map.panTo(latLng);
}
}
if (data.connected && devicePosition !== -1) {
devicePosition.setIcon(data.connected ? 'onlineCarIcon' : 'offlineCarIcon');
}
}
If you have multiple markers, you need to update each one accordingly to their id, I suggest to find (or add, if you create the APIs) an unique ID in json.devicesData[i].
Let's suppose the uniqueId of each marker is called, well, uniqueId, then your code can be something like this:
var devicePosition = {};
function fillMap(json) {
for (var i = 0; i < json.devicesData.length; i++) {
var data = json.devicesData[i];
var uniqueId = data.uniqueId;
if (data.positions) {
var index = data.positions.length - 1;
if (data.positions[index].lat && data.positions[index].lon) {
var latLng = L.latLng(parseFloat(data.positions[index].lat), parseFloat(data.positions[index].lon));
if (!devicePosition[uniqueId]) {
var devicePosition[uniqueId] = L.marker(latLng, {draggable : false})
.addTo(map);
} else {
devicePosition[uniqueId].setLatLng(latLng)
.update();
}
// Optional if you want to center the map on th marker
// map.panTo(latLng);
}
}
if (data.connected && devicePosition[uniqueId]) {
devicePosition[uniqueId].setIcon(data.connected ? 'onlineCarIcon' : 'offlineCarIcon');
}
}
I have some serious question. How can i set multiple popups to be opened at the same time? I am using this code to open a popup:
var container = document.getElementById('popup');
var content = document.getElementById('popup-content');
var closer = document.getElementById('popup-closer');
closer.onclick = function() {
overlay.setPosition(undefined);
closer.blur();
return false;
};
var overlay = new ol.Overlay({
element: container
});
And for viewing content for specific feature in cluster at specific coordinates i use this:
map.on('click', function (evt) {
var feature = map.forEachFeatureAtPixel(evt.pixel,
function (feature, layer) { return feature; });
var coordinate = evt.coordinate;
var prop;
var vyprop = "";
overlay.setPosition(coordinate);
var features = feature.get('features');
for(var i = 0; i < features.length; i++) {
prop = features[i].getProperties();
vyprop += prop.odbermisto + "<br>";
}
content.innerHTML = vyprop;
});
Because it uses div as a content and moves it from coordinates, hwere it is needed, I ain't able to open two popups at the same time. is there any solution to do that, without duplicating and deleting divs, which i dont wanna do? Thx for help guys
I'm using jQuery Tools Plugin as image slider (image here), but due to large amount of images I need to load them few at a time. Since it's javascript coded, I can't have the scroll position as far as I know. I want to load them as soon as the last image shows up or something like that. I have no idea where I put and event listener neither anything.
Here is my code http://jsfiddle.net/PxGTJ/
Give me some light, please!
I just had to use jQuery Tools' API, the onSeek parameter within the scrollable() method.
It was something like that
$(".scrollable").scrollable({
vertical: true,
onSeek: function() {
row = this.getIndex();
// Check if it's worth to load more content
if(row%4 == 0 && row != 0) {
var id = this.getItems().find('img').filter(':last').attr('id');
id = parseInt(id);
$.get('galeria.items.php?id='+id, null, function(html) {
$('.items').append(html);
});
}
}
});
That could be made the following way:
//When the DOM is ready...
$(document).ready(function() {
//When the user scrolls...
$(window).scroll(function() {
var tolerance = 800,
scrollTop = $(window).scrollTop();
//If the the distance to the top is greater than the tolerance...
if(scrollTop > tolerance) {
//Do something. Ajax Call, Animations, whatever.
}
}) ;
});
That should do the trick.
EDIT: Because you're not using the native scroll, we've got to do a little fix to the code:
//When the DOM is ready...
$(document).ready(function() {
//When the user scrolls...
$("div.scrollable").find(".next").click(function() {
var tolerance = 800,
// The absolute value of the integer associated
// to the top css property
scrollTop = Math.abs(parseInt($("div.items").css("top")));
//If the the distance to the top is greater than the tolerance...
if(scrollTop > tolerance) {
//Do something. Ajax Call, Animations, whatever.
}
}) ;
});
try something like this
$('#scrollable').find('img:last').load(function() {
//load the content
});
OR find the offset location/position of the last image and try loading your content when you reach the offset position on scrolling
HTML :
<div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<span>Hello !!</span>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br>
</div>
some CSS :
div {
width:200px;
height:200px;
overflow:scroll;
}
Javascript :
$(document).ready(function() {
$('div').scroll(function() {
var pos = $('div').scrollTop();
var offset = $('span').offset().top;
if(pos >= offset ) {
alert('you have reached your destiny');
}
});
});
here's a quick demo http://jsfiddle.net/8QbwU/
Though Demo doesn't met your full requirements, I believe It does give you some light to proceed further :)
First, you'll want to use jQuery for this
Second, put a placeholder on your page to contain your data.
<table id="dataTable" class="someClass" style="border-collapse: collapse;">
<colgroup>
<col width="12%" />
<col width="12%" />
<col width="12%" />
<!-- Define your column widths -->
</colgroup>
</table>
You'll need to code your own GetData method in a webservice, but this is the general idea (And call Refresh(); from your page load)
function Refresh() {
var getData = function(callback, context, startAt, batchSize) {
MyWebservice.GetData(
startAt, //What record to start at (1 to start)
batchSize, //Results per page
3, //Pages of data
function(result, context, method) {
callback(result, context, method);
},
null,
context
);
};
$('#dataTable').scrolltable(getData);
}
The getData function variable is passed into the scrolltable plugin, it will be called as needed when the table is being scrolled. The callback and context are passed in, and used by the plugin to manage the object you are operating on (context) and the asynchronous nature of the web (callback)
The GetData (note the case) webmethod needs to return a JSON object that contains some critical information, how your server side code does this is up to you, but the object this plugin expects is the following. The Prior and Post data are used to trigger when to load more data, basically, you can scroll through the middle/active page, but when you start seeing data in the prior or post page, we're going to need to fetch more data
return new {
// TotalRows in the ENTIRE result set (if it weren't paged/scrolled)
TotalRows = tableElement.Element("ResultCount").Value,
// The current position we are viewing at
Position = startAt,
// Number of items per "page"
PageSize = tableElement.Element("PageSize").Value,
// Number of pages we are working with (3)
PageCount = tableElement.Element("PageCount").Value,
// Data page prior to active results
PriorData = tbodyTop.Html(),
// Data to display as active results
CurrentData = tbodyCtr.Html(),
// Data to display after active results
PostData = tbodyBot.Html()
};
Next is the plugin itself
/// <reference path="../../js/jquery-1.2.6.js" />
(function($) {
$.fn.scrolltable = function(getDataFunction) {
var setData = function(result, context) {
var timeoutId = context.data('timeoutId');
if (timeoutId) {
clearTimeout(timeoutId);
context.data('timeoutId', null);
}
var $table = context.find("table");
var $topSpacer = $table.find('#topSpacer');
var $bottomSpacer = $table.find('#bottomSpacer');
var $newBodyT = $table.children('#bodyT');
var $newBodyC = $table.children('#bodyC');
var $newBodyB = $table.children('#bodyB');
var preScrollTop = context[0].scrollTop;
$newBodyT.html(result.PriorData);
$newBodyC.html(result.CurrentData);
$newBodyB.html(result.PostData);
var rowHeight = $newBodyC.children('tr').height() || 20;
var rowCountT = $newBodyT.children('tr').length;
var rowCountC = $newBodyC.children('tr').length;
var rowCountB = $newBodyB.children('tr').length;
result.Position = parseInt(result.Position);
$newBodyC.data('firstRow', result.Position);
$newBodyC.data('lastRow', (result.Position + rowCountC));
context.data('batchSize', result.PageSize);
context.data('totalRows', result.TotalRows);
var displayedRows = rowCountT + rowCountC + rowCountB;
var rowCountTopSpacer = Math.max(result.Position - rowCountT - 1, 0);
var rowCountBottomSpacer = result.TotalRows - displayedRows - rowCountTopSpacer;
if (rowCountTopSpacer == 0) {
$topSpacer.closest('tbody').hide();
} else {
$topSpacer.closest('tbody').show();
$topSpacer.height(Math.max(rowCountTopSpacer * rowHeight, 0));
}
if (rowCountBottomSpacer == 0) {
$bottomSpacer.closest('tbody').hide();
} else {
$bottomSpacer.closest('tbody').show();
$bottomSpacer.height(Math.max(rowCountBottomSpacer * rowHeight, 0));
}
context[0].scrollTop = preScrollTop; //Maintain Scroll Position as it sometimes was off
};
var onScroll = function(ev) {
var $scrollContainer = $(ev.target);
var $dataTable = $scrollContainer.find('#dataTable');
var $bodyT = $dataTable.children('tbody#bodyT');
var $bodyC = $dataTable.children('tbody#bodyC');
var $bodyB = $dataTable.children('tbody#bodyB');
var rowHeight = $bodyC.children('tr').height();
var currentRow = Math.floor($scrollContainer.scrollTop() / rowHeight);
var displayedRows = Math.floor($scrollContainer.height() / rowHeight);
var batchSize = $scrollContainer.data('batchSize');
var totalRows = $scrollContainer.data('totalRows');
var prevRowCount = $bodyT.children('tr').length;
var currRowCount = $bodyC.children('tr').length;
var postRowCount = $bodyB.children('tr').length;
var doGetData = (
(
(currentRow + displayedRows) < $bodyC.data('firstRow') //Scrolling up
&& (($bodyC.data('firstRow') - prevRowCount) > 1) // ...and data isn't already there
)
||
(
(currentRow > $bodyC.data('lastRow')) //Scrolling down
&& (($bodyC.data('firstRow') + currRowCount + postRowCount) < totalRows) // ...and data isn't already there
)
);
if (doGetData) {
var batchSize = $scrollContainer.data('batchSize');
var timeoutId = $scrollContainer.data('timeoutId');
if (timeoutId) {
clearTimeout(timeoutId);
$scrollContainer.data('timeoutId', null);
}
timeoutId = setTimeout(function() {
getDataFunction(setData, $scrollContainer, currentRow, batchSize);
}, 50);
$scrollContainer.data('timeoutId', timeoutId);
}
};
return this.each(function() {
var $dataTable = $(this);
if (!getDataFunction)
alert('GetDataFunction is Required');
var batchSize = batchSize || 25;
var outerContainerCss = outerContainerCss || {};
var defaultContainerCss = {
overflow: 'auto',
width: '100%',
height: '200px',
position: 'relative'
};
var containerCss = $.extend({}, defaultContainerCss, outerContainerCss);
if (! $dataTable.parent().hasClass('_outerContainer')) {
$dataTable
.wrap('<div class="_outerContainer" />')
.append($('<tbody class="spacer"><tr><td><div id="topSpacer" /></td></tr></tbody>'))
.append($('<tbody id="bodyT" />'))
.append($('<tbody id="bodyC" />'))
.append($('<tbody id="bodyB" />'))
.append($('<tbody class="spacer"><tr><td><div id="bottomSpacer" /></td></tr></tbody>'));
}
var $scrollContainer = $dataTable.parent();
$scrollContainer
.css(containerCss)
.scroll(onScroll);
getDataFunction(setData, $scrollContainer, 1, batchSize);
});
};
})(jQuery);
You'll likely need to tweak some things. I just converted it to a jQuery plugin and it's probably still a little glitchy.