Datatables date range filter - javascript

How to add date range filter..
like From-To .
I got working regular search and pagination, etc..
But I dont know how to make date range filter.
I'm using Datatables 1.10.11 version.
My code:
var oTable;
function callFilesTable($sPaginationType, $bPaginate, $bFilter, $iDisplayLength, $fnSortcol, $fnSortdir){
$.extend($.fn.dataTableExt.oStdClasses, {
sSortAsc : 'header headerSortDown',
sSortDesc : 'header headerSortUp',
sSortable : 'header'
});
oTable = $('#sort').DataTable({
dom : '<"table-controls-top"fl>rt<"table-controls-bottom"ip>',
pagingType : $sPaginationType,
paging : $bPaginate,
searching : $bFilter,
pageLength : $iDisplayLength,
order : [ [$fnSortcol, $fnSortdir] ],
columnDefs : [
{
width : '50%',
targets : [ 2 ],
orderable : true,
searchable : true,
type : 'natural'
},
{
width : '10%',
targets : [ 3 ],
orderable : true
},
{
width : '20%',
targets : [ 4 ],
orderable : true
},
{
targets : ['_all'],
orderable : false,
searchable : false
}
],
language : paginationTemplate,
drawCallback : function() {
checkSelecta();
placeHolderheight();
// hide pagination if we have only one page
var api = this.api();
var pageinfo = api.page.info();
var paginateRow = $(this).parent().find('.dataTables_paginate');
if (pageinfo.recordsDisplay <= api.page.len()) {
paginateRow.css('display', 'none');
} else {
paginateRow.css('display', 'block');
}
}
});
oTable.on( 'length.dt', function ( e, settings, len ) {
updateSession({ iDisplayLength: len });
});
}
And I'm using NaturalSort 0.7 version.

I got mine working base on https://www.datatables.net/examples/plug-ins/range_filtering.html. Here is my jsfiddle https://jsfiddle.net/bindrid/2bkbx2y3/6/
$(document).ready(function () {
$.fn.dataTable.ext.search.push(
function (settings, data, dataIndex) {
var min = $('#min').datepicker('getDate');
var max = $('#max').datepicker('getDate');
var startDate = new Date(data[4]);
if (min == null && max == null) return true;
if (min == null && startDate <= max) return true;
if (max == null && startDate >= min) return true;
if (startDate <= max && startDate >= min) return true;
return false;
}
);
$('#min').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
$('#max').datepicker({ onSelect: function () { table.draw(); }, changeMonth: true, changeYear: true });
var table = $('#example').DataTable();
// Event listener to the two range filtering inputs to redraw on input
$('#min, #max').change(function () {
table.draw();
});
});

Following one using momentsjs, the advantage of momentsjs is we can compare different types of date/date time as simple
$.fn.dataTableExt.afnFiltering.push(
function( settings, data, dataIndex ) {
var min = $('#min-date').val()
var max = $('#max-date').val()
var createdAt = data[0] || 0; // Our date column in the table
//createdAt=createdAt.split(" ");
var startDate = moment(min, "DD/MM/YYYY");
var endDate = moment(max, "DD/MM/YYYY");
var diffDate = moment(createdAt, "DD/MM/YYYY");
//console.log(startDate);
if (
(min == "" || max == "") ||
(diffDate.isBetween(startDate, endDate))
) { return true; }
return false;
}
);

Related

Caluclate total in dynamiclly created JQuery datatable form JSON?

