Ugent !!! Abort all file uploads in Blueimp jquery file upload - javascript

I am trying to upload form using BLueimp File Upload Jquery but i cannot abort all the file uploads. My configration is :
url: form.attr('action'),
type: 'POST',
datatype: 'json',
dropZone: $(document),
pasteZone: $(document),
singleFileUploads: true,
limitConcurrentUploads: 1,
And i cannot change any configration . I mean singleFileUploads : true is must.
I have also tried
xqXHr = data.submit();
But aborting it only aborts 1 file instead of all. I have been searching for 5 hourse and cannot find answer :( .
Full js code
$(document).on('click','.redbut',function(){
jqXHR.abort();
jqXHR = null;
});
$(document).bind('drop dragover', function (e) {
e.preventDefault();
});
setInterval(function(){
q=0;
$('.upf_percent').each( function(index){
q=71*index;
$(this).css('top', q + "px");
}) ;
}, 100);
$(document).ready( function() {
check_nf();
$('.direct-upload').each( function(n) {
var form = $(this);
'use strict';
form.fileupload({
url: form.attr('action'),
type: 'POST',
datatype: 'json',
dropZone: $(document),
pasteZone: $(document),
singleFileUploads: true,
limitConcurrentUploads: 1,
add: function (event, data) {
window.onbeforeunload = function() {
return 'Are you sure you want to cancel file uploads.';
};
show_ub();
$.each(data.files, function (index, file) {
var size = formatFileSize(file.size);
var filename = file.name;
var r_s = makeid(5);
file.uploadID = r_s;
$('.direct-upload').append('<div class="u_daba '+r_s+'"><div class="file_data"></div><div class="upf_percent"><div class="arrowdown">0%</div> </div><div class="progress"><div class="bar"></div></div></div>');
check_nf();
$('.'+r_s+' .file_data').html(filename+' <span class="marginL15">( '+size+' )</span><span class="floatRight marginR30 blue"><i>Pending</i></span>');
n++;
});
jqXHR = data.submit();
},
progress: function(e, data){
$.each(data.files, function (index, file ) {
var p = Math.round((data.loaded / data.total) * 100);
var r_s = file.uploadID;
$('.'+r_s+' .progress .bar').css('width', p + '%');
$('.'+r_s+' .upf_percent').html('<div class="arrowdown"></div>'+p + '%');
if(p>0){
$('.'+r_s+' .upf_percent').css('display', "block");
$('.'+r_s+' .file_data span:nth-of-type(2)').text('Uploading');
$('.'+r_s+' .file_data span:nth-of-type(2)').addClass('green');
$('.'+r_s+' .file_data span:nth-of-type(2)').removeClass('blue');
}
t = 0.9537*p + 1.13;
$('.'+r_s+' .upf_percent').css('left', t + "%");
});
},
fail: function(e, data) {
// Remove 'unsaved changes' message.
window.onbeforeunload = null;
$.each(data.files, function (index, file ) {
var r_s = file.uploadID;
$('.'+r_s+' .progress .bar').css('width', '100%').addClass('red');
$('.'+r_s+' .upf_percent').css('display', "none");
$('.'+r_s+' .file_data span:nth-of-type(2)').text('Error: '+data.errorThrown);
$('.'+r_s+' .file_data span:nth-of-type(2)').addClass('red');
$('.'+r_s+' .file_data span:nth-of-type(2)').removeClass('green');
});
},
done: function (event,data){
$.each(data.files, function (index, file ) {
var r_s = file.uploadID;
$('.'+r_s+' .file_data span:nth-of-type(2)').text('Uploaded Successfully !!');
$('.'+r_s+' .upf_percent').css('display', "none");
});
},
stop: function (event, data) {
window.onbeforeunload = null;
hide_ub();
get_fffi();
}
});
});
});
$(document).on('click','.uploadbut',function(){
$('.direct-upload #file').click();
});

Related

Javascript module parttern ajax

I am learning javascript design patterns. So am converting my rough jquery code into cleaner module pattern. The question is, how will i call a click event after ajax has loaded in module pattern (Object literal). I used to solve it using $(document).ajaxcomplete(callback).
here is the working supergetti code
$('.meidaBtn, #media_load_btn').on('click', function(event) {
event.preventDefault();
$('.media').show(500);
$('#mediaBox').html('Loading...');
var link = location.origin + '/dashboard/media';
$.ajax({
url: link
}).done(function(data) { // data what is sent back by the php page
$('#mediaBox').html(data); // display data
// Click through
$('.imageBox img').bind('click', function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
$('.media').hide();
});
});
});
Here is the javascript module pattern / object literal
var mediaPlugin = {
init: function() {
this.cacheDom();
this.bindEvents();
},
// Cache Dom
cacheDom: function() {
this.baseUrl = location.origin + '/dashboard/media';
this.$button = $('.meidaBtn, #media_load_btn');
this.$media = $('.media');
this.$mediaBox = $('#mediaBox');
this.$imageBox = $('.imageBox img');
},
// Bind Events
bindEvents: function() {
this.$button.on('click', this.render.bind(this));
this.$imageBox.on('click', this.addImage.bind(this));
},
// Show Data
render: function(e) {
e.preventDefault();
this.$media.show(500);
this.loadData();
},
// Load the data
loadData: function() {
var that = this;
$.ajax({
url: this.baseUrl,
type: 'GET',
success: function(data) {
// console.log(that.$mediaBox);
that.$mediaBox.html(data);
},
error: function() {
console.log("An error occored!");
},
complete: function() {
// console.log("I am now complete");
// that.loadMore();
}
});
},
// Add Image
addImage: function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
this.$media.hide();
}
};
mediaPlugin.init();
The method provided below adds a simple property to the object which is used as a delegate/callback. You simply point your function to it and then it is called automatically since it is called in the complete event.
var mediaPlugin = {
init: function() {
this.cacheDom();
this.bindEvents();
},
// Cache Dom
cacheDom: function() {
this.baseUrl = location.origin + '/dashboard/media';
this.$button = $('.meidaBtn, #media_load_btn');
this.$media = $('.media');
this.$mediaBox = $('#mediaBox');
this.$imageBox = $('.imageBox img');
},
// Bind Events
bindEvents: function() {
this.$button.on('click', this.render.bind(this));
this.$imageBox.on('click', this.addImage.bind(this));
},
// Show Data
render: function(e) {
e.preventDefault();
this.$media.show(500);
this.loadData();
},
loadDataComplete: function() {},
// Load the data
loadData: function() {
var that = this;
$.ajax({
url: this.baseUrl,
type: 'GET',
success: function(data) {
// console.log(that.$mediaBox);
that.$mediaBox.html(data);
},
error: function() {
console.log("An error occored!");
},
complete: function() {
// console.log("I am now complete");
// that.loadMore();
that.loadDataComplete();
}
});
},
// Add Image
addImage: function() {
var src = $(this).attr('src');
var alt = $(this).attr('alt');
src = src.replace('tumbnail_', '');
tinyMCE.execCommand('mceInsertContent', false, '<img src="' + src + '" alt="' + alt + '">');
this.$media.hide();
}
};
var myCompleteFunction = function myCompleteFunction() {}
mediaPlugin.init();
mediaPlugin.loadDataComplete = myCompleteFunction;
mediaPlugin.loadData();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I finally figured how to get this code working. I used jquery .delegate() and i now work like magic. Below is the working code. thanks #abc123 for stoping by.
var media = (function(){
// Cache dom
var baseUrl = location.origin+'/dashboard/media';
var $button = $('.meidaBtn, #media_load_btn');
var $media = $('.media');
var $mediaBox = $('#mediaBox');
var $imageBox = $mediaBox.find('img');
var options = {
url: baseUrl,
type: 'GET',
success: function(data){
$mediaBox.html(data);
},
error: function(){
console.log("An error occored!");
},
complete: function(){
// console.log("I am now complete");
// that.loadMore();
}
};
// Bind Events
$button.on('click', _render);
$mediaBox.delegate('.imageBox', 'click', _addImage);
function _render(e){
e.preventDefault();
$media.show(500);
_loadData();
}
// Load images
function _loadData(){
$.ajax(options);
}
// Add Images
function _addImage(){
img = $(this).find('img');
console.log(img.attr('src')); // This should display the image url
}
})();

