Tumblr 'loading more' button - ajax

In the first place I want to say sorry for my bad english . I'm trying to develop a tumblr theme , and add a 'loading more' button . I used JavaScript to determinate the current page and the next one . When 'Loading More' button is pressed , I use jQuery to make a request to next tumblr page ex ( sitename.tumblr.ro/page/next-page ) , get the html , extract the posts html and append it to current page . But the problem is that the like button is not working on the appended posts . When I click the button , noting is happening . The cursor is not even pointing ... Here's my javascript code :
var $holder = $('div.posts_holder');
var page = null;
$(document).on('click','div.loading_more.loading_trigger',function(){
if(page == null)
{
page = window.location.href.search('page') > -1 ? window.location.href.split('/')[window.location.href.split('/').length-1] : 1;
}
page = Number(page)+1;
$(this).text('Please Wait..');
var load_page = '{BlogURL}page/'+page;
var $saved = $(this);
//get the page
$.get(load_page,function(response)
{
var $append_html = $(response).find('div.posts_holder');
if($append_html.html().replace(' ','').trim() == '')
{
$saved.removeClass('loading_trigger');
}
$saved.text('Loading More');
$holder.append($append_html.html()).masonry();
$holder.masonry( 'reloadItems' );
$holder.masonry( 'layout' );
setTimeout(function(){
$holder.masonry( 'reloadItems' );
$holder.masonry( 'layout' );
},800);
});
});

I found the answer . You must add :Tumblr.LikeButton.get_status_by_page(page); to your javascript after you added new items ,where 'page' is the number of page you just added.

Related

Display image one by one

I have a checkbox in my form that will display images when an item is checked .
Is it possible that the images will be displayed one by one every time an item is clicked because at the moment , every time I checked an item on the checkbox , it is displayed on the div that I assigned .
What I want to achieve is , when an item is checked , it will be displayed and when I clicked another item , the previous image will be overridden by the new item that was checked .
I assigned an ID and class in the image and here is my JS :
jQuery(document).ready(function( $ ){
$(function() {
$('.decalcheckbox input[type=checkbox]').on("change",function() {
var checkbox = $(this).val().toLowerCase();
var checkboxremovespace = checkbox.replace(/ /g, "_")
$('#decal_'+ checkboxremovespace).toggle(this.checked);
}).change(
); // trigger the change
});
});
Sorry for my English but I hope I explained what I want to say .
Thanks .
I just made some modification on my code as follows .
Hopefully someone can shed some light .
jQuery(document).ready(function( $ ){
$(function() {
$('.decalcheckbox input[type=checkbox]').on("change",function() {
if ($(this).is(':checked')) {
$("#bento_preview_item").hide();
}
else{
$("#bento_preview_item").show();
}
var checkbox = $(this).val().toLowerCase();
var checkboxremovespace = checkbox.replace(/ /g, "_")
$('#decal_'+ checkboxremovespace).toggle(this.checked);
}).change(
); // trigger the change
});
});
Thanks .

Packery not arranging additional divs when loaded via AJAX

I am using packery to arrange blog posts in a masonry format. This works fine for posts that are initially displayed on the page but when I load new posts - when the pagination links are clicked - via AJAX the posts just get added to the container but do no 'repack' or re-arrange in a masonry format.
I am using WordPress and using my own AJAX call, see code below:
// For jQuery noConflict
(function($) {
$(document).ready(function() {
// Find out the page number
var pageNumber;
$('.custom-pagination a.page-numbers').click(function() {
pageNumber = $(this).html();
});
// AJAX call to load more posts when pagination links are clicked
$(document).on( 'click', '.custom-pagination a.page-numbers', function( event ) {
event.preventDefault();
page = pageNumber;
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
success: function( html ) {
var $container = $('#all-posts').packery();
$container.append( html );
$container.packery( 'appended', html );
}
});
});
});
})(jQuery);
// End jQuery noConflict
Can anyone point me in the right direction on how to call packery again to re-arrange my posts in a masonry format after they are loaded via AJAX?
Thanks.
I had the same issue, and took care of it server-side (web2py/python), in accordance with the instructions here:
# this function is called via ajax
def function_that_loads_the_new_content():
...
new_divs = #generate new content
new_divs_as_string = ''.join([str(x) for x in new_divs])
# this script runs when the new content is appended to the container
update_results = \
"var $items = $('%s');$pack.append($items).packery( 'appended', $items );" \
% new_divs_as_string
return update_results
The idea is to use packery's appending functionality after the new elements have been added to the container element. The above script is essentially equivalent to this template offered in the packery page:
$('.append-button').on( 'click', function() {
// create new item elements
var $items = $('<div class="grid-item">...</div>');
// append items to grid
$grid.append( $items )
// add and lay out newly appended items
.packery( 'appended', $items );
});