Am new to JavaScript & jQuery. Using jQuery datatables to populate data from JSON API. Table Header is also dynamic which means JSON variable as header text. How to add the total(Column & Row). Want rowwise total and columnwise total.
In this table want to add the Total text at the end of the row and column. Row total and column total.
Ajax Coding:-
function manufacturingSummary(todayDate) {
$('.loader').show();
$.ajax({
url : adminBaseUrl + "mfgSummary",
type : "POST",
crossDomain : true,
data : {
"summary_date" : todayDate
},
success : function(data) {
if (data.status == 1) {
$('.loader').hide();
var summaryColumns = [];
$.each( data.prodMfgSummary[0], function( key, value ) {
var items = {};
items.data = key;
items.title = key;
items.orderable = false;
/*items.className = "dt-body-right { text-align: center; }";*/
summaryColumns.push(items);
});
createProdSummaryTable(summaryColumns, data.prodMfgSummary);
} else {
$('.loader').hide();
$('#productionSummary').DataTable().clear().draw();
}
},
error : function(xhr, status) {
$('.loader').hide();
alert(status);
}
});
}
Table Creation Code:-
function createProdSummaryTable(columns, mfgSummaryProductData){
$('#productionSummary').dataTable({
"autoWidth" : false,
responsive : true,
"aaData" : mfgSummaryProductData,
"destroy" : true,
"aaSorting": [],
"bFilter": false,
"aoColumns" : columns,
"iDeferLoading" : 57
});
}
Help me to solve this issue.
Here is an example using columnDefs and its render and target options gor columnwise and footerCallback for rowwise
var dataSet = [{"name":"Wade Rodriguez","field1":21,"field2":22,"field3":20,"field4":21},{"name":"Maxwell Rush","field1":31,"field2":27,"field3":29,"field4":37},{"name":"Ruiz Murray","field1":40,"field2":30,"field3":27,"field4":31},{"name":"Tanner Crosby","field1":37,"field2":35,"field3":21,"field4":39},{"name":"Shelby Douglas","field1":25,"field2":25,"field3":30,"field4":30},{"name":"Haney Fulton","field1":35,"field2":26,"field3":38,"field4":27}]
$(document).ready(function() {
var my_columns = [];
$.each(dataSet[0], function(key, value) {
var my_item = {};
my_item.data = key;
my_item.title = key;
my_columns.push(my_item);
});
my_columns.push({
title: 'Total'
})
$(document).ready(function() {
$("#example").DataTable({
data: dataSet,
"columns": my_columns,
"columnDefs": [{
"render": function(data, type, row) {
return Object.values(row).reduce((a, b) => isNaN(b) ? a : a + b, 0)
},
"targets": my_columns.length - 1
}],
"footerCallback": function(row, data, start, end, display) {
$('#example tfoot').html('');
$('#example').append('<tfoot><td>Total</td></tfoot>');
var api = this.api();
var total = 0;
api.columns([1, 2, 3, 4], {
page: 'current'
}).every(function() {
var sum = this
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
total += sum;
$('#example tfoot tr').append('<td>' + sum + '</td>');
});
$('#example tfoot tr').append('<td>' + total + '</td>');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="//cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />
<script src="//cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<table id="example" class="display" cellspacing="0" width="100%">
</table>

DataTables merge jQuery/Javascript functions from two seperate tables

I am trying to make two functions work together that both work on their own.
Number 1: Is my table with a dropdown filter inside a control panel which I am trying to add a secondary checkbox filter to, everything works fine here.
http://jsfiddle.net/btofjkus/12/
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
Number 2: Is an example I found online of filtering a DataTable with a button as you can see it works on its own but I am trying to change it slightly from a button to a checkbox so the filter can be released once it is unchecked.
You will have noticed the checkbox I made for this in Number 1. #checkbox-filter.
https://jsfiddle.net/annoyingmouse/ay16vnp1/
$(function () {
var dataTable = $('#example').DataTable({
searching: true,
info: false,
lengthChange: false
});
$('#filterButton').on('click', function () {
dataTable.draw();
});
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the age column
if (target === position){
return true;
}
return false;
}
);
Now you can see the two functions I am trying to put all this together into one table (Number 1) at http://jsfiddle.net/btofjkus/12/.
What I want to do is create a checkbox filter for "Software Engineers" from the "Position" column in Number 1.
This looks complicated when I write it down with all these codeblocks but it's really just merging two functions together in the correct way.
I have tried tearing the code apart myself and gluing it together but everything I try seems to be wrong.
Example: (failure)
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
$(document).ready(function() {
if $('#checkbox-filter').is(':checked' function() {
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the age column
if (target === position){
return true;
}
return false;
}
);
});
});
As you can see above I tried mashing the code together with no luck, I have also tried some methods that seem to invoke the function but not when #checkbox-filter is checked.
The example below makes the dropdown filter only select "Software Engineers" from the "Position" column which is my criteria for this checkbox filter (but only when its checked).
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the position column
if (target === position){
return true;
}
return false;
}
);
How can I make this work only when the checkbox is selected. And release when it is deselected.
UPDATE:
This kind of works but not as it should (once checked try interacting with the dropdown filter) you will see it kind of works, but it doesn't change back when it is unchecked, it also does not filter the visible data when checked meaning I have to interact with the dropdown menu to see results. How can I fix this?
http://jsfiddle.net/btofjkus/13/
$(document).ready(function () {
$('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
console.log(select);
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
console.log()
});
//changes below
$('#checkbox-filter').change(function() {
if ($(this).is(':checked')) {
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the position column
if (target === position){
return true;
}
return false;
}
);
}
});
Here is the working solution jsfiddle
$(document).ready(function () {
var dataTable = $('#example').DataTable({
ordering: false,
bLengthChange: false,
initComplete: function () {
this.api().columns(2).every(function () {
var column = this;
var select = $('<select><option value="">Show all</option></select>')
.appendTo($("#control-panel").find("div").eq(1))
.on('change', function () {
var val = $.fn.dataTable.util.escapeRegex(
$(this).val());
column.search(val ? '^' + val + '$' : '', true, false)
.draw();
});
column.data().unique().sort().each(function (d, j) {
select.append('<option value="' + d + '">' + d + '</option>')
});
});
}
});
$('#checkbox-filter').on('change', function() {
dataTable.draw();
});
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var target = 'Software Engineer';
var position = data[1]; // use data for the age column
if($('#checkbox-filter').is(":checked")) {
if (target === position) {
return true;
}
return false;
}
return true;
}
);
});