Upload multiple image using AJAX, PHP and jQuery

I have a lot of problem to upload multiple images using AJAX. I write this code:
HTML
<form id="upload" method="post" enctype="multipart/form-data">
<div id="drop" class="drop-area">
<div class="drop-area-label">
Drop image here
</div>
<input type="file" name="file" id="file" multiple/>
</div>
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
jQuery/AJAX
$(document).on("change", "input[name^='file']", function(e){
e.preventDefault();
var This = this,
display = $("#uploads");
// list all file data
$.each(This.files, function(i, obj){
// for each image run script asynchronous
(function(i) {
// get data from input file
var file = This.files[i],
name = file.name,
size = file.size,
type = file.type,
lastModified = file.lastModified,
lastModifiedDate = file.lastModifiedDate,
webkitRelativePath = file.webkitRelativePath,
slice = file.slice,
i = i;
// DEBUG
/*
var acc = []
$.each(file, function(index, value) {
acc.push(index + ": " + value);
});
alert(JSON.stringify(acc));
*/
$.ajax({
url:'/ajax/upload.php',
contentType: "multipart/form-data",
data:{
"image":
{
"name":name,
"size":size,
"type":type,
"lastModified":lastModified,
"lastModifiedDate":lastModifiedDate,
"webkitRelativePath":webkitRelativePath,
//"slice":slice,
}
},
type: "POST",
// Custom XMLHttpRequest
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
// Check if upload property exists
if(myXhr.upload)
{
// For handling the progress of the upload
myXhr.upload.addEventListener("progress",progressHandlingFunction, false);
}
return myXhr;
},
cache: false,
success : function(data){
// load ajax data
$("#listTable").append(data);
}
});
// display progress
function progressHandlingFunction(e){
if(e.lengthComputable){
var perc = Math.round((e.loaded / e.total)*100);
perc = ( (perc >= 100) ? 100 : ( (perc <= 0) ? 0 : 0 ) );
$("#progress"+i+" > div")
.attr({"aria-valuenow":perc})
.css("width", perc+"%");
}
}
// display list of files
display.append('<li>'+name+'</li><div class="progress" id="progress'+i+'">'
+'<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%;">'
+'</div></div>');
})(i);
});
});
I've tried a various versions and I never succeed to send multiple data through ajax. I have tried in this way what you see above, and now I get only POST informations. I understand why i get POST but I need to send FILES information and I do not know where I'm wrong.
I not work the first time with ajax and often use it for most projects but I have never used to send multiple files and that bothering me now.
Thanks!
Try utilizing json to upload , process file object
html
<div id="drop" class="drop-area ui-widget-header">
<div class="drop-area-label">Drop image here</div>
</div>
<br />
<form id="upload">
<input type="file" name="file" id="file" multiple="true" accepts="image/*" />
<ul class="gallery-image-list" id="uploads">
<!-- The file uploads will be shown here -->
</ul>
</form>
<div id="listTable"></div>
css
#uploads {
display:block;
position:relative;
}
#uploads li {
list-style:none;
}
#drop {
width: 90%;
height: 100px;
padding: 0.5em;
float: left;
margin: 10px;
border: 8px dotted grey;
}
#drop.hover {
border: 8px dotted green;
}
#drop.err {
border: 8px dotted orangered;
}
js
var display = $("#uploads"); // cache `#uploads`, `this` at `$.ajax()`
var droppable = $("#drop")[0]; // cache `#drop` selector
$.ajaxSetup({
context: display,
contentType: "application/json",
dataType: "json",
beforeSend: function (jqxhr, settings) {
// pre-process `file`
var file = JSON.parse(
decodeURIComponent(settings.data.split(/=/)[1])
);
// add `progress` element for each `file`
var progress = $("<progress />", {
"class": "file-" + (!!$("progress").length
? $("progress").length
: "0"),
"min": 0,
"max": 0,
"value": 0,
"data-name": file.name
});
this.append(progress, file.name + "<br />");
jqxhr.name = progress.attr("class");
}
});
var processFiles = function processFiles(event) {
event.preventDefault();
// process `input[type=file]`, `droppable` `file`
var files = event.target.files || event.dataTransfer.files;
var images = $.map(files, function (file, i) {
var reader = new FileReader();
var dfd = new $.Deferred();
reader.onload = function (e) {
dfd.resolveWith(file, [e.target.result])
};
reader.readAsDataURL(new Blob([file], {
"type": file.type
}));
return dfd.then(function (data) {
return $.ajax({
type: "POST",
url: "/echo/json/",
data: {
"file": JSON.stringify({
"file": data,
"name": this.name,
"size": this.size,
"type": this.type
})
},
xhr: function () {
// do `progress` event stuff
var uploads = this.context;
var progress = this.context.find("progress:last");
var xhrUpload = $.ajaxSettings.xhr();
if (xhrUpload.upload) {
xhrUpload.upload.onprogress = function (evt) {
progress.attr({
"max": evt.total,
"value": evt.loaded
})
};
xhrUpload.upload.onloadend = function (evt) {
var progressData = progress.eq(-1);
console.log(progressData.data("name")
+ " upload complete...");
var img = new Image;
$(img).addClass(progressData.eq(-1)
.attr("class"));
img.onload = function () {
if (this.complete) {
console.log(
progressData.data("name")
+ " preview loading..."
);
};
};
uploads.append("<br /><li>", img, "</li><br />");
};
}
return xhrUpload;
}
})
.then(function (data, textStatus, jqxhr) {
console.log(data)
this.find("img[class=" + jqxhr.name + "]")
.attr("src", data.file)
.before("<span>" + data.name + "</span><br />");
return data
}, function (jqxhr, textStatus, errorThrown) {
console.log(errorThrown);
return errorThrown
});
})
});
$.when.apply(display, images).then(function () {
var result = $.makeArray(arguments);
console.log(result.length, "uploads complete");
}, function err(jqxhr, textStatus, errorThrown) {
console.log(jqxhr, textStatus, errorThrown)
})
};
$(document)
.on("change", "input[name^=file]", processFiles);
// process `droppable` events
droppable.ondragover = function () {
$(this).addClass("hover");
return false;
};
droppable.ondragend = function () {
$(this).removeClass("hover")
return false;
};
droppable.ondrop = function (e) {
$(this).removeClass("hover");
var image = Array.prototype.slice.call(e.dataTransfer.files)
.every(function (img, i) {
return /^image/.test(img.type)
});
e.preventDefault();
// if `file`, file type `image` , process `file`
if (!!e.dataTransfer.files.length && image) {
$(this).find(".drop-area-label")
.css("color", "blue")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
}).dequeue("msg");
return "File dropped, processing file upload...";
});
processFiles(e);
} else {
// if dropped `file` _not_ `image`
$(this)
.removeClass("hover")
.addClass("err")
.find(".drop-area-label")
.css("color", "darkred")
.html(function (i, html) {
$(this).delay(3000, "msg").queue("msg", function () {
$(this).css("color", "initial").html(html)
.parent("#drop").removeClass("err")
}).dequeue("msg");
return "Please drop image file...";
});
};
};
php
<?php
if (isset($_POST["file"])) {
// do php stuff
// call `json_encode` on `file` object
$file = json_encode($_POST["file"]);
// return `file` as `json` string
echo $file;
};
jsfiddle http://jsfiddle.net/guest271314/0hm09yqo/