Is it possible to implement a circular/infinite carousel using owl carousel? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am using owl carousel and it works perfectly except it does not support circular/infinite scrolling. I did search for ideas on google and stackoverflow with no luck. Has anyone implemented circular/infinite scrolling in owl carousel?
Owl Carousel does have the loop: true configuration setting. But, there's a few problems I don't like:
Owl doesn't goto the first slide when at the end, when dragging (instead of clicking on navigation buttons)
Owl rewinds to the first slide, it doesn't wrap around infinitely. This is a big difference, and not nearly as pleasing as a properly circular / infinitely scrolling carousel.
To that end I've found and recommend using the Slick Carousel instead. Slick has a "Center Mode" which had exactly the functionality I was looking for:
http://kenwheeler.github.io/slick/
No.They said that carousel doesn't support circular slides.
Possibly this may help:
rewindNav: true
But this works only with navigation arrows, not with responsive slides =(
Or you may huck it somehow)
I was able to accomplish it using jquery/php/ajax. Here is how I did it:
1) First you need to initially place the first x amount of images on the page which will technically be the first page and then afterwards you'll load via ajax each time you reach the end of the carousel. In the example script I supplied I am getting a list of images from a fictional database table called "images". In my php script, for this particular example, it will return 24 owl-item divs with content. For this example I will loading 24 images at a time on the first page initially and then ajax will attempt to return 24 more each time.
HTML (You will need to add the first items into the carousel div and these items will technically be the first page of items. You could use php to populate the divs/image source for the initial first page. Just use regular divs like I did below because the carousel will add the owl-item class to them once it initializes).
<div class="circle-slider">
<div>
<img src="/path/to/image/1" />
</div>
<div>
<img src="/path/to/image/2" />
</div>
.... the rest of the images go here, each in their own div ....
.... for this example I'd load 24 images total ...
</div>
Javascript (This javascript goes on the same page as the HTML above.)
<script type="text/javascript">
$(document).ready(function() {
var itemsPerPage = 0; // The number of items per page.
var page = 2; // Start on page 2 since we initially created page 1 in HTML
var working = false; //Boolean to keep the trigger from firing while we work
var lastvalue = 0; //last value of the owl objects item position array
var carouselDiv = '.circle-slider'; // the div that you will be placing the owl carousel on. See HTML above. MUST BE IN jQuery Notation.
//Normal Owl Carousel Setup. See their site for more options. My example works with these options. No guarantee if you change them to something else that it will work.
$(carouselDiv).owlCarousel({
items : 1,
itemsDesktop : [1920,2],
itemsDesktopSmall : [980,2],
itemsTablet: [768,2],
itemsTabletSmall: [480,1],
itemsMobile : [370,1],
singleItem : false,
itemsScaleUp : false,
slideSpeed : 800,
paginationSpeed : 300,
rewindSpeed : 250,
pagination:false,
autoPlay : false,
afterMove : function() {
// This is where all the magic happens. Once you slide the items around and let go this afterMove callback fires.
var owl = $(carouselDiv).data('owlCarousel'); //get the current owl carousel object
lastvalue = owl.positionsInArray[owl.positionsInArray.length-1]; //Get the last item position value in the position array
if((owl.currentItem == owl.maximumItem) && !working){
working = true; //Set working to true so we dont fire more events and load more items until this request is finished working
$.ajax({
method: "GET",
url: "/path/to/php/script/see/script/below",
async: false,
dataType: "script",
data: { page: page, itemWidth: owl.itemWidth }
}).done(function( data ) {
itemsPerPage = parseInt(cresults.numberOfItems, 10);
if( itemsPerPage ){
$('.owl-wrapper').width($('.owl-wrapper').width() + (itemsPerPage * owl.itemWidth)); //modify the width of the wrapper div to handle the new items
$('.owl-wrapper').append(cresults.html); //append the markup
owl.maximumItem = parseInt(owl.maximumItem, 10) + parseInt(itemsPerPage, 10); //modify the max items in the owl object
for (var i = 0; i < itemsPerPage; i++) { // add new indexes in the position array for the owl object.
lastvalue = lastvalue-owl.itemWidth
owl.positionsInArray.push(lastvalue);
}
owl.maximumPixels = owl.maximumPixels - (owl.itemWidth * itemsPerPage); //modify the owl maximum pixels to accomodate new items
owl.$owlItems = $(carouselDiv).find(".owl-item");
page = page + 1;
}
working = false;
});
}
}
});
});
</script>
PHP SCRIPT (Create a php file and this should be the page that is used in the ajax url in the JavaScript i.e. $.ajax({method: "GET",url: "/path/to/php/script"..... )
<?php
$page = isset($_GET['page']) ? $_GET['page'] : 2;
$itemWidth = isset($_GET['itemWidth']) ? $_GET['itemWidth'] : 0;
//Get 24 images from my database
$link = mysqli_connect("myhost","myuser","mypassw","mybd") or die("Error " . mysqli_error($link));
$query = 'SELECT * FROM images LIMIT 24 OFFSET ' . (($page - 1) * 24);
$result = $link->query($query);
$return = null;
while($image = mysqli_fetch_object($result)) {
$return .= '<div style="width: ' . $itemWidth . 'px;" class="owl-item"><div><img src="' . $image->path . '" alt="img" /></div></div>';
}
mysqli_close($link);
// Replace some characters in the return string to they wont mess up javascript
$return = preg_replace('/\n/s', "", $return);
$return = preg_replace('/\s\s+/', ' ', $return);
$return = preg_replace('/\'/', '’', $return);
echo 'cresults = { "html" : \'' . $return . '\', numberOfItems: \'' . $result->num_rows . '\'};'; //echoing the return value will fulfill the Ajax call to this method
That's pretty much it. Easy as pie. Works pretty well too. If the browser resizes and causes the owl items to resize as well, it does reset the carousel back to the first item but I figured out how to add the items to the object so it doesnt mess things up and that is already included in the JavaScript. Let me know if you have any issues and I might be able to help fix them. Been working on this several days and just got this working so I haven't had time to extensively test it but I know it works on mobile phones, both iPhone and Android and works on iPads as well as on desktop browsers. Have fun!

jQuery hashchange how to do?

I have made a jQuery thing; with will load content without refreshing the page. The code for that is:
$(document).ready(function(){
// initial
$('#content').load('content/index.php');
// handle menu clicks
$('#navBar ul li ').click(function(){
var page = $(this).children('a').attr('href');
$('#content').load('content/'+ page +'.php');
return false;
});
});
Now I want to have a sort of history thing in that, the code for that is:
(function(){
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('#nav a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
Found on: http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
My Question is: how can i make the second code working with the first?
Since you haven't gotten an answer yet I will write it. You need the plugin jQuery hashchange for the code to run.
https://github.com/cowboy/jquery-hashchange
To implement a cache you could do something like
$('#content').load('content/index.php');
//create a cache object
var cache = {};
// handle menu clicks
$('#navBar ul li ').click(function(){
var page = $(this).children('a').attr('href');
//check if the page was already requested
if(cache[page] === undefined){
//if not fetch the page from the server
$.get('content/'+ page +'.php', function(data){
$('#content').html(data);
//save data in cache
cache[page] = data;
}else{
//use data from cache
$('#content').html(cache[page]);
}
return false;
});
Use History JS. It works for HTML5 pushState and also falls back to HTML 4 hashtags. Also works for keeping the state model when the page is refreshed.

CKEditor: Customized HTML on inserting an image

I'm using CKEditor 3.5 to provide WYSYWYG editing in a website. When inserting an image you can provide width and height of the image, which results in HTML like follows:
<img alt="" src="/Images/Sample.png" style="width: 62px; height: 30px; " />
Since this does the resizing in the browser and in other places on the same website I use Nathanael Jones' Image Resizing Module, I'd like to get the following output instead:
<img alt="" src="Images/Sample.png?width=62&height=30" />
Is there an easy way to control the generated HTML or have I really to write my own dialog/plugin for CKEditor?
EDIT:
Adding the following lines to config.js was the solution that eventually worked for me:
CKEDITOR.on('dialogDefinition', function (ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var dialog = dialogDefinition.dialog;
var editor = ev.editor;
if (dialogName == 'image') {
dialogDefinition.onOk = function (e) {
var imageSrcUrl = e.sender.originalElement.$.src;
var width = e.sender.originalElement.$.width;
var height = e.sender.originalElement.$.height;
var imgHtml = CKEDITOR.dom.element.createFromHtml('<img src=' + imageSrcUrl + '?width=' + width + '&height=' + height + ' alt="" />');
editor.insertElement(imgHtml);
};
}
});
The next problem is then, when editing an image, the width and height naturally are in the URL field and are missing in the dedicated fields for width and height. So I need to come up with a solution for the reverse... :-)
I kind of had the same problem, I needed to remove those attributes from the generated HTML for the image, so what I did was to override the onOK method of the uploader and insert the image element manually using the CKEditor's API, something like this:
CKEDITOR.on('dialogDefinition', function(ev) {
// Take the dialog name and its definition from the event data
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
var editor = ev.editor;
if (dialogName == 'image') {
dialogDefinition.onOk = function(e) {
var imageSrcUrl = e.sender.originalElement.$.src;
var imgHtml = CKEDITOR.dom.element.createFromHtml("<img src=" + imageSrcUrl + " alt='' align='right'/>");
editor.insertElement(imgHtml);
};
}
}
This has worked for us so far.
Look at the "output html" sample, you can find there some code that changes the dimensions in images from styles to attributes, so you can adjust it to rewrite the URL.
I don't have enough points to comment on that previous answer. but in respect to your error: CKEDITOR.currentInstance returns undefined.
That is strange because CKEDITOR is global, but you shouldn't have to resort to that.
Within the OK function invocation, you have access to "editor", you shouldn't have to get the instance.
just a suggestion.
Best bet might be to "recreate" the src (and possibly the style) field's behavior. I've do something similar. (but not as complex)
Start with the original code (from plugins/dialog/image.js) and create setup and commit logic that produces (and parses) the markup you're looking for.
Then during dialog definition
Delete Originals
Add your "custom" fields
style field not sure, maybe just leave it in the dialog, but stub out it's commit logic.
I added my field to the dialog...
var infoTab = dialogDefinition.getContents( 'info' );
// Move the ID field from "advanced" to "info" tab.
infoTab.add( idField_config);
var idField_config = {
type : 'text',
label : 'Name',
id : 'linkId',
setup : function( type, element ) {
//if ( type == IMAGE )
this.setValue( element.getAttribute( 'id' ) );
},
commit : function( type, element ) {
//if ( type == IMAGE ) {
if ( this.getValue() || this.isChanged() )
element.setAttribute( 'id', this.getValue() );
//}
}
};
Issues I faced.
New fields get added to end of
dialog.
Pieces of the original code
( type == IMAGE ) isn't valid (Love to know why but felt comfortable it was safe to comment for my usage)
You might face problems with the markup rules undoing your hard work, but "output html" sample" suggestion should help you weed through that issue.

Resources