Load html with ajax and delegate on success to function - javascript

On page load menu.php is appended. Now it needs to activate the function mmenu once it is loaded successfully.
$("nav#menu" ).load( "/v4/inc/menu.php" );
$("nav#menu").mmenu({
offCanvas : {
position : "left",
zposition : "front"
},
counters: true
})

You need to use the complete callback of load() so that your menu plugin is initialized after the html exists for it
$("nav#menu" ).load( "/v4/inc/menu.php", function(){
/* the new html now exists */
$(this).mmenu({
offCanvas : {
position : "left",
zposition : "front"
},
counters: true
});
});
See load() API Docs

Related

fancybox beforeClose issue

I have a form implemented in a fancybox (version 2.1.5) iframe. People can choose to not to fill up the form and click on "X" to close fancybox form or alternately fill up the form and click on Register.
I have a beforeClose callback setup to set cookies and do some work. But I want this to be triggered only if someone clicks on "X" or Esc key. See code below
$.fancybox.open({
type: "iframe",
href: "/[url].php",
autoSize: true,
height: "auto",
margin: 0,
padding: 0,
autoCenter: true,
maxWidth: 460,
maxHeight: 615,
modal: false,
iframe: {
scrolling: "no"
},
beforeClose: function () {
//set cookie code
},
});
But if someone was to Register, it will show a Thank you message for 2 seconds and close the fancybox. This is done by using window.parent.$.fancybox.close(); See detailed code below
$.post('/register.php', post_vars, function(data) {
window.parent.$.fancybox.close();
});
However I do not want the beforeClose event to be called in case I close it from the iFrame or even if it gets called, I need to somehow know that it has been done from the iframe & not using the "X" button.
Is there a way to differentiate this?
I can think different ways to do this, like binding custom events to the fancybox close button or catching the escape key with keyup or keypress, etc.
I guess the simplest way is to create in the parent page, a custom close function like :
var closedFromIframe = false;
function customClose() {
closedFromIframe = true;
jQuery.fancybox.close();
}
This function will close fancybox (from the parent page itself) when invoked from the iframed page AND will enable the (previously defined) closedFromIframe flag, so instead of this :
$.post('/register.php', post_vars, function(data) {
window.parent.$.fancybox.close();
});
... you could do
$.post('/register.php', post_vars, function(data) {
window.parent.customClose();
});
Then, in your fancybox script you could validate within the beforeClose callback, the status of the closedFromIframe flag and do whatever you need to :
$.fancybox.open({
// your API options
beforeClose : function () {
if (closedFromIframe) {
// closed from iframe custom function
} else {
// close button -or- escape key
}
},
afterClose : function () {
closedFromIframe = false; // reset flag
}
});
Notice we are also resetting the closedFromIframe flag within the afterClose callback.
See a DEMO of this implementation.
This will be triggered only if someone clicks on "X" or Esc key
$(document).ready(function () {
$(".fancybox").fancybox({
closeClick: false, // prevents closing when clicking INSIDE fancybox
openEffect: 'none',
closeEffect: 'none',
enableEscapeButton: false,
helpers: {
overlay: {
closeClick: false // prevents closing when clicking OUTSIDE fancybox
}
},
beforeClose: function () {
return confirm('Are you sure?')
}
})
});

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.

how to detect onClick or click event on a view added to kendo window

I have kendo window popup which I open on some event being fired. In that kendo window I have added a view using window.content(new View().el).The View contains several divs one of which has id leftarrow.
Onclick on div #leftArrow I need to do something. But I am not able to detect the onclick event .
I have added on the click event listener in the view and given it a callback function. When I put event listener breakpoint on click , the event is firing but somehow it is not getting listened in the view .Can anybody tell where the problem is??
/*This is the controller file where I have created the kendo window and added view in it*/
var window = uiLayer.extWindow({
elem : $('#popUp'),
actions:["Close"],
modal: true,
animation: false,
resizable: true,
close: that.onClose,
width: "95%",
height: "95%",
minHeight : "35%",
minWidth : "60%",
position:{
top:"1%",
left:"1%",
height:"100%",
width:"100%"
}
});
window.open();
window.content(new PopUpScrollLayoutView(this).el);
/*This is the view in which I have added various templates which contain the div #leftArrow . I have added click event in the events and given it a callback method.
*/
PopUpScrollLayoutView = Marionette.LayoutView.extend({
initialize : function(options){
console.log("Initialising EventContentView");
console.log(options.getAllWidgets());
var allWidgets = options.getAllWidgets();
this.render(allWidgets);
},
events: {
"click #leftArrow":"leftArrowClicked"
},
tagName: "div",
className: "scrollContent",
regions : {
leftArrow : "#leftArrow",
mainArea : "#mainArea",
rightArrow : "#rightArrow",
footer : "#footer"
},
render : function(allWidgets){
this.$el.append(template());
this.$el.append(mainAreaTemplate());
this.$el.append(FooterAreaTemplate());
},
leftArrowClicked:function(e){
console.log("Inside left arrow");
}
});
You can use jQuery for this purpose:
$("#leftArrow").click(leftArrowClicked);

How to run JavaScript after AJAX load?

I am using a vertical dropdown or accordion menu run by some js.
To keep the menu as it is and prevent it from snapping back to it's initial state when some content is loaded I am using a load function.
That seems to work:-)
But the actual content, an image slider, uses some js as well and when loaded via function the js doesn't trigger, because the entire site is not again.
How can I re-trigger the js for that content?
This is the load function:
$(document).ready(function() {
$('ul#menu2 li ul li a').click(function() {
var page = $(this).attr('href');
$('#content').load(page + '.php');
return false;
})
;});
This is the hookup for the slider
$(document).ready(function() {
// Using default configuration
$('#carousel').carouFredSel();
// Using custom configuration
$('#carousel').carouFredSel({
items : 1,
direction : "left",
responsive : false,
auto : {
play : false
},
scroll : {
items : 1,
easing : "swing", // "elastic", "swing"
duration : 500,
},
prev : {
button : "#p",
key : "left"
},
next : {
button : "#n",
key : "right"
},
});});
The js for the slider is called jquery.carouFredSel-6.2.1.js.
I guess this and the hookup need to be re-triggered to make the slider work
when only the content was loaded instead of the entire page.
Can anyone help me with this?
Call $('#carousel').carouFredSel(); from the callback function on the ajax request. Something like this.
$( "#result" ).load( "ajax/test.html", function() {
alert( "Load was performed." );
});
Perhaps
$(document).ready(function() {
$('ul#menu2 li ul li a').click(function(e) {
e.preventDefault(); // Prevents the browser from navigating to wherever the href was leading to
var page = $(this).attr('href');
$('#content').load(page + '.php', function() {
// Loads Carousel only after #content has fully loaded
$('#carousel').carouFredSel({
items : 1,
direction : "left",
responsive : false,
auto : {
play : false
},
scroll : {
items : 1,
easing : "swing", // "elastic", "swing"
duration : 500,
},
prev : {
button : "#p",
key : "left"
},
next : {
button : "#n",
key : "right"
},
});
});
return false;
});
});
They have a section in their documentation for inserting items into the carousel after it has been initialized:
http://docs.dev7studios.com/jquery-plugins/caroufredsel-advanced#insertitem
$(document).ready(function() {
$('ul#menu2 li ul li a').click(function() {
var page = $(this).attr('href');
$('#content').load(page + '.php', function(){
$('#carousel').carouFredSel({
'insertItem' : $('#content') // Or whatever you need to add
});
});
return false;
});
});

How to add a ...loading to my tabbed ajax script

I used a flowplayer tutorial to make some ajax tabbed content but the it doesn't use any kind of a loading indication in between content load. How can I add that to this script? http://pastebin.com/PebcJspn
<script>
$(function() {
$(".feed-tabs ul").tabs("div.feeds > div", {
effect: 'fade',
onBeforeClick: function(event, i) {
// get the pane to be opened
var pane = this.getPanes().eq(i);
// only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
if (pane.is(":empty")) {
// load it with a page specified in the tab's href attribute
pane.load(this.getTabs().eq(i).attr("href"));
}
}
});
});
</script>
You can try add an element with a loading gif before call the method .load() and it will be removed when .load() inserts the html result.
<script>
$(function() {
$(".feed-tabs ul").tabs("div.feeds > div", {
effect: 'fade',
onBeforeClick: function(event, i) {
// get the pane to be opened
var pane = this.getPanes().eq(i);
// only load once. remove the if ( ... ){ } clause if you want the page to be loaded every time
if (pane.is(":empty")) {
//add this
pane.append("<img src='http://mentalized.net/activity-indicators/indicators/ilcu/roller.gif'/>")
// load it with a page specified in the tab's href attribute
pane.load(this.getTabs().eq(i).attr("href"));
}
}
});
});
</script>

Categories

Resources