How to allow datepicker to pick future dates in JQuery?

I need a datepicker for our project and whilst looking online.. I found one. However, it disables to allow future dates. I tried looking into the code but I cannot fully understand it. I'm kind of new to JQuery.
This is the code (it's very long, sorry):
<script>
$.datepicker._defaults.isDateSelector = false;
$.datepicker._defaults.onAfterUpdate = null;
$.datepicker._defaults.base_update = $.datepicker._updateDatepicker;
$.datepicker._defaults.base_generate = $.datepicker._generateHTML;
function DateRange(options) {
if (!options.startField) throw "Missing Required Start Field!";
if (!options.endField) throw "Missing Required End Field!";
var isDateSelector = true;
var cur = -1,prv = -1, cnt = 0;
var df = options.dateFormat ? options.dateFormat:'mm/dd/yy';
var RangeType = {ID:'rangetype',BOTH:0,START:1,END:2};
var sData = {input:$(options.startField),div:$(document.createElement("DIV"))};
var eData = {input:null,div:null};
/*
* Overloading JQuery DatePicker to add functionality - This should use WidgetFactory!
*/
$.datepicker._updateDatepicker = function (inst) {
var base = this._get(inst, 'base_update');
base.call(this, inst);
if (isDateSelector) {
var onAfterUpdate = this._get(inst, 'onAfterUpdate');
if (onAfterUpdate) onAfterUpdate.apply((inst.input ? inst.input[0] : null), [(inst.input ? inst.input.val() : ''), inst]);
}
};
$.datepicker._generateHTML = function (inst) {
var base = this._get(inst, 'base_generate');
var thishtml = base.call(this, inst);
var ds = this._get(inst, 'isDateSelector');
if (isDateSelector) {
thishtml = $('<div />').append(thishtml);
thishtml = thishtml.children();
}
return thishtml;
};
function _hideSDataCalendar() {
sData.div.hide();
}
function _hideEDataCalendar() {
eData.div.hide();
}
function _handleOnSelect(dateText, inst, type) {
var localeDateText = $.datepicker.formatDate(df, new Date(inst.selectedYear, inst.selectedMonth, inst.selectedDay));
// 0 = sData, 1 = eData
switch(cnt) {
case 0:
sData.input.val(localeDateText);
eData.input.val('');
cnt=1;
break;
case 1:
if (sData.input.val()) {
var s = $.datepicker.parseDate(df,sData.input.val()).getTime();
var e = $.datepicker.parseDate(df,localeDateText).getTime();
if (e >= s) {
eData.input.val(localeDateText);
cnt=0;
}
}
}
}
function _handleBeforeShowDay(date, type) {
// Allow future dates?
var f = (options.allowFuture || date < new Date());
switch(type)
{
case RangeType.BOTH:
return [true, ((date.getTime() >= Math.min(prv, cur) && date.getTime() <= Math.max(prv, cur)) ?
'ui-daterange-selected' : '')];
case RangeType.END:
var s2 = null;
if (sData.input && sData.input.val()) {
try{
s2 = $.datepicker.parseDate(df,sData.input.val()).getTime();
}catch(e){}
}
var e2 = null;
if (eData.input && eData.input.val()) {
try {
e2 = $.datepicker.parseDate(df,eData.input.val()).getTime();
}catch(e){}
}
var drs = 'ui-daterange-selected';
var t = date.getTime();
if (s2 && !e2) {
return [(t >= s2 || cnt === 0) && f, (t===s2) ? drs:''];
}
if (s2 && e2) {
return [f, (t >= s2 && t <= e2) ? drs:''];
}
if (e2 && !s2) {
return [t < e2 && f,(t < e2) ? drs:''];
}
return [f,''];
}
}
function _attachCloseOnClickOutsideHandlers() {
$('html').click(function(e) {
var t = $(e.target);
if (sData.div.css('display') !== 'none') {
if (sData.input.is(t) || sData.div.has(t).length || /(ui-icon|ui-corner-all)/.test(e.target.className)) {
e.stopPropagation();
}else{
_hideSDataCalendar();
}
}
if (eData && eData.div.css('display') !== 'none') {
if (eData.input.is(t) || eData.div.has(t).length || /(ui-icon|ui-corner-all)/.test(e.target.className)) {
e.stopPropagation();
}else{
_hideEDataCalendar();
}
}
});
}
function _alignContainer(data, alignment) {
var dir = {right:'left',left:'right'};
var css = {
position: 'absolute',
top: data.input.position().top + data.input.outerHeight(true)
};
css[alignment ? dir[alignment]:'right'] = '0em';
data.div.css(css);
}
function _handleChangeMonthYear(year, month, inst) {
// What do we want to do here to sync?
}
function _focusStartDate(e) {
cnt = 0;
sData.div.datepicker('refresh');
_alignContainer(sData,options.opensTo);
sData.div.show();
_hideEDataCalendar();
}
function _focusEndDate(e) {
cnt = 1;
_alignContainer(eData,options.opensTo);
eData.div.datepicker('refresh');
eData.div.show();
sData.div.datepicker('refresh');
sData.div.hide();
}
// Build the start input element
sData.input.attr(RangeType.ID, options.endField ? RangeType.START : RangeType.BOTH);
sData.div.attr('id',sData.input.attr('id')+'_cDiv');
sData.div.addClass('ui-daterange-calendar');
sData.div.hide();
var pDiv = $(document.createElement("DIV"));
pDiv.addClass('ui-daterange-container');
// Move the dom around
sData.input.before(pDiv);
pDiv.append(sData.input.detach());
pDiv.append(sData.div);
sData.input.on('focus', _focusStartDate);
sData.input.keydown(function(e){if(e.keyCode==9){return false;}});
sData.input.keyup(function(e){
_handleKeyUp(e, options.endField ? RangeType.START : RangeType.BOTH);
});
_attachCloseOnClickOutsideHandlers();
var sDataOptions = {
showButtonPanel: true,
changeMonth: true,
changeYear: true,
isDateSelector: true,
beforeShow:function(){sData.input.datepicker('refresh');},
beforeShowDay: function(date){
return _handleBeforeShowDay(date, options.endField ? RangeType.END : RangeType.BOTH);
},
onChangeMonthYear: _handleChangeMonthYear,
onSelect: function(dateText, inst) {
return _handleOnSelect(dateText,inst,options.endField ? RangeType.END : RangeType.BOTH);
},
onAfterUpdate: function(){
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#'+sData.div.attr('id') + ' .ui-datepicker-buttonpane'))
.on('click', function () {
sData.div.hide();
});
}
};
sData.div.datepicker($.extend({}, options, sDataOptions));
// Attach the end input element
if (options.endField) {
eData.input = $(options.endField);
if (eData.input.length > 1 || !eData.input.is("input")) {
throw "Illegal element provided for end range input!";
}
if (!eData.input.attr('id')) {eData.input.attr('id','dp_'+new Date().getTime());}
eData.input.attr(RangeType.ID, RangeType.END);
eData.div = $(document.createElement("DIV"));
eData.div.addClass('ui-daterange-calendar');
eData.div.attr('id',eData.input.attr('id')+'_cDiv');
eData.div.hide();
pDiv = $(document.createElement("DIV"));
pDiv.addClass('ui-daterange-container');
// Move the dom around
eData.input.before(pDiv);
pDiv.append(eData.input.detach());
pDiv.append(eData.div);
eData.input.on('focus', _focusEndDate);
// Add Keyup handler
eData.input.keyup(function(e){
_handleKeyUp(e, RangeType.END);
});
var eDataOptions = {
showButtonPanel: true,
changeMonth: true,
changeYear: true,
isDateSelector: true,
beforeShow:function(){sData.input.datepicker('refresh');},
beforeShowDay: function(date){
return _handleBeforeShowDay(date, RangeType.END);
},
onSelect: function(dateText, inst) {
return _handleOnSelect(dateText,inst,RangeType.END);
},
onAfterUpdate: function(){
$('<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" data-handler="hide" data-event="click">Done</button>')
.appendTo($('#'+eData.div.attr('id') + ' .ui-datepicker-buttonpane'))
.on('click', function () {
eData.div.hide();
});
}
};
eData.div.datepicker($.extend({}, options, eDataOptions));
}
return {
// Returns an array of dates[start,end]
getDates: function getDates() {
var dates = [];
var sDate = sData.input.val();
if (sDate) {
try {
dates.push($.datepicker.parseDate(df,sDate));
}catch(e){}
}
var eDate = (eData.input) ? eData.input.val():null;
if (eDate) {
try {
dates.push($.datepicker.parseDate(df,eDate));
}catch(e){}
}
return dates;
},
// Returns the end date as a js date
getStartDate: function getStartDate() {
try {
return $.datepicker.parseDate(df,sData.input.val());
}catch(e){}
},
// Returns the start date as a js date
getEndDate: function getEndDate() {
try {
return $.datepicker.parseDate(df,eData.input.val());
}catch(e){}
}
};
}
var cfg = {startField: '#fromDate', endField: '#toDate',opensTo: 'Left', numberOfMonths: 3, defaultDate: -50};
var dr = new DateRange(cfg);
</script>
There is a comment along the code that says, "Allow Future Dates?" That's where I tried looking but I had no luck for hours now. Please help me.
This is how the date range picker looks like in my page:
Thank you so much for your help.
UPDATE: JSFIDDLE http://jsfiddle.net/dacrazycoder/4Fppd/
In cfg, add a property with key allowFuture with the value of true
http://jsfiddle.net/4Fppd/85/

Calling ASMX webservice from JQuery Autocomplete

I'm currently trying to get the response from an asmx service and use it in an autocomplete textbox
Here the code i'm currently using:
$(function () {
$("#<%=txtParentCat.ClientID %>").autocomplete({
selectFirst: true,
source: Magelia.WebStore.Admin.Scripts.Services.AutoCompleteServices.GetCategoriesFull,
extraParams: { contains: $('#<%=txtParentCat.ClientID %>').val(), storeId: '<%=this.Page.UnitOfWorkContext.StoreId.ToString() %>' },
minLength: 0,
delay: 0,
autoFocus: true,
dataType: 'json',
parse: function (data) {
var rows = new Array();
for (var i = 0; i < data.length; i++) {
rows[i] = { data: data[i], value: data[i], result: data[i] };
}
return rows;
},
formatItem: function (row) {
return row;
},
autofill: true,
highlight: false,
multiple: true,
multipleSeparator: ";"
,
response: function (event1, ui) {
var input = $('#<%=txtParentCat.ClientID %>');
input.on('keydown', function (event) {
var key = event.keyCode || event.charCode;
if (key == 8 || key == 46)
select = false;
else
select = true;
});
if (select == true && ui.content.length > 0) {
var $userVal = this.value;
var $newVal = ui.content[0].value;
if ($userVal != "") {
var n = $newVal.toLowerCase().indexOf($userVal.toLowerCase());
if (n == 0)
n = n + $userVal.length;
if (n != -1) {
$("#<%=txtParentCat.ClientID %>").val($newVal);
setSelectionRange($("#<%=txtParentCat.ClientID %>").get(0), n, $newVal.length);
}
}
}
}
});
});
I keep getting a 500 internal error which i think must be because i'm sending the parameters needed to call the webservice the wrong way.
Here the parameters required to call the service:
Magelia.WebStore.Admin.Scripts.Services.AutoCompleteServices.GetCategoriesFull(contains,storeId,onSuccess,onFailed,userContext)
Any help is much appreciated. Thank you in advance :)

jQuery plugin activation bug

I'm having some trouble identifying a bug on the website I'm developing. To be more specific, I'm using jPages twice on the same page.
The first instance of the plugin is used as a navigation through the website as it is a one page website. A
nd the second instance is used to browse through a bunch of products rather than scrolling.
You can find the website I'm building here : .
I'll also paste all the JavaScript, because I have no idea for now where the bug is and why is behaving like that :
$(document).ready(function() {
var default_cluster_options = {
environment : "Development",
local_storage_key : "Cluster",
plugin_navigation_class : ".navigation",
plugin_wrapper_id : "content-wrapper",
headings : ['.heading-first h1', '.heading-second h1'],
input_types : ['input', 'textarea'],
info_iqns_class : ".iqn",
preview_iqn_class : ".preview",
limits : [ { min: 1224, items: 8 }, { min: 954, items: 6 }, { min: 624, items: 4 }, { min: 0, items: 2 } ],
shop_local_storage_key : "Shop",
};
var default_plugin_options = {
containerID : "",
first : false,
previous : false,
next : false,
last : false,
startPage : 1,
perPage : 1,
midRange : 6,
startRange : 1,
endRange : 1,
keyBrowse : false,
scrollBrowse: false,
pause : 0,
clickStop : true,
delay : 50,
direction : "auto",
animation : "fadeIn",
links : "title",
fallback : 1000,
minHeight : true,
callback : function(pages, items) {}
};
var Cluster = function(cluster_options, plugin_options) {
var self = this;
this.options = $.extend({}, default_cluster_options, cluster_options);
this.plugin_options = $.extend({}, default_plugin_options, plugin_options);
this.environment = this.options.environment;
this.data_key = this.options.local_storage_key;
this.shop_data_key = this.options.shop_local_storage_key;
this.plugin_navigation_class = this.options.plugin_navigation_class;
this.plugin_wrapper_id = this.options.plugin_wrapper_id;
this.headings = this.options.headings;
this.input_types = this.options.input_types;
this.viewport = $(window);
this.body = $('body');
this.viewport_width = this.viewport.width();
this.viewport_height = this.viewport.height();
this.info_iqns_class = this.body.find(this.options.info_iqns_class);
this.preview_iqn_class = this.body.find(this.options.preview_iqn_class);
this.limits = this.options.limits;
this.current_shop_page = this.options.current_shop_page;
this.total_shop_pages = this.options.total_shop_pages;
this.initiate_cluster(self.plugin_navigation_class, {
containerID : self.plugin_wrapper_id,
startPage : +(self.get_local_storage_data(self.data_key) || 1),
callback : function(pages){
self.set_local_storage_data(self.data_key, pages.current);
}
});
this.inititate_shop();
this.initiate_shop_touch_events();
};
Cluster.prototype.set_environment = function() {
if(this.environment == "Development") {
less.env = "development";
less.watch();
}
};
Cluster.prototype.set_local_storage_data = function(data_key, data_val) {
return localStorage.setItem(data_key, data_val);
};
Cluster.prototype.get_local_storage_data = function(data_key) {
return localStorage.getItem(data_key);
};
Cluster.prototype.initiate_scalable_text = function() {
for(var i in this.headings) {
$(this.headings[i]).fitText(1.6);
}
};
Cluster.prototype.initiate_placeholder_support = function() {
for(var i in this.input_types) {
$(this.input_types[i]).placeholder();
}
};
Cluster.prototype.initiate_iqn_selected_class = function() {
if(this.viewport_width < 980) {
$(this.info_iqns_class).each(function(index, element) {
var iqn = $(element).parent();
$(iqn).on('click', function() {
if($(iqn).hasClass('selected')) {
$(iqn).removeClass('selected');
} else {
$(iqn).addClass('selected');
}
});
});
}
};
Cluster.prototype.initiate_preview_action = function() {
$(this.preview_iqn_class).each(function(index, element) {
var data = $(element).attr('data-image-link');
$(element).on('click', function(ev) {
$.lightbox(data, {
'modal' : true,
'autoresize' : true
});
ev.preventDefault();
});
});
};
Cluster.prototype.initiate_plugin = function(plugin_navigation, plugin_options) {
var options = $.extend({}, this.plugin_options, plugin_options);
return $(plugin_navigation).jPages(options);
};
Cluster.prototype.initiate_shop_touch_events = function() {
var self = this;
return $("#shop-items-wrapper").hammer({prevent_default: true, drag_min_distance: Math.round(this.viewport_width * 0.1)}).bind("drag", function(ev) {
var data = JSON.parse(self.get_local_storage_data(self.shop_data_key));
if (ev.direction == "left") {
var next_page = parseInt(data.current_page + 1);
if(next_page > 0 && next_page <= data.total_pages) {
$(".shop-items-navigation").jPages(next_page);
}
}
if(ev.direction == "right") {
var prev_page = parseInt(data.current_page - 1);
if(prev_page > 0 && prev_page <= data.total_pages) {
$(".shop-items-navigation").jPages(prev_page);
}
}
});
}
Cluster.prototype.inititate_shop = function() {
var self = this;
for(var i = 0; i < this.limits.length; i++) {
if(this.viewport_width >= this.limits[i].min) {
this.initiate_plugin('.shop-items-navigation', {
containerID : "shop-items-wrapper",
perPage : self.limits[i].items,
midRange : 8,
animation : "fadeIn",
links : "blank",
keyBrowse : true,
callback : function(pages) {
var data = {
current_page : pages.current,
total_pages : pages.count
}
self.set_local_storage_data(self.shop_data_key, JSON.stringify(data));
}
});
return false;
}
}
};
Cluster.prototype.initiate_cluster = function(plugin_navigation, plugin_options) {
this.set_environment();
this.initiate_scalable_text();
this.initiate_placeholder_support();
this.initiate_iqn_selected_class();
this.initiate_preview_action();
this.initiate_plugin(plugin_navigation, plugin_options);
};
var cluster = new Cluster();
});
And the bug I was talking about, when you are on the Home page and navigate to the Shop page you will notice the the second instance of the plugin doesn't activate as the items should only be 8 ( if the width of the screen is more than 1224px ) and you should be able to browse through with the keyboard left and right arrows, but you cannot.
But if you are on the Shop page, hit refresh and the plugin will now activate after page load.
So, I would like some help with that, tracking the bug, because I'm still learning JavaScript and I'm not very experienced with it.
According to jPages source file this happens because at second plugin initialization plugin can't find :visible elements as they are hidden by first plugin initialization (line 60):
this._items = this._container.children(":visible");
To load your shop module with jPages plugin you need to initialize that plugin after shop items are shown. To do this you need to modify callback value in initiate_cluster function:
Lets say that Shop page index is 4:
Cluster.prototype.initiate_cluster = function(plugin_navigation, plugin_options) {
// ... your code
plugin_options.callback = function( pages ) {
if( pages.current == 4 ) {
this.inititate_shop();
}
};
this.initiate_plugin(plugin_navigation, plugin_options);
};
And remove this.inititate_shop(); function call from Cluster class constructor.
This should work.
Or you can try to swap plugin calls, but I'm not sure:
// first we initiate shop
this.inititate_shop();
// then main site navigation
this.initiate_cluster(self.plugin_navigation_class, {
containerID : self.plugin_wrapper_id,
startPage : +(self.get_local_storage_data(self.data_key) || 1),
callback : function(pages){
self.set_local_storage_data(self.data_key, pages.current);
}
});

Categories