Dynamic content not loading on mobile - javascript

This is the page having an issue: http://f6d.28a.myftpupload.com/blog/
All posts on this page are loaded are using a jquery.
The page is working fine on desktop, even on firefox if I test page using ctrl+shift+m for page is working properly.
But when I open this page on my iphone 5s, iOS 8.2, No posts are loading.
Code through which those post are loaded is as below:
jQuery(function($){
var $grid = $('.post-area').masonry({
itemSelector: '.post-area .box',
});
var page = 1;
var loading = true;
var $window = $(window);
var $content = $("body #main");
var load_posts = function( cat = $("input[name='cat_id']").val(), year = '', orderby = '' ){
if((cat != '' || year != '' || orderby != '') && page == 1){
$content.html('');
$content.append('<div id="temp_load" style="text-align:center">\
<img src="http://f6d.28a.myftpupload.com/wp-content/themes/bob/images/ajax-loader.png" />\
</div>');
}
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page, cat: cat, year: year, orderby: orderby},
dataType : "html",
url : "http://f6d.28a.myftpupload.com/wp-content/themes/bob/template-parts/loopHandler.php",
beforeSend : function(){
if(page != 1){
$content.append('<div id="temp_load" style="text-align:center; bottom: 0; left: 0; position: absolute; right: 0;">\
<img src="http://f6d.28a.myftpupload.com/wp-content/themes/bob/images/ajax-loader.png" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
$data.hide();
$content.append($data);
$grid.append( $data ).masonry( 'appended', $data );
$grid.masonry( 'reloadItems' );
$grid.masonry( 'layout' );
$data.fadeIn(500, function(){
$("#temp_load").remove();
loading = false;
});
} else {
$("#temp_load").remove();
}
},
error : function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
$window.scroll(function() {
var content_offset = $content.offset();
console.log(content_offset.top);
if(!loading && ($window.scrollTop() +
$window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
var cat = $('select[name="cat"]').val();
var year = $('select[name="year"]').val();
var orderby = $('select[name="orderby"]').val();
page++;
load_posts( cat, year, orderby );
}
});
$('select[name="cat"]').on('change', function() {
var cat = $(this).val();
var year = $('select[name="year"]').val();
var orderby = $('select[name="orderby"]').val();
page = 1;
load_posts(cat, year, orderby);
});
$('select[name="year"]').on('change', function() {
var year = $(this).val();
var cat = $('select[name="cat"]').val();
var orderby = $('select[name="orderby"]').val();
page = 1;
load_posts(cat, year, orderby);
});
$('select[name="orderby"]').on('change', function() {
var orderby = $(this).val();
var cat = $('select[name="cat"]').val();
var year = $('select[name="year"]').val();
page = 1;
load_posts(cat, year, orderby);
});
load_posts();
});
Can some please guide me on this....

Related

making a ajax live load

can anyone know how can I make this as an ajax live load?
unfortunately, I have limited acknowledge about javascript/jquery/ajax
simply I want to load the search result on ajax live load
This is my javascript code to load the data but it will refresh the page
I want to not refresh the page and load the data on live load
<script type="text/javascript">
function get_url() {
var urlPrefix = 'https://example.com/home/courses?'
var urlSuffix = "";
var slectedCategory = "";
var selectedLevel = "";
var selectedIelts = "";
var selectedCountry = "";
var selectedPtype = "";
var selectedDtype = "";
var selectedLanguage = "";
var selectedRating = "";
//Get selected category
$('.categories:checked').each(function() {
selectedCategory = $(this).attr('value');
});
// Get selected countries
if($("#country-search-value-unique").val() != 'all'){
selectedCountry = $("#country-search-value-unique").val();
};
if($("#ielts-search-value-unique").val() != 'all'){
selectedIelts = $("#ielts-search-value-unique").val();
};
if($("#ptype-search-value-unique").val() != 'all'){
selectedPtype = $("#ptype-search-value-unique").val();
};
if($("#dtype-search-value-unique").val() != 'all'){
selectedDtype = $("#dtype-search-value-unique").val();
};
if($("#level-search-value-unique").val() != 'all'){
selectedLevel = $("#level-search-value-unique").val();
};
if($("#price-search-value-unique").val() != 'all'){
selectedPrice = $("#price-search-value-unique").val();
};
// Get selected difficulty Level
$('.languages:checked').each(function() {
selectedLanguage = $(this).attr('value');
});
// Get selected rating
$('.ratings:checked').each(function() {
selectedRating = $(this).attr('value');
});
urlSuffix = "category="+selectedCategory+"&&level="+selectedLevel+"&&ielts="+selectedIelts+"&&country="+selectedCountry+"&&ptype="+selectedPtype+"&&dtype="+selectedDtype+"&&language="+selectedLanguage+"&&rating="+selectedRating;
var url = urlPrefix+urlSuffix;
return url;
}
function filter() {
var url = get_url();
window.location.replace(url);
//console.log(url);
}
function toggleLayout(layout) {
$.ajax({
type : 'POST',
url : 'https://example.com/home/set_layout_to_session',
data : {layout : layout},
success : function(response){
location.reload();
}
});
}
function showToggle(elem, selector) {
$('.'+selector).slideToggle(20);
if($(elem).text() === "show_more")
{
$(elem).text('show_less');
}
else
{
$(elem).text('show_more');
}
}
$(document).on('click', '.catparent-label', function(e) {
$(this).next('ul').fadeIn(); $('li.has').removeClass('is-active'); $('ul.tree').addClass('has-selection'); $('ul.tree').find("label").removeClass('is-seleted'); $(this).closest('li').addClass('is-active'); $(this).addClass('is-seleted'); $('ul.tree').find("input[type='checkbox']"); $(this).closest('li').find(".catparent"); $('.BackListDisciplines').show(); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.subcat-label', function(e) {
$('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').find("input[type='checkbox']").prop('checked', !1); $(this).addClass('is-seleted'); $(this).closest('li').find(".subcat"); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.BackListDisciplines', function(e) {
$('li.has').removeClass('is-active'); $('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').removeClass('has-selection'); $('.tree ul').hide(); $('ul.tree').find("input[type='checkbox']"); $('.BackListDisciplines').hide(); StudyFilter()
}
);
</script>

ajax send data based on checkbox value

I need to send ajax requests with checkbox values (on each click/check). I have three lists with checkboxes, each list filters the data returend from php (with mysql AND condition):
$('body').on('click', '.click, :checkbox, .pag_link', function() {
var self = this;
// radio buttons
if ($('#res_prop').is(':checked')) {
var use = $('#res_prop').val();
}
else if ($('#com_prop').is(':checked')) {
var use = $('#com_prop').val();
}
else {
$('p.error').show();
die();
}
//checkboxes from each list have the same class, is this ok?
if ($(self).is(':checkbox')) {
$(self).on('change', function() {
if ($(self).prop('class') == 'filter1' || $('.filter1').is(':checked')) {
if ($('.filter1').is(':checked'))
var type = $(self).val(); // maybe should be an array
else var type = null;
} else var type = null;
if ($(self).prop('class') == 'filter2' || $('.filter2').is(':checked')) {
if ($('.filter2').is(':checked'))
var status = $(self).val(); // maybe should be an array
else var status = null;
} else var status = null;
if ($(self).prop('class') == 'filter3' || $('.filter3').is(':checked')) {
if ($('.filter3').is(':checked'))
var bhk = $(self).val(); // maybe should be an array
else var bhk = null;
} else var bhk = null;
});
}
else {
var type = status = bhk = null;
}
if ($(self).is('.pag_link')) {
if ($(self).text() == '«')
var page = (parseInt($('.active').text()) - 1);
else if ($(self).text() == '»')
var page = (parseInt($('.active').text()) + 1);
else
var page = parseInt($(self).text());
}
else {
var page = 1;
}
$.ajax({
method: 'POST',
url: '/search',
data: {
'do': getUrlParameter('do'),
'use': use,
'type': type,
'status': status,
'bhk': bhk,
'city': $('select[name="city"]').val(),
'zone': $('select[name="zone"]').val(),
'page': page
}
}).done(function(data) {
if ($( '#search' ).is(':visible'))
$( '#search' ).hide();
if ($(self).is(':checkbox')) {
alert('should work');
var new_content = $(data).find( '#scroll-to-list' );
$( '#scroll-to-list' ).replaceWith( new_content );
}
else {
var new_content = $(data).find( '#search-filters, #scroll-to-list' );
$( '#results' ).html( new_content );
$( 'html, body' ).animate({
scrollTop: $( '#scroll-to-list' ).offset().top
}, 1000);
}
});
});
I'm looking on each click/check to do the ajax request and print the new results (relying on server is performance-wise?). If checked, the variable gets the value and is sent, if unchecked the variable gets null. The search.php script handles the mysql Select query (with ifs adding the AND conditions to the query).
I just have 1 example in the db but the checkboxes script is not working (or the mysql select query is not including the and condition, i think the problem is in the jquery, the php script is fine).
$use = isset( $_POST['use'] ) ? (int) $_POST['use'] : ''; // int AJAX
$filter_type = isset( $_POST['type'] ) ? (int) $_POST['type'] : ''; // int AJAX
$filter_status = isset( $_POST['status'] ) ? (int) $_POST['status'] : ''; // int AJAX
$filter_bhk = isset( $_POST['bhk'] ) ? (int) $_POST['bhk'] : ''; // int AJAX
$filter_city = isset( $_POST['city'] ) ? (int) $_POST['city'] : 0; // int AJAX
$filter_zone = isset( $_POST['zone'] ) ? (int) $_POST['zone'] : 0; // int AJAX
$page_number = isset( $_POST['page'] ) ? (int) $_POST['page'] : ''; // int AJAX
if ($filter_type != NULL || $filter_type != '') {
$filter_type = 'AND t2.type = ' . $filter_type;
} else $filter_type = NULL;
if ($filter_status != NULL || $filter_status != '') {
$filter_status = 'AND t2.status = ' . $filter_status;
} else $filter_status = NULL;
if ($filter_bhk != NULL || $filter_bhk != '') {
$filter_bhk = 'AND t2.bhk = ' . $filter_bhk;
} else $filter_bhk = NULL;
if ($filter_city > 0) {
$filter_city = 'AND t2.city = ' . $filter_city;
$filter_zone = NULL;
if ($filter_zone > 0) {
$filter_zone = 'AND t2.zone = ' . $filter_zone;
}
} else $filter_city = $filter_zone = NULL;
if ($stmt = $mysqli->prepare(' SELECT t1.id, t2.*
FROM ' . $table . ' t1 // not from get/post
INNER JOIN property t2 ON t2.id = t1.id
WHERE t2.use = ?
' . $filter_type
. $filter_status
. $filter_bhk
. $filter_city
. $filter_zone . '
LIMIT ?, ?')) {
$stmt->bind_param('iii', $use, $start, $limit);
$stmt->execute();
I just found this JQuery method .serialize()... and it changed my life :)
$('body').on('click', '.click, :checkbox, .pag_link', function() {
var self = this;
if (!$(':radio').is(':checked')) {
$('p.error').show();
die();
}
var data = $('input, select').serializeArray(),
mode = getUrlParameter('do'),
page = 1;
if ($(self).is('.pag_link')) {
if ($(self).text() == '«')
page = (parseInt($('.active').text()) - 1);
else if ($(self).text() == '»')
page = (parseInt($('.active').text()) + 1);
else
page = parseInt($(self).text());
}
data.push({ name : 'do', value : mode});
data.push({ name : 'page', value : page});
alert($.param(data));
$.ajax({
method: 'POST',
url: '/search',
data: $.param(data)
}).done(function (data) {
if ($( '#search' ).is(':visible'))
$( '#search' ).hide();
if ($(self).is(':checkbox')) {
var new_content = $(data).find( '#scroll-to-list' );
$( '#scroll-to-list' ).replaceWith( new_content );
}
else {
var new_content = $(data).find( '#search-filters, #scroll-to-list' );
$( '#results' ).html( new_content );
$( 'html, body' ).animate({
scrollTop: $( '#scroll-to-list' ).offset().top
}, 1000);
}
});
});
Hope it helps someone.

Pubnub getting duplicated message when changing channel

I have a problem with pubnub.
I have friends list and I need to change pubnub channel on clicking them, by switching to another friend, to chat with him.
I have global channel variable, and I am changing it on friend click. The problem is, when I switch to another friend and write a message, the message appears in panel is duplicated.
Here is the code I am using.
base = "/";
pubnub = "";
channel ="";
messageListContent = "ul.chat-messages-block";
function handleMessage(message,$index) {
if ( $index != 'me' ) {
var $index = 'left';
} else {
var $index = 'right';
}
var $imageUrl = "";
if ( message.picture != '' && message.picture != null ) {
$imageUrl = message.picture;
if ( (/^http:\/\//.test( $imageUrl ) ) ) {
$imageUrl = $imageUrl;
} else {
$imageUrl = "uploads/user/"+ $imageUrl;
}
} else {
$imageUrl = 'resources/images/user-male.png';
}
var messageEl = jQuery('<li class="'+$index+' clearfix">'+
'<div class="user-img pull-'+$index+'"> <img src="' + $imageUrl +'" alt="'+message.username+'"> </div>'+
'<div class="chat-body clearfix">'+
'<div class="">'+
'<span class="name">'+message.username+'</span><span class="name"></span><span class="badge"><i class="fa fa-clock-o"></i>'+message.chat_date+'</span></div>'+
'<p>'+ message.message + '</p>'+
' </div>'+
'</li>');
jQuery(messageListContent).append(messageEl);
};
jQuery.getJSON( "/chat/read", function( data ) {
var items = [];
if ( data != null && data != "" ){
pubnub = PUBNUB.init({
publish_key: data.publish_key,
subscribe_key: data.subscribe_key,
});
if ( data.messages.length > 0 ) {
var $my_id = data.current_user;
for( var i = 0; i < data.messages.length; i++ ) {
if ( data.messages[i].user_id == $my_id ) {
$index = "me";
} else {
var $index = "";
}
handleMessage(data.messages[i],$index);
}
}
}
});
jQuery(document).ready(function () {
jQuery('#sendMessageButton').click(function (event) {
var message = jQuery('#messageContent').val();
var friend_id = jQuery('li.activeChannel').attr('data-id');
if ( message != '' ) {
jQuery.ajax({
url: base+"chat/sendChat",
type:'POST',
data:{
friend_id: friend_id,
text:message
},
success:function(data){
var data = JSON.parse(data);
//sounds.play( 'chat' );
pubnub.publish({
channel: channel,
message: {
username: data.messages.username,
message: data.messages.message,
user_id: data.messages.friend_id,
current_user: data.messages.user_id,
picture: data.messages.picture,
type:'message',
chat_date: data.messages.chat_date
}
});
},
error: function(err){
jQuery('.errorText').fadeIn();
}
});
jQuery('#messageContent').val("");
}
});
// Also send a message when the user hits the enter button in the text area.
jQuery('#messageContent').bind('keydown', function (event) {
if((event.keyCode || event.charCode) !== 13) return true;
jQuery('#sendMessageButton').click();
return false;
});
jQuery('ul.chat-users li').click(function(){
var friend_id = jQuery(this).attr('data-id');
jQuery('ul.chat-users li').removeClass('activeChannel');
jQuery(this).addClass('activeChannel');
jQuery.ajax({
url: base+"chat/getUsersChat",
type:'POST',
data:{
friend_id: friend_id
},
success:function(data){
var data = JSON.parse(data);
jQuery('.chat-messages ul').html("");
//id = pubnub.uuid();
//channel = 'oo-chat-' + id+friend_id;
channel = 'oo-chat-' + data.channel;
if ( data.messages.length > 0 ) {
var $my_id = data.current_user;
for( var i = 0; i < data.messages.length; i++ ) {
if ( data.messages[i].user_id == $my_id ) {
$index = "me";
} else {
var $index = "";
}
//messageListContent = "ul.activeChannel"+channel;
//console.log(channel);
handleMessage(data.messages[i],$index);
}
}
pubnub.subscribe({
channel: channel,
message: function(message) {
console.log("Pubnub callback", message);
handleMessage(message,"me");
},
connect: function(message) {
console.log("Pubnub is connected", message);
},
//callback:
});
},
error: function(err){
jQuery('.errorText').fadeIn();
}
});
});
});
And here is how it is looking
Any Idea?
I had even tried to unsubscribe the previous channel on friend click, but no result.
What am I doing wrong?
I solved the problem. The problem was in pubnub.js version, it was 3.4, I switched to 3.7.1 and added the following code
jQuery('ul.chat-users li').click(function(){
var friend_id = jQuery(this).attr('data-id');
jQuery('ul.chat-users li').removeClass('activeChannel');
jQuery(this).addClass('activeChannel');
if ( channel != "" ) {
pubnub.unsubscribe({
channel : channel,
});
}

Cordova/Phonegap calendar plugin iOS create event

I'm using Cordova/Phonegap plugin found here:
https://github.com/EddyVerbruggen/Calendar-PhoneGap-Plugin
My app is an RSS feed that had different events everyday, I would like to change the javascript code so that the user is able to add to calendar and the function reads the title date at least.
In my main.js the function is:
function Calendar_Add(){
// prep some variables
var startDate = new Date("March 18, 2014 13:00:00");
var endDate = new Date("March 18, 2014 14:30:00");
var title = "Event Added!";
var location = "Home";
var notes = "Some notes about this event.";
var success = function(message) { alert("Success: " + JSON.stringify(message)); };
var error = function(message) { alert("Error: " + message); };
// create
window.plugins.calendar.createEventWithCalendar(title,location,notes,startDate,endDate,success,error);
}
This is creating an event but again I am having trouble making the variables. This is my full javascript page of what I have tried:
//jQuery get target page
function IE_navigate(index) {
Bindex = index;
$.mobile.changePage('#eventPage', 'slidefade');
$.each(data, function(i,item){
if (i == Bindex) {
//Clear if page was previously populated
//Populate page
$('#page-title').html(item.title + "<br />");
$('#page-region').html(item.Region + "<br />");
$('#page-content').html(item.fullInfo + "<br />");
/*
startDate = new Date(item.Date);
endDate = new Date(item.Date);
title = item.title;
place = item.Region;
*/
$(this).ready(function(e) {
$('#page-content').on('click','a', function(e){
e.preventDefault();
currentPage = $(this).attr('href');
window.open(currentPage, '_system', 'location=yes')
});
});
// return false;
return false
}
});
};
var Aindex = "";
var Bindex = "";
var data = [];
$(function () { Load_Content() });
function Load_Content() {
$('#feed').empty();
data = [];
$.ajax({
type: 'GET',
url:'http://www.e-grid.net/BayAreaTech/wp-rss2.php?cat=1',
dataType: 'xml',
success: function (xml) {
$('#header-title').html("e-Grid Mobile");
$(xml).find("item:lt(60)").each(function () {
var dateText = $(this).find("Date").text().toString();
var eventDate = moment(dateText,"YYYY-MM-DD");
var title = $(this).find("title").text();
var region = dateText.substr(8).toUpperCase();
if (region == "SCV") { region = "Santa Clara Valley";}
if (region == "OEB") { region = "Oakland/East Bay";}
if (region == "SF") { region = "San Francisco";}
if (region == "ALL") { region = "All regions";}
var description = $(this).find("description").text();
var infoDisplay = description.substr(0, description.indexOf(",")+120) + "..."; //Parsed DATE from description
var fullDescription = $(this).find('encoded').text();
var category = $(this).find("category").text();
var linkUrl = $(this).find("link").text();
var displayTitle = title;
var item = {title: displayTitle,
link: linkUrl,
infoDescription: infoDisplay,
Date: new Date(eventDate),
Region: region,
fullInfo: fullDescription,}
var now = moment().subtract('days', 1);
if (item.Date >= now){ data.push(item); }
});
data.sort(function (a, b) {
a = new Date(a.Date);
b = new Date(b.Date);
return a<b ? -1 : a>b ? 1 : 0;
});
if (data.length > 0) {
$.each(data, function (index, item) {
Aindex = data.indexOf(this)
var h_feedList = '<li';
h_feedList += '><a href="#" onclick="IE_navigate(' + Aindex + ')" target="_blank">';
h_feedList += '<h3>'; // Start Title Text
h_feedList += item.title; // Title Text
h_feedList += '</h3><p>'; // End the title text - start the description text
h_feedList += item.infoDescription; // Description text
h_feedList += '</p>'; // End description text
h_feedList += '</a>'; // End list link
h_feedList += '</li>'; // End List Item
$('#feed').append(h_feedList);
});
}
else
{
var message = "No upcoming events within your selection; check back soon!";
$('#feed').append('<h3>' + message + '</h3>');
}
}
});
};
function next_event() {
Bindex++;
if (Bindex > data.length){ Bindex = 0; }
$('#page-title').html(data[Bindex].title);
$('#page-region').html(data[Bindex].Region);
$('#page-content').html(data[Bindex].fullInfo);
startDate = new Date(data[Bindex].Date);
endDate = new Date(data[Bindex].Date);
title = data[Bindex].title;
place = data[Bindex].Region;
}
function previous_event() {
Bindex--;
if (Bindex <= 0){ Bindex = data.length; }
$('#page-title').html(data[Bindex].title);
$('#page-region').html(data[Bindex].Region);
$('#page-content').html(data[Bindex].fullInfo);
startDate = new Date(data[Bindex].Date);
endDate = new Date(data[Bindex].Date);
title = data[Bindex].title;
place = data[Bindex].Region;
}
$(document).ajaxStart(function() {
$.mobile.loading('show', {text: 'Loading BayArea Events...', textVisible: true, textonly: true});
});
$(document).ajaxStop(function() {
$.mobile.loading('hide');
});
$( document ).on( "pagecreate", "#home", function() {
$( document ).on( "swipeleft swiperight", "#home", function( e ) {
// We check if there is no open panel on the page because otherwise
// a swipe to close the left panel would also open the right panel (and v.v.).
// We do this by checking the data that the framework stores on the page element (panel: open).
if ( $( ".ui-page-active" ).jqmData( "panel" ) !== "open" ) {
if ( e.type === "swipeleft" ) {
$( "#settingspanel" ).panel( "open" );
} else if ( e.type === "swiperight" ) {
$( "#fieldpanel" ).panel( "open" );
}
}
});
});
$( document ).on( "pagecreate", "#eventPage", function() {
$( document ).on( "swipeleft swiperight", "#eventPage", function( e ) {
if ( e.type === "swipeleft" ) {
next_event();
} else if ( e.type === "swiperight" ) {
previous_event();
}
});
});
function Calendar_Add(){
// prep some variables
var startDate = new Date(item.Date);
var endDate = new Date(item.Date);
var title = item.title;
var location = item.region;
var notes = "";
var success = function(message) { alert("Success: " + JSON.stringify(message)); };
var error = function(message) { alert("Error: " + message); };
// create
window.plugins.calendar.createEventWithCalendar(title,location,notes,startDate,endDate,success,error);
}
The function createEventWithCalendar does not exist for the Calendar plugin. You should use createEvent with the same parameters.
You would probably have been warned by a Javascript error if you had a function like this somewhere:
window.onerror = function(a,b,c) {
alert(a);
alert(b);
alert(c);
}
Hope this helps you getting my plugin to work,
Eddy

JavaScript Module not incrementing number correctly

I have been trying to learn how to write modules in JavaScript. With this attempt I am trying to load 10 pictures from Flickr on page load, and then load 10 more pictures once the user scrolls to the bottom of the page. This is not firing consistantly and I am not sure why.
I would like to load 10 pictures at page load, and then 10 additional pictures each time the user scrolls down to the bottom of the page.
I think the issue is with the curPage property that is called using this.settings.curPage
curPage is incremented in the jaxPhotos method using this.settings.curPage++
I am not sure but I think the issue is with either the jaxPhotos method or the scrollMorePics method.
Here's a fiddle with my module:http://jsfiddle.net/R3Bt7/
Here's my HTML:
<div class="flickrContainer" data-options='{"searchQuery" : "candy", "tagQuery" : "candy", "tagMode": "all", "picsPerPage" : "10", "curPage" : 1}'>
</div>
Here's my JS:
var FlickrModule = (function ($element) {
var flickrFeed = function () {
this.$element = $element;
this.init();
};
flickrFeed.prototype.init = function () {
this.setOptions()
.jaxPhotos(this.settings.curPage)
.onScrollHandler();
};
flickrFeed.prototype.setOptions = function () {
var options = this.$element.data().options;
var defaults = {
searchQuery : '',
tagQuery : '',
tagMode : '',
picsPerPage: '1',
curPage: 1
}
this.settings = $.extend({}, defaults, options);
return this;
};
flickrFeed.prototype.jaxPhotos = function (pageNumber) {
var self = this;
// ajax call to flickr json
$.ajax({
url: '//api.flickr.com/services/rest/?method=flickr.photos.search&api_key=xxxxxxxxxxxxxxxxxxxx&tags=' + this.settings.searchQuery + '&tag_mode=' + this.settings.tagMode + '&page=' + this.settings.currPage + '&per_page=' + this.settings.picsPerPage + '&format=json&jsoncallback=?',
dataType: 'jsonp',
data: JSON,
success: function (data) {
// start assembling some dom elements to wrap around each page
var pageTxtWrap = document.createElement('div'),
pageTxt= document.createElement('p');
pageTxt.textContent = 'Page ' + pageNumber + ' - Scroll down for more pictures!';
pageTxt.innerText = 'Page ' + pageNumber + ' - Scroll down for more pictures!';
pageTxtWrap.className = 'pageTextWrap';
pageTxtWrap.appendChild(pageTxt);
// Use createDocumentFragment() as it is the fastest method of element creation
var docFragPageHdr = document.createDocumentFragment();
docFragPageHdr.appendChild(pageTxtWrap);
document.body.appendChild(docFragPageHdr);
// create variables for easier access to the JSON trees we're using
flickr = data.photos,
flickrLength = flickr.photo.length;
// run through the JSON we just got and assemble the pictures
for (var i = 0; i < flickrLength; i++) {
var farmId = flickr.photo[i].farm,
serverId = flickr.photo[i].server,
photoId = flickr.photo[i].id,
secretId = flickr.photo[i].secret,
imgTitle = flickr.photo[i].title;
var flickImg = document.createElement('img');
flickImg.className = 'flickerImg';
flickImg.id = 'flickImg'+i;
flickImg.title = imgTitle;
flickImg.src = 'http://farm' + farmId + '.staticflickr.com/' + serverId + '/' + photoId + '_' + secretId + '_m.jpg';
var docFragFlickImg = document.createDocumentFragment();
docFragFlickImg.appendChild(flickImg);
document.body.appendChild(docFragFlickImg);
}
}
});
// increase currPage so we can go to the next page of pictures
this.settings.curPage++;
return this;
};
flickrFeed.prototype.onScrollHandler = function () {
$(document).on('scroll', this.scrollMorePics.bind(this));
return this;
};
flickrFeed.prototype.scrollMorePics = function(){
if ( $(window).scrollTop() + $(window).height() > $(document).height() - 50 ) {
console.log('Before ajax curPage = ', this.settings.curPage);
this.jaxPhotos(this.settings.curPage);
console.log('After ajax curPage = ', this.settings.curPage);
};
return this;
};
return flickrFeed;
}( $('.flickrContainer') ));
(function () {
var myModule = new FlickrModule();
})();
A small example on how you can access instance variables and methods based on your code:
var FlickrModule = (function ($) {
var flickrFeed = function ($element) {
this.$element = $element;
this.init();
};
flickrFeed.prototype.init = function(){
console.log('init', this.$element);
};
return flickrFeed;
})(jQuery);
$(function(){
var $container = $('.flickrContainer'),
fm = new FlickrModule($container);
});
http://jsfiddle.net/5nJqM/

Categories

Resources