I'm appending isotope items via Ajax in Wordpress:
My JS Code:
var $news_container = $('#news'); //The ID for the list with all the blog posts
$news_container.isotope({ //Isotope options, 'item' matches the class in the PHP
itemSelector: '.newsItem',
masonry: {
columnWidth: '.news-item-sizer',
gutter: '.gutter-sizer'
}
});
var has_run = false;
var init_offset = 0;
$('button.showall').click(function(e) {
e.preventDefault();
var button = $(this);
// Disable button
$(button).removeClass('showall');
$(button).addClass('showless');
// Record Nonce
var nonce = $(this).data("nonce");
if(has_run == false) {
button.data('offset', $(this).data("offset"));
init_offset = $(this).data("offset");
}
// Set AJAX parameters
data = {
action: 'mft_load_more_ajax',
init_offset: init_offset,
offset: button.data('offset'),
nonce: nonce
};
$.post(mft_load_more_ajax.ajaxurl, data, function(response) {
// Set Container Name
var response = JSON.parse(response);
console.log(response);
// Run through JSON
$.each( response, function( key, value ) {
// Set Value
var val = $(value);
// Set Container
var $container = $('#news').isotope();
// Append Val
$container.append(val).isotope( 'appended', val );
$(button).html('show less');
});
// Set Offset
var offset = button.data("offset");
button.data("offset", offset + 11 );
// If Has Run
has_run = true;
return false;
}
Until now, this works quite fine. Now I would like to switch the buttontext and it's class to .showless and on the next click all previously appended items should be removed. They all have the class .newsItem.appendedItem.
I tried this method:
$('button.showless').click(function(e) {
var button = $(this);
console.log('showless');
$out = $('.newsItem.appendedItem');
var isotopeInstance = $('#news').data('isotope');
isotopeInstance.$allAtoms = isotopeInstance.$allAtoms.not($out);
$out.remove();
// Disable button
$(button).removeClass('showless');
$(button).addClass('showall');
has_run = false;
return false;
});
Unfortunately this doesn't work, because the showless function is not even being entered, as I don't get a log in the console. What am I overlooking?
Thanks for your help!
Cara
Update 1:
I'm getting this error in Google Console.
Not sure, what was the problem now. But I cleaned the code a little bit with using an if statement, to check if the elements already got appended.
So my final code now looks like this:
var $news_container = $('#news'); //The ID for the list with all the blog posts
$news_container.isotope({ //Isotope options, 'item' matches the class in the PHP
itemSelector: '.newsItem',
masonry: {
columnWidth: '.news-item-sizer',
gutter: '.gutter-sizer'
}
});
var is_appended = false;
$('button.showall').click(function(e) {
e.preventDefault();
var button = $(this);
// Record Nonce
var nonce = $(this).data("nonce");
if(is_appended == false) {
button.data('offset', $(this).data("offset"));
// Disable button
button.prop( "disabled" , true );
// Set AJAX parameters
data = {
action: 'mft_load_more_ajax',
offset: button.data('offset'),
nonce: nonce
};
$.post(mft_load_more_ajax.ajaxurl, data, function(response) {
// Set Container Name
var response = JSON.parse(response);
console.log(response);
// Run through JSON
$.each( response, function( key, value ) {
// Set Value
var val = $(value);
// Set Container
var $container = $('#news').isotope();
// Append Val
$container.append(val).isotope( 'appended', val );
});
// Undo Button Disable
button.prop( "disabled" , false );
button.html('Weniger News anzeigen');
// Set Offset
// var offset = button.data("offset");
// button.data("offset", offset + 11 );
// If Was appended
is_appended = true;
return false;
});
} else if(is_appended == true) {
$out = $('.newsItem.appendedItem');
$news_container.isotope( 'remove', $out )
// layout remaining item elements
.isotope('layout');
button.html('Alle News anzeigen');
is_appended = false;
return false;
}
});
In Chrome everything works perfectly. But just figured out, that in Firefox my Ajax array is completely empty and I'm not able to fetch any data. Probably another problem, I'm going to post separately.
In my application i have to show the path covered by an user in particulat date working fine for first response,from second response from ajax i am getting data which is diffrent from first one but still map showing 1st response result
I included google map javascript api like below in header section of html
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
I am using following code in my jsp file
<script>
$(document).ready(function(){
window.setInterval(positionCheck, 20000);
});
</script>
<script>
$(document).ready(function(){
document.getElementById("directions_panel").innerHTML = "";
document.getElementById("map").innerHTML = "";
$("#searchSubmit").onclick(){
positionCheck();
}
});
</script>
<script type="text/javascript">
function positionCheck(){
var username=$("#xmlLabel").val();
var searchDate=$("#searchDate").val();
if(username!=""&& searchDate!=''){
This part where i used ajax call working fine for first response
from second response onwards problem arises it is showing content of first response from server
$.ajax({
type : "POST",
url : "searchLocation.mnt",
data :"xmlLabel="+username+"&searchDate="+searchDate,
dataType : "json",
mimeType : 'application/json',
success : function(data) {
if(data!=""){
mapLoaded(data);
function mapLoaded(data){
var size=0;
var counts=0;
var stops = data;
alert(stops);
size =stops.length;
if(stops.length>0){
var mapid=document.getElementById("map");
var map = new window.google.maps.Map(mapid);
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer({suppressMarkers: true,polylineOptions: {
strokeColor: "black"
}});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
window.tour.fitBounds(map);
alert(stops.length);
if (stops.length > 1)
window.tour.calcRoute(directionsService, directionsDisplay);
}
alert(stops.length);
function Tour_startUp(stops) {
if (!window.tour) window.tour = {
updateStops: function (newStops) {
stops = newStops;
},
// map: google map object
// directionsDisplay: google directionsDisplay object (comes in empty)
loadMap: function (map, directionsDisplay) {
var myOptions = {
zoom:4,
center: new window.google.maps.LatLng(17.379818, 78.478542), // default to Hyderabad
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
map.setOptions(myOptions);
directionsDisplay.setMap(map);
},
fitBounds: function (map) {
var bounds = new window.google.maps.LatLngBounds();
// extend bounds for each record
jQuery.each(stops, function (key, val) {
var myLatlng = new window.google.maps.LatLng(val.latitude, val.longitude);
bounds.extend(myLatlng);
});
map.fitBounds(bounds);
},
calcRoute: function (directionsService, directionsDisplay) {
var batches = [];
var itemsPerBatch = 10; // google API max = 10 - 1 start, 1 stop, and 8 waypoints
var itemsCounter = 0;
var wayptsExist = stops.length > 0;
while (wayptsExist) {
var subBatch = [];
var subitemsCounter = 0;
for (var j = itemsCounter; j < stops.length; j++) {
subitemsCounter++;
subBatch.push({
location: new window.google.maps.LatLng(stops[j].latitude, stops[j].longitude),
stopover: true
});
if (subitemsCounter == itemsPerBatch)
break;
}
itemsCounter += subitemsCounter;
batches.push(subBatch);
wayptsExist = itemsCounter < stops.length;
// If it runs again there are still points. Minus 1 before continuing to
// start up with end of previous tour leg
itemsCounter--;
}
// now we should have a 2 dimensional array with a list of a list of waypoints
var combinedResults;
var unsortedResults = [{}]; // to hold the counter and the results themselves as they come back, to later sort
var directionsResultsReturned = 0;
for (var k = 0; k < batches.length; k++) {
var lastIndex = batches[k].length - 1;
var start = batches[k][0].location;
var end = batches[k][lastIndex].location;
// trim first and last entry from array
var waypts = [];
waypts = batches[k];
waypts.splice(0, 1);
waypts.splice(waypts.length - 1, 1);
var request = {
origin: start,
destination: end,
waypoints: waypts,
travelMode: window.google.maps.TravelMode.WALKING
};
(function (kk) {
directionsService.route(request, function (result, status) {
if (status == window.google.maps.DirectionsStatus.OK) {
var unsortedResult = { order: kk, result: result };
unsortedResults.push(unsortedResult);
directionsResultsReturned++;
if (directionsResultsReturned == batches.length) // we've received all the results. put to map
{
// sort the returned values into their correct order
unsortedResults.sort(function (a, b) { return parseFloat(a.order) - parseFloat(b.order); });
var count = 0;
for (var key in unsortedResults) {
if (unsortedResults[key].result != null) {
if (unsortedResults.hasOwnProperty(key)) {
if (count == 0) // first results. new up the combinedResults object
combinedResults = unsortedResults[key].result;
else {
// only building up legs, overview_path, and bounds in my consolidated object. This is not a complete
// directionResults object, but enough to draw a path on the map, which is all I need
combinedResults.routes[0].legs = combinedResults.routes[0].legs.concat(unsortedResults[key].result.routes[0].legs);
combinedResults.routes[0].overview_path = combinedResults.routes[0].overview_path.concat(unsortedResults[key].result.routes[0].overview_path);
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getNorthEast());
combinedResults.routes[0].bounds = combinedResults.routes[0].bounds.extend(unsortedResults[key].result.routes[0].bounds.getSouthWest());
}
count++;
}
}
}
directionsDisplay.setDirections(combinedResults);
var legs = combinedResults.routes[0].legs;
var summaryPanel = document.getElementById('directions_panel');
summaryPanel.innerHTML = '';
var totdist=0;
// alert(legs.length);
for (var i=0; i < legs.length;i++){
var markerletter = "A".charCodeAt(0);
var markerletter2= "B".charCodeAt(0)
markerletter += i;
markerletter2 += i;
markerletter = String.fromCharCode(markerletter);
markerletter2 = String.fromCharCode(markerletter2);
createMarker(directionsDisplay.getMap(),legs[i].start_location,legs[i].start_address,markerletter);//To display location address on the marker
var routeSegment = i + 1;
var point=+routeSegment+1;
summaryPanel.innerHTML += '<b>Route Segment: ' + routeSegment + '</b><br>';
summaryPanel.innerHTML += '<b>Point '+ routeSegment +' :</b>'+ ' ' +legs[i].start_address + ' <br> ';
summaryPanel.innerHTML += '<b>Point '+ point +' :</b>'+ ' '+legs[i].end_address + '<br>';
summaryPanel.innerHTML += '<b>Distance Covered '+' :</b>'+legs[i].distance.text + '<br><br>';
var test=legs[i].distance.text.split(' ');
var one=parseFloat(test[0]);
if(test[1]=="m"){
var one=parseFloat(test[0]/1000);
}
totdist=parseFloat(totdist)+parseFloat(one);
}
summaryPanel.innerHTML += '<b> Total Distance :'+totdist + 'km'+ '</b><br><br>';
var i=legs.length;
var markerletter = "A".charCodeAt(0);
markerletter += i;
markerletter = String.fromCharCode(markerletter);
createMarker(directionsDisplay.getMap(),legs[legs.length-1].end_location,legs[legs.length-1].end_address,markerletter);
}
}
});
})(k);
}
}
};
}
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
var icons = new Array();
icons["red"] = new google.maps.MarkerImage("mapIcons/marker_red.png",
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
function getMarkerImage(iconStr) {
counts++;
if(counts==size){
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/blue.png";
}else{
if (iconStr=="undefined") {
iconStr = "red";
var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
else{
var markerimageLoc="http://www.google.com/mapfiles/marker"+ iconStr +".png";
// var markerimageLoc = "http://www.maps.google.com/mapfiles/ms/icons/red.png";
}
}
icons[iconStr] = new google.maps.MarkerImage(markerimageLoc,
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(25, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 6,20.
new google.maps.Point(9, 34));
return icons[iconStr];
}
// Marker sizes are expressed as a Size of X,Y
// where the origin of the image (0,0) is located
// in the top left of the image.
// Origins, anchor positions and coordinates of the marker
// increase in the X direction to the right and in
// the Y direction down.
var iconImage = new google.maps.MarkerImage('mapIcons/marker_red.png',
// This marker is 20 pixels wide by 34 pixels tall.
new google.maps.Size(20, 34),
// The origin for this image is 0,0.
new google.maps.Point(0,0),
// The anchor for this image is at 9,34.
new google.maps.Point(9, 34));
var iconShadow = new google.maps.MarkerImage('http://www.google.com/mapfiles/shadow50.png',
// The shadow image is larger in the horizontal dimension
// while the position and offset are the same as for the main image.
new google.maps.Size(37, 34),
new google.maps.Point(0,0),
new google.maps.Point(9, 34));
// Shapes define the clickable region of the icon.
// The type defines an HTML <area> element 'poly' which
// traces out a polygon as a series of X,Y points. The final
// coordinate closes the poly by connecting to the first
// coordinate.
var iconShape = {
coord: [9,0,6,1,4,2,2,4,0,8,0,12,1,14,2,16,5,19,7,23,8,26,9,30,9,34,11,34,11,30,12,26,13,24,14,21,16,18,18,16,20,12,20,8,18,4,16,2,15,1,13,0],
type: 'poly'
};
function createMarker(map, latlng, label, character) {
var markerletter=character;
if( /[^a-zA-Z]/.test( character ) ) {
var markerletter="undefined";
}
var contentString = '<b>'+label+'</b><br>';
var marker = new google.maps.Marker({
position: latlng,
map: map,
shadow: iconShadow,
icon: getMarkerImage(markerletter),
shape: iconShape,
title: label,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
marker.myname = label;
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
return marker;
}
}
}else{
}
},
error : function(e) {
alert('Error: ' + e,"Alert Box");
}
});
}
}
</script>
and i included div tag like this in body section
<div id="map" style="border: 2px solid #3872ac; height: 500px;"
class="col-sm-6"></div>
above code working fine if i am not using ajax,problem exist only for ajax
sorry to trouble all of you,i feel very silly that i declared variable of stops globally and i need to call methods like below
function initialize(data) {
size = 0;
counts = 0;
var map=0;
var stops = data;
size = stops.length;
if (stops.length > 0) {
var map = new window.google.maps.Map(document
.getElementById("map"));
// new up complex objects before passing them around
var directionsDisplay = new window.google.maps.DirectionsRenderer(
{
suppressMarkers : true,
polylineOptions : {
strokeColor : "black"
}
});
var directionsService = new window.google.maps.DirectionsService();
Tour_startUp(stops);
window.tour.loadMap(map, directionsDisplay);
i changed the below methods from window.tour.fitBounds(map); window.tour.calcRoute(stops,directionsService,
directionsDisplay); to
window.tour.fitBounds(map,stops);
if (stops.length > 1)
window.tour.calcRoute(stops,directionsService,
directionsDisplay);
}
}
I have a problem with my script. I want to remove the load more button and instead do an infinite scroll when I get to bottom of the page.
I'm using a WordPress template and without support I'm stuck on this nonsense.
What should I change to do to this script?
jQuery(document).ready(function($){
var $container = $('#hentry-wrapper');
// Isotope
// modified Isotope methods for gutters in masonry
$.Isotope.prototype._getMasonryGutterColumns = function() {
var gutter = this.options.masonry && this.options.masonry.gutterWidth || 0;
containerWidth = this.element.width();
this.masonry.columnWidth = this.options.masonry && this.options.masonry.columnWidth ||
// or use the size of the first item
this.$filteredAtoms.outerWidth(true) ||
// if there's no items, use size of container
containerWidth;
this.masonry.columnWidth += gutter;
this.masonry.cols = Math.floor( ( containerWidth + gutter ) / this.masonry.columnWidth );
this.masonry.cols = Math.max( this.masonry.cols, 1 );
};
$.Isotope.prototype._masonryReset = function() {
// layout-specific props
this.masonry = {};
// FIXME shouldn't have to call this again
this._getMasonryGutterColumns();
var i = this.masonry.cols;
this.masonry.colYs = [];
while (i--) {
this.masonry.colYs.push( 0 );
}
};
$.Isotope.prototype._masonryResizeChanged = function() {
var prevSegments = this.masonry.cols;
// update cols/rows
this._getMasonryGutterColumns();
// return if updated cols/rows is not equal to previous
return ( this.masonry.cols !== prevSegments );
};
var loadMore = $('#load-more');
var posts_per_page = parseInt(loadMore.attr('data-perpage'));
var offset = posts_per_page;
var totalPosts = parseInt(loadMore.attr('data-total-posts'));
var author = parseInt(loadMore.attr('data-author'));
var category = parseInt(loadMore.attr('data-category'));
var tag = loadMore.attr('data-tag');
var datemonth = loadMore.attr('data-month');
var dateyear = loadMore.attr('data-year');
var search = loadMore.attr('data-search');
var loader = $('#posts-count').attr('data-loader');
if (!author) author = 0;
if (!category) category = 0;
if (!tag) tag = '';
if (!datemonth) datemonth = 0;
if (!dateyear) dateyear = 0;
if (!search) search = '';
// cache jQuery window
var $window = $(window);
// start up isotope with default settings
$(window).load(function(){
reLayout();
$window.smartresize( reLayout );
if (offset < totalPosts) {
$('#nav-pagination-load-more').fadeIn(200);
mega_initLoadMore();
}
});
function reLayout() {
var mediaQueryId = getComputedStyle( document.body, ':after' ).getPropertyValue('content');
// fix for firefox, remove double quotes "
//mediaQueryId = mediaQueryId.replace( /"/g, '' );
//console.log( mediaQueryId );
var windowSize = $window.width();
var masonryOpts;
// update sizing options
switch ( mediaQueryId ) {
case 'large' :
masonryOpts = {
gutterWidth: 0
};
break;
case 'big' :
masonryOpts = {
//columnWidth: 297,
gutterWidth: 0
};
break;
case 'medium' :
masonryOpts = {
//columnWidth: 269,
gutterWidth: 0
};
break;
case 'small' :
masonryOpts = {
//columnWidth: $container.width() / 4,
gutterWidth: 0
};
break;
case 'tiny' :
masonryOpts = {
//columnWidth: $container.width() / 1,
gutterWidth: 0
};
break;
}
$container.isotope({
resizable: false, // disable resizing by default, we'll trigger it manually
itemSelector : '.type-post',
transformsEnabled: false, // Firefox Vimeo issue
masonry: masonryOpts
}).isotope( 'reLayout' );
}
function mega_initLoadMore(){
loadMore.click(function(e) {
$(this).unbind("click").addClass('active');
$('#posts-count').html('<img src="'+ loader +'"/>');
e.preventDefault();
mega_loadMorePosts();
});
}
function mega_reLayout(){
$container.isotope( 'reLayout' );
}
function mega_loadMorePosts(){
jQuery.ajax({
url: megaAjax.ajaxurl,
type: 'POST',
data: {
action : 'mega_ajax_blog',
nonce : megaAjax.nonce,
category: category,
author: author,
tag: tag,
datemonth: datemonth,
dateyear: dateyear,
search: search,
offset: offset
},
success: function( data ) {
var $newElems = $(data);
// ensure that images load before adding to masonry layout
$newElems.imagesLoaded( function(){
// FitVids
$('.fluid-video, .entry-content', $newElems).fitVids();
$container.append($newElems).isotope( 'appended', $newElems );
// Flex Slider
$('.flexslider', $newElems).flexslider({
animation: "fade",
slideshow: false,
keyboard: false,
directionNav: true,
touch: true,
prevText: "",
nextText: ""
});
setTimeout(function(){
mega_reLayout();
}, 1000);
offset = offset + posts_per_page;
loadMore.removeClass('active');
if (offset < totalPosts){
$('#posts-count').text('');
loadMore.bind("click", mega_initLoadMore());
}
else {
setTimeout(function(){
loadMore.parent().remove();
}, 1000 );
}
});
}
});
return false;
}
});
I think this script is taken from "HEAT WORDPRESS THEME" directly which is located in js folder of the theme. Its simple to modify,you just need to remove Ajax post loading function and keep Isotop initializing function only. For help see this link
http://www.shambix.com/en/isotope-twitter-bootstrap-infinite-scroll-fluid-responsive-layout/
I am developing a web app with Django and i have this ajax where i'm refreshing some images from the db in order to display them in a template.
function refreshUploadedImages() {
var inputs = ['Designer Name', 'Color', 'Fabric', 'Type', 'Tag', 'Subtag'];
$.getJSON('/admin/image-uploader/images', function(data) {
$('#uploadedFiles').empty();
for (uiid in data) {
ui = data[uiid];
var div = $('<div>');
div.data('id', ui.id);
// image
var image = new Image();
image.src = ui.url
image.width = 180;
div.append($('<div>').append(image));
// list
var ul = $('<ul>')
div.append(ul)
// inputs
for (input in inputs) {
ul.append(
$('<li>').append(
$('<label>').append(
$('<span>').append(document.createTextNode(inputs[input] + ':'))
).append($('<input>'))));
}
$('#uploadedFiles').append(div);
div.append('<li><input type="button" class="delete-img-btn" id = <<ui.id>> img-id=image.id value="Delete"/></li>');
}
$(window).trigger('uploadedImagesRefresh');
});
$(function(){
//
$('.delete-img-btn').live('click', function() {
//asign the image id from the button attribute 'img-id'
var id= $(this).attr('img-id');
//The data to be send via ajax the server will recieve 2 POST variables ie. 'action' and 'id'(which is the img id)
var data={
'action':'/admin/image-uploader/',
'pk' : id,
'success':refreshUploadedImages
};
//The ajax request.
vary = $('.delete-img-btn').attr('id');
$.post("/admin/image-uploader/delete/"+vary , data);
});
});
}
My problem is, in this line
div.append('<li><input type="button" class="delete-img-btn" id = <<ui.id>> img-id=<<<image.id>>> value="Delete"/></li>');
I want to assign id a variable ui.id i.e (id = <<ui.id>> ) which is defined somewhere outside the div.append. Can you help me on how to do it please.
Is this all you're trying to do?
div.append(
'<li><input type="button" class="delete-img-btn" id="'
+ ui.id + '" img-id="'
+ image.id + '" value="Delete"/></li>');
image.id isn't defined though.
Somehow I am unable to fire the onerror event or get the code in the onerror to work. This code is an attempt to collect a sequence of images in an array. I am using onerror event in order to mark the end of sequence and thus terminate the loop.
//definition of Slide object
function Slide(inpImage, imgCaption) {
this.inpImage = inpImage;
this.imgCaption = imgCaption;
}
window.onload = function() {
var defaultImage = img_slide.src; //This is a default file
//basically getting the file path and name of next image in the sequence
var nextImage = f_nextFile(f_path(img_slide.src),f_serial(img_slide.src));
//An array object which stores Slide Objects
arr_slides.push(new Slide(img_slide,img_slide.src));
while (defaultImage != nextImage){ //code to populate arr_slides array
var imgObj = new Image();
imgObj.src = nextImage;
arr_slides.push(new Slide(imgObj,nextImage));
//get the next image in the sequence of images
nextImage = f_nextFile(f_path(nextImage),f_serial(nextImage));
testImage = function(nextImage,defaultImage){
var tester=new Image();
tester.onerror = function () {
nextImage = defaultImage;
};
tester.onload = function () {
//do nothing
};
var loadNext = function() {
tester.src=nextImage;
};
loadNext();
};
testImage(nextImage,defaultImage);
}
alert("The number of images in array : " + arr_slides.length);
};