How can change action in Function of Ajax?

I want change action in function AjaxUpload.
this code value of setnamefile in action not change, because page not reload.
and I think if change action when of submit, but I cannot done.
How can change action in Function of Ajax ?
html
<input id="namefileupload" value="<?php echo date("d-m-Y").'-'.rand(0,9999); ?>" >
javascript
var setnamefile = $('#namefileupload').val();
new AjaxUpload(btnUpload, {
action: 'upload-file.php?savename=' + setnamefile,
name: 'uploadfile',
onSubmit: function(file, ext){
if (! (ext && /^(jpg|png|jpeg|gif|doc|docx|pdf|xls|xlsx|pptx|ppt)$/.test(ext))){
status.text('file it not support');
return false;
}
status.text('Uploading...');
},
onComplete: function(file, response){
status.text('');
if(response==="success"){
var mydate=new Date();
var today = mydate.getDate()+ mydate.getFullYear();
var numrand = Math.floor(Math.random() * 9999) + 1;
var restype = file.substring(file.lastIndexOf('.') + 1).toLowerCase();
$('<li></li>').appendTo('#files').html(''+file+'').addClass('success');
$('#namefileupload').val(today+'-'+numrand);
setnamefile = today+'-'+numrand;
} else{
$('<li></li>').appendTo('#files').text(file).addClass('error');
}
}
});
if you are having some form or related id then you can do this:
$("#formId").attr("action", your url);
use like this:
<button id="addImage">test</button>
new AjaxUpload($('#addImage'), {
action: 'url,
name: 'uploadimage',
dataType: 'json',
onSubmit: function (file, ext) {
},
onComplete: function (file, response) {
}
});
$('input[type="file"]').on('click', function(e){
alert('hi!');
});

Bypass Input FIle; Uploading Image directly using javascript

I'd like to automate the uploading of images to a website. The problem is I'm stuck at the input file type. The site seems to use a JQuery uploading method. I'd like to feed the script the image data directly satisfying validation.
Here's the HTML of the input file type used to upload images along with it's structure.
<div id="item_img_msg1" abp="568"></div>
<div class="mg_b5 mg_l10" id="item_img_empty1" abp="569">
<input name="updfile1" class=" " id="item_img_file1" type="file" abp="570">
</div>
<div class="mg_b5 mg_l10" id="item_img_selected1" style="display: none;" abp="571">
<img id="item_img1" src="/common/images/noimage.gif" abp="572">
<input id="item_img_del1" style="vertical-align: bottom;" type="button" value="Delete" abp="573">
</div>
<input name="hdnImgDelFlg1" id="imgdelflg1" type="hidden" value="" abp="574">
<span class="font_85 pg_l10" abp="575">(Sizeļ¼šUnder 1MB;Format:JPEG,GIF,PNG</span>
<br abp="576">
<span class="pg_l10" abp="577">Wide or Tall images will be chopped</span>
<div class="HelpTxt mg_t5" abp="578">
Guide:Image Upload Guide
</div>
And here's the related javascript.
var ImageUploader = function (idx) {
var postData = {
name: "updfile",
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var deleteData = {
index: idx,
imgApiType: $("#img_api_type").val(),
unq: $("#unique_id").val(),
postCnt: 0
};
var onIamgeUploaded = function (response) {
var status = $(response).find("otoma_status").text();
if (status != "0") {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed</div>");
return;
}
var url = $(response).find("img_url").text();
$("#item_img" + idx).attr("src", url + "?" + new Date().getTime());
$("#item_img_empty" + idx).hide();
$("#item_img_selected" + idx).show();
$("[name='hdnImgDelFlg" + idx + "']").val("0");
postData.postCnt++;
};
this.manualUpload = function (data) {
var postDataForManual = $.extend({}, postData, data);
jQuery.ajax({
data: postDataForManual,
url: "/api/itemimage/upload",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
var loading_image_tag = $("<img>").attr({
"class": "js-loading_image" + idx,
src: Module.imgpath + "/lib/fileuploader/loading.gif"
});
$("#item_img_empty" + idx).after(loading_image_tag);
$("#item_img_empty" + idx).hide();
},
success: function (response) {
onIamgeUploaded(response);
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
$("#item_img_empty" + idx).show();
},
complete: function () {
$("img.js-loading_image" + idx).remove();
}
});
};
var init = function (idx) {
postData.index = idx;
try {
new AjaxUpload("#item_img_file" + idx, {
action: "/api/itemimage/upload",
name: "updfile",
data: postData,
onSubmit: function (file, extension) {
AjaxUtils.loading(true);
$("#item_img_msg" + idx).html("");
},
onComplete: function (file, response) {
AjaxUtils.loading(false);
onIamgeUploaded(response);
}
});
} catch (e) {}
$("#item_img_del" + idx).click(function () {
jQuery.ajax({
dateType: "xml",
data: deleteData,
url: "/api/itemimage/delete",
cache: false,
type: "post",
beforeSend: function (XMLHttpRequest) {
deleteData.postCnt = postData.postCnt;
$("#item_img_msg" + idx).html("");
$("#item_img_empty" + idx).show();
$("#item_img_selected" + idx).hide();
$("[name='hdnImgDelFlg" + idx + "']").val("1");
},
error: function () {
$("#item_img_msg" + idx).html("<div class='error_with_icon'>Upload Failed!</div>");
}
});
});
};
init(idx);
};
var ImageUploaders = [];
var maxImageNumber = $("#max_image_number").val();
for (var i = 1; i <= maxImageNumber; i++) {
ImageUploaders.push(new ImageUploader(i));
}
var params = Module.Utility.getParameters();
var buying_support_item_id = params.buying_support_item_id;
if (buying_support_item_id) {
ImageUploaders[0].manualUpload({
buying_support_item_id: buying_support_item_id
});
}
I can make javascript script calls to the webpage. I just basically need to know which calls to make. Does anyone know how to do this? If so, could you provide sample code.
Thanks!

jQuery add/removeClass & AJAX not working

I'm using Isotope with AJAX to pull in some posts in WordPress, pretty much everything is there, except for the default Isotope animation runs when I AJAX in content, which looks a bit weird. I still wanted it to animate when filtered though.
So I thought I could just use add/removeClass within my AJAX function to turn it off/on when needed, but if I do the animation never runs.
Any ideas where I'm going wrong here?
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
if( $('body').hasClass('home') ) {
var loopHandler = '/inc/loop-handler.php';
} else {
var loopHandler = '/inc/loop-handler-archive.php';
}
var load_posts = function(){
$.ajax({
type : "GET",
data : {numPosts : 1, pageNumber: page},
dataType : "html",
url : templateDir+loopHandler,
beforeSend : function(){
if(page != 1){
$('.loader').append('<div id="temp_load" style="text-align:center; z-index:9999;">\
<img src="'+templateDir+'/img/ajax-loader.gif" />\
</div>');
}
},
success : function(data){
$data = $(data);
if($data.length){
var itemHeight = $('.item').height();
var height = $content.height()+itemHeight*2;
$content.append($data);
$content.css('min-height', height);
$data.hide();
// should stop the animation
$('.isotope').addClass('no-transition');
$content.isotope('destroy');
$content.imagesLoaded( function(){
$content.isotope({
// options
layoutMode: 'fitRows',
itemSelector : '.item'
});
});
$data.fadeIn(700, function(){
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// should start up the animation again
$('.isotope').removeClass('no-transition');
$content.css('min-height', '0');
} 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;
page++;
load_posts();
}
});
load_posts();
If you need any of the HTML/PHP I'm happy to post it up. Also, here's the dev site if you want to check it out.
I don't know Isotope and I have not tested if it works. But I have refactor your code with annotations to help you better understand the problem.
I think it comes from how you call removeClass and addClass successively, the two instantly cancel.
var page = 1;
var loading = true;
var $window = $(window);
var $content = $('.isotope');
var loopHandler = '/inc/loop-handler.php';
var isotopeController = {
append: function($data) {
// Add AJAX data
var itemHeight = $('.item').height();
var height = $content.height() + itemHeight * 2;
$content.append($data);
$content.css('min-height', height);
// Stop
isotopeController.stop($data);
// Restart
$content.imagesLoaded(function() {
// When images loaded !
isotopeController.start($data);
});
},
start: function($data) {
// Start isotope
$content.isotope({
layoutMode: 'fitRows',
itemSelector: '.item'
});
// Show data
$data.fadeIn(700, function() {
$("#temp_load").fadeOut(700).remove();
loading = false;
});
// Start the animation
$content.removeClass('no-transition');
$content.css('min-height', '0');
},
stop: function($data) {
// Hide data
$data.hide();
// Stop the animation
$content.addClass('no-transition');
// Stop isotope
$content.isotope('destroy');
},
loadPosts: function() {
$.ajax({
type: "GET",
data: {
numPosts: 1,
pageNumber: page
},
dataType: "html",
url: templateDir + loopHandler,
beforeSend: function() {
if (page != 1) {
$('.loader').append('' +
'<div id="temp_load" style="text-align:center; z-index:9999;">' +
'<img src="' + templateDir + '/img/ajax-loader.gif" />' +
'</div>'
);
}
},
success: function(data) {
var $data = $(data);
if ($data.length) {
isotopeController.append($data);
} else {
$("#temp_load").remove();
}
},
error: function(jqXHR, textStatus, errorThrown) {
$("#temp_load").remove();
alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
}
};
$window.scroll(function() {
var content_offset = $content.offset();
if (!loading && ($window.scrollTop() + $window.height()) > ($content.scrollTop() + $content.height() + content_offset.top)) {
loading = true;
page++;
isotopeController.loadPosts();
}
});
// On load
$(function() {
if (!$('body').hasClass('home')) {
loopHandler = '/inc/loop-handler-archive.php';
}
isotopeController.loadPosts();
});

Categories