initialization code placement for ajax call - javascript

One of my page has buttons like- btnNext, btnPrevious, btnZoomIn, btnZoomOut and a div housing a tag. The images are loaded from the database.
I am using 'smooth zoom pan' plugin (http://vectorflower.com/preview/smooth_zoom/) on the images to achieve Zoom In and Zoom Out functions.I invoke the zoom in & zoom out functions using the code:
<script>
jQuery(function($){
initSmoothZoom();
});
function initSmoothZoom(){
$('#pgimg').smoothZoom({
width: '100%',
height: '100%',
zoom_BUTTONS_SHOW : 'NO',
pan_BUTTONS_SHOW : 'NO',
pan_LIMIT_BOUNDARY : 'YES',
zoom_MAX:800,
zoom_MIN:100,
responsive: true,
responsive_maintain_ratio: true,
border_TRANSPARENCY: 0,
});
}
</script>
Navigation buttons - btnNext & btnPrevious when clicked loads new image from the database using ajax.
The first time when the page loads, zoom in & zoom out functions work perfectly. However, when next image is loaded using ajax by the navigation buttons, the zoom in & zoom out function don't work. They begin to work only after hitting refresh.
I tried to call the zoom in & zoom out initialization code inside the ajax: success function, even then it does not work.
function loadNextImage(){
....................
$.ajax({
type:'POST',
url:"<?php echo base_url(); ?>pages/load_req_page_via_navigator/",
dataType: 'json',
data: {..........................},
beforeSend: function() {
$("#loader").show();
},
success:function(result){
destroy_ias();
initSmoothZoom();//<------------------
$("#canvas").html(result);
},
error: function(result)
{
alert('error:'+result);
},
fail:(function(result) {
alert('fail:'+result);
}),
complete: function() {
$("#loader").hide();
}
});
}
...................
}
Please tell someone, as where should i placed the initialization so that it will work.

Related

How to show loading image on dropdown change event(SelectedIndexChange)

I have a dropdown and grid on my page.On change of dropdown value the grid gets refreshed.The data which is bind to the grid is fetched from the database.When I change dropdown value I should be able to see a loading image on my screen.After the data is loaded the loading image should disappear.How will I achieve this??
Any suggestion will be helpful..
Below is the code that I have used for submit click .How should I modify it to work on dropdown change event.
<script type="text/javascript">
function ShowProgress() {
setTimeout(function () {
var modal = $('<div />');
modal.addClass("modal");
$('body').append(modal);
var loading = $(".loading");
loading.show();
var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
loading.css({ top: top, left: left });
}, 200);
}
$('form').live("submit", function () {
ShowProgress();
});
You can, of course, show it before making the request, and hide it after it completes:
Html :
<div id='loading-image'>
<img src='loadinggraphic.gif'/>
</div>
Script :
$('#loading-image').show();
$.ajax({
url: 'data.php',
cache: false,
success: function(data){
$('.info').html(data);
},
complete: function(){
$('#loading-image').hide();
}
});
Here, in data.php you can put your logic to fetch the data from the database.
I usually prefer the more general solution of binding it to the global ajaxStart and ajaxStop events, that way it shows up for all ajax events:
$('#loading-image').bind('ajaxStart', function(){
$(this).show();
}).bind('ajaxStop', function(){
$(this).hide();
});

jQuery Reload div onclick

Trying to make jQuery reload a .php file I have in my directory whenever I press a certain button.
(function($)
{
$(document).ready(function()
{
$('.loadimg').hide();
$.ajaxSetup(
{
cache: false,
beforeSend: function() {
$('.loadimg').show();
$('#loadunasreports').hide();
},
complete: function() {
$('#loadunasreports').show();
$('.loadimg').hide();
},
success: function() {
$('#loadunasreports').show();
$('.loadimg').hide();
}
});
var $container = $("#loadunasreports");
$('#reloaddata').click(function() {
$container.load("unasreport.php");
});
});
})(jQuery);
When I press #reloaddata it shows and hide the div as supposed to, but it doesn't reload the php file in that div. However if I make it load dynamicly every 10 seconds for example then it works, but that's not what I want.
So how should I do?

jQuery Infinite Scroll's loading fires too early

I tried to implement jQuery Infinite Scroll. But the loading fires too early. At first, it fires even if I only scroll the page 1 pixel. And then it still fires far before I scroll the page to the bottom.
At first, I make an Ajax call to fill in the first page. Then I initialize Infinite Scroll. As following.
$.ajax({
url : 'data/page1.html',
cache : true,
dataType : 'html',
success : function(newElements) {
$('#container')
.append(newElements)
.infinitescroll({
// -- selector for: --
navSelector : '#pagenav', // the paged navigation
nextSelector : '#pagenav', // the NEXT link (to page 2)
itemSelector : '.item', // all items you'll retrieve
// --
loading : {
finishedMsg: 'No more items to load',
img: 'images/ajax-loading.gif'
}
});
}
});
I had simplified my files at here for demonstration purpose.
EDIT: Demonstration on Plunker.
After checking the source code, I found on line 423 that the loading has something to do with the position of navigation. Then I realized that I hid navigation by setting display: none; to it in my CSS that caused the script to be unable to calculate the position of navigation correctly. After removing display: none;, the problem has been fixed.
Thank everyone who tried to help me.
Try it like this
$(document).ready(function() {
$('#container').infinitescroll({
dataType: 'html',
appendCallback: false,
navSelector: '#pagenav', // selector for the paged navigation
nextSelector: '#pagenav', // selector for the NEXT link (to page 2)
itemSelector: '.item',
pixelsFromNavToBottom: 50
});
});
Plunker
Try this
$(document).ready(function() {
$.ajax({
url: "data/page1.html",
cache: true,
dataType: "html",
success: function(newElements) {
setTimeout((function() {
$("#container").append(newElements).infinitescroll({
navSelector: "#pagenav",
nextSelector: "#pagenav",
itemSelector: ".item",
loading: {
finishedMsg: "No more items to load",
img: "images/ajax-loading.gif"
}
});
}), 5000);
}
});
});
I had the same problem when I was looking for an infinite scroll plugin, so I ended up using Endless Scroll.
The good thing about this plugin is that you can define options, such as 'bottomPixels', as shown in the following example:
$(document).endlessScroll({
bottomPixels: 300,
fireDelay: 200,
callback: function() {
if ($('#table').length > 0 && !loadedAllEntries && !loadPending) {
loadEntries($('#table tbody tr').size());
}
},
ceaseFire: function() {
if (loadedAllEntries)
return 1;
if ($('#table').length === 0)
return 2;
}
});
I set loadPending to true in the beginning of every request so that only one request is active for every given moment. Hope this helps.

tumblr audio + Masonry with infinite scroll- other solutions posted have confused me [duplicate]

Here's a test page: http://masonry-test.tumblr.com/
I'm using jquery Masonry with infinite scroll on tumblr. All is fine except with audio players. They won't load on the second page and display this message instead [Flash 9 is required to listen to audio.].
Did a little research and found a solution. One here (this one too) and here's the js from the Mesh theme that does that successfully (line 35).
Problem is I don't know where and how to implement it in my code. Everything I tried either wasn't working or it left a small gap around the masonry blocks. My code:
$(document).ready(function () {
var $container = $('.row');
$container.imagesLoaded(function () {
$container.masonry({
itemSelector: '.post',
columnWidth: 1
});
});
$container.infinitescroll({
navSelector: '#page-nav',
nextSelector: '#page-nav a',
itemSelector: '.post',
loading: {
finishedMsg: "No more entries to load.",
img: "http://static.tumblr.com/7wtblbo/hsDlw78hw/transparent-box.png",
msgText: "Loading..."
},
debug: true,
bufferPx: 5000,
errorCallback: function () {
$('#infscr-loading').animate({
opacity: 0.8
}, 2000).fadeOut('normal');
}
},
function (newElements) {
//tried this but doesn't work
/* repair video players*/
$('.video').each(function(){
var audioID = $(this).attr("id");
var $videoPost = $(this);
$.ajax({
url: '/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
$videoPost.append('\x3cdiv class=\x22video_player_label\x22\x3e' + data.posts[0]['video-player'] +'\x3c/div\x3e');
}
}
});
});
/* repair audio players*/
$('.audio').each(function(){
var audioID = $(this).attr("id");
var $audioPost = $(this);
$.ajax({
url: '/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
$audioPost.append('\x3cdiv class=\x22audio_player\x22\x3e' + data.posts[0]['audio-player'] +'\x3c/div\x3e');
}
}
});
});
var $newElems = $(newElements).css({
opacity: 0
});
$newElems.imagesLoaded(function () {
$newElems.animate({
opacity: 1
});
$container.masonry('appended', $newElems, true);
});
});
$(window).resize(function () {
$('.row').masonry();
});
});
By default the API will return a white audio player.
you can change it by using the jQuery method to replace the flash player with a black or white player respectively.
.replace("audio_player.swf", "audio_player_black.swf")
or simply change the color itself
.replace("color=FFFFFF", "color=EA9D23");
Example:
$('.audio').each(function(){
var audioID = $(this).attr("id");
var $audioPost = $(this);
$.ajax({
url: '/api/read/json?id=' + audioID,
dataType: 'jsonp',
timeout: 50000,
success: function(data){
$audioPost.append('\x3cdiv class=\x22audio_player\x22\x3e' + data.posts[0]['audio-player'].replace("audio_player.swf","audio_player_black.swf") +'\x3c/div\x3e');
}
}
});
I had a lot of trouble with this and hope it helps someone out. I found the above information here Change Tumblr audio player color with Javascript.
I noticed a few things and this is what I advise you to try:
For that script to work, the elements with the class "audio" should each have an "id" attribute with the post ID. The HTML should look like that:
<div class="audio" id={PostID}>{AudioPlayerWhite}</div>
Tumblr will automatically fill the {PostID} part with the ID for each post. I suppose it works in the same manner for videos (haven't tried it with videos yet).
As for position, I did it like this:
function (newElements) {
....
$newElems.imagesLoaded(function () {
....
});
//audio repair goes here!
}
Here is a solution I came up with when I needed to implement the same functionality in the template I was creating.
In your HTML, include your AudioPlayer Tumblr tag between comments. This is to prevent loaded scripts from being called. Also add a class "unloaded" to keep track whether or not we've loaded the audio player for this post or not.
...
{block:AudioPlayer}
<div class="audio-player unloaded">
<!--{AudioPlayerBlack}-->
</div>
{/block:AudioPlayer}
...
If you look at the commented code after the page is loaded, you will notice an embed tag being passed to one of the Tumblr javascript functions. Since we commented it, it will not execute. Instead we will want to extract this string and replace the div contents with it.
Create a javascript function which will do this. This can be done with regular javascript, but to save time I will do it with jQuery since this is how I did it for my template:
function loadAudioPosts() {
// For each div with classes "audio-player" and "unloaded"
$(".audio-player.unloaded").each(function() {
// Extract the <embed> element from the commented {AudioPlayer...} tag.
var new_html = $(this).html().substring(
$(this).html().indexOf("<e"), // Start at "<e", for "<embed ..."
$(this).html().indexOf("d>")+2 // End at "d>", for "...</embed>"
);
// Replace the commented HTML with our new HTML
$(this).html(new_html);
// Remove the "unloaded" class, to avoid reprocessing
$(this).removeClass("unloaded");
});
}
Call loadAudioPosts() once on page load, then every time your infinite scrolling loads additional posts.

How do enable tooltip on dynaically added code?

I have a site, which uses paging.
I use the following plugin for tooltips: http://plugins.jquery.com/project/tooltip
I use AJAX to update a div container. This is the code:
$(".page-number").live("click", function ()
{
var page = parseInt($(this).html());
var progressbarValue = ((page / $("#NumberOfPages").val()) * 100);
var catId = $("#CategoryID").val();
$.ajax({
url: '#Url.Action("QuestionList")',
data: { "categoryId": catId, "page": page },
success: function (data) {
$("#question-list").html(data);
$("#progressbar").progressbar("value", progressbarValue);
$("#progresstext").html("<p>" + Math.round(progressbarValue) + "% gennemgået</p>");
EnableDisableToolTip();
}
});
});
This is the function to enable/disable tooltips:
<script type="text/javascript">
function EnableDisableToolTip() {
var help_text = $("#helptext_checkbox").is(':checked:');
if (help_text) {
alert("true");
$(".tooltip").qtip("enable")
}
else if (!help_text) {
alert("false");
$(".tooltip").qtip("disable");
}
}
</script>
When i load a new page, i cannot see any tooltips when i hover the mouse over an element with class="tooltip". Also, when i view the source code, the dynamically added code isnt there. It works on the first page, and the source code with class="tooltip" is there. But not with the dynamic stuff.
How can i solve this issue?
[EDIT]
The tooltip code:
$(".tooltip").each(function()
{
$(this).qtip({
show: 'mouseover',
hide: 'mouseout',
style: {
name: 'light', // Inherit from preset style
width: {
min: 0,
max: 250
},
},
position: {
corner: {
target: 'topMiddle',
tooltip: 'bottomLeft'
},
adjust: {
screen: true,
scroll: false
}
}
});
});
Viewing the page source shows what was delivered to the client when the page was originally requested. It does not show the current DOM.
When you add the new content to the page, it does not know what has been run. You need to rescan the page for tooltips when the content is added.
In EnableDisableToolTip there is a condition to enable/disable the tooltip ($("#helptext_checkbox").is(':checked:')). Are you sure it is checked when you make a ajax call? I think it is not checked due to which the tooltip is not enabled.

Categories

Resources