How to run JavaScript after AJAX load? - javascript

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;
});
});

Related

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.

Load html with ajax and delegate on success to function

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

Ajax loading and previous active scripts

I call a loading function for loading content into my #content div.
All work but my problem is this div contains sometimes content that needs a script to run.
(here MIXITUP)
For now, I call ( callback function ) the function who runs mixitup after loading (ajax) but when I load content more than one time, mixitup seems to be a little lost, the filters btn lost active class.
Here's my code for my file AJAX.php:
$(function() {
// historique
$(window).bind('popstate', function() {
console.log( "popstate event" );
var url = window.location;
var hash = url.href.substring(url.href.lastIndexOf('/') + 1);
$('#content').load( url + ' #content');
});
// hide loading
$('#loading').hide();
// menu action link click
$('.menu a').click(function(e) {
e.preventDefault();
$('#loading').slideDown(500);
$("html, body").animate({ scrollTop: $('#loading').offset().top }, 20);
$('.menu li').removeClass('active');
$(this).parent().addClass('active');
var lien = $(this).attr('href');
$('#content').fadeOut(500, function() {
$('#content').load( lien + ' #content> *', function () {
$('#content').fadeIn(500, function() {
$('#loading').slideUp();
history.pushState(null, null, lien);
});
});
});
});
});
And here is my.js
function mixitNow() {
$('.mixit').mixItUp({
load: {
filter: 'all'
},
controls: {
toggleFilterButtons: false,
toggleLogic: 'or',
live: true,
},
callbacks: {
onMixEnd: function(state) {
$("body").getNiceScroll().resize();
}
}
});
$( "a.toggle" ).click(function() {
$(".linkto a.toggle[data-target="+$(this).attr('data-target')+"]").toggleClass( "active" );
// Trigger the NiceScroll to resize
$("body").getNiceScroll().resize();
});
$('.navmenu').niceScroll({cursorcolor: "#84dbff", cursorborder: "none", cursorwidth: "4px", cursorborderradius: "0", scrollspeed: "100"});
$("body").niceScroll({cursorcolor: "#22ABDE", cursorborder: "1px solid #fff", cursorborderradius: "0", scrollspeed: "100"});
};
$(document).ready(function() {
mixitNow(); //works
console.log( "doc ready call 2 mixit" );
});
$(document).ajaxSuccess(function() {
console.log( "ajaxSuccess" );
mixitNow(); //works
});
instead of .load() you could use $.ajax and make use of the success handler
$.ajax({
url: url,
type: 'GET',
success:function(response){
// check response and
if(xyz){
mixItUp()
}else {
// else no mixin
}
}
})
You must delete the instance of MixItUp from the memory before your new ajax call, otherwise further instantiations on the same element will be blocked. Call this before making the ajax call.
try {
$('.mixit').mixItUp('destroy');
}catch(x) {}

jQuery : load a plugin using on function

I'm using jQuery and Tooltipster (showing tooltips when going hover user names), which are working great except for one situation : when I first go hover a user name, it does not show up.
<div class="user">Firstname Lastname</div>
Here is my jQuery code :
$(document).ready(function() {
$(document).on('mouseover', '.user', function() {
// Tooltip for EC user
$('.evac_user').tooltipster({
animation : 'fade',
delay : 0,
content : 'Loading...',
functionBefore : function(origin, continueTooltip) {
continueTooltip();
// next, we want to check if our data has already been cached
if (origin.data('ajax') !== 'cached') {
$.ajax({
type : 'GET',
url : "/myfunction",
success : function(data) {
// update our tooltip content with our returned data and cache it
origin.tooltipster('update', data).data('ajax', 'cached');
}
});
}
}
});
});
});
$('.user').on('mouseover', function(){

Filterable Portfolio Hashtag

I'm working with a filterable Portfolio. I've got a little problem with the links to filter the portfolio.
When I click on the buttons, it filters the portfolio correctly, but after that it connects automatically to the a site like xy.com/#myfilter and trying to open it.
Maybe you have an idea how to disable this?
LINK SAMPLE:
Design
THE JS-FILE IS THE FOLLOWING:
(function($) {
$.fn.filterable = function(settings) {
settings = $.extend({
useHash : true,
animationSpeed : 500,
show : { width: 'show', opacity: 'show' },
hide : { width: 'hide', opacity: 'hide' },
useTags : true,
tagSelector : '#portfolio-filter a',
selectedTagClass : 'current',
allTag : 'all'
}, settings);
return $(this).each(function(){
/* FILTER: select a tag and filter */
$(this).bind("filter", function( e, tagToShow ){
if(settings.useTags){
$(settings.tagSelector)
.removeClass(settings.selectedTagClass);
$(settings.tagSelector + '[href=' + tagToShow + ']')
.addClass(settings.selectedTagClass);
}
$(this).trigger("filterportfolio", [ tagToShow.substr(1) ]);
});
/* FILTERPORTFOLIO: pass in a class to show, all others will be hidden */
$(this).bind("filterportfolio", function( e, classToShow ){
if(classToShow == settings.allTag){
$(this).trigger("show");
}else{
$(this).trigger("show", [ '.' + classToShow ] );
$(this).trigger("hide", [ ':not(.' + classToShow + ')' ] );
}
if(settings.useHash){
location.hash = '#' + classToShow;
}
});
/* SHOW: show a single class*/
$(this).bind("show", function( e, selectorToShow ){
$(this)
.children(selectorToShow)
.animate(settings.show, settings.animationSpeed);
});
/* SHOW: hide a single class*/
$(this).bind("hide", function( e, selectorToHide ){
$(this)
.children(selectorToHide)
.animate(settings.hide, settings.animationSpeed);
});
/* ============ Check URL Hash ====================*/
if(settings.useHash){
if(location.hash != '') {
$(this).trigger("filter", [ location.hash ]);
}else{
$(this).trigger("filter", [ '#' + settings.allTag ]);
}
/* ============ Setup Tags ====================*/
if(settings.useTags){
$(settings.tagSelector).click(function(){
$('#portfolio-list').trigger("filter", [ $(this).attr('href') ]);
$(settings.tagSelector).removeClass('current');
$(this).addClass('current');
});
}
});
}
})(jQuery);
$(document).ready(function(){
$('#portfolio-list').filterable();
});
Could it also be, that I have a problem with my search friendly URLS?
Thanks a lot for every help.
Best regards.
You need to make some adjustments to the click event:
At your current click function:
$(settings.tagSelector).click(function(){
$('#portfolio-list').trigger("filter", [ $(this).attr('href') ]);
$(settings.tagSelector).removeClass('current');
$(this).addClass('current');
});
Change it to:
$(settings.tagSelector).click(function(event){
$('#portfolio-list').trigger("filter", [ $(this).attr('href') ]);
$(settings.tagSelector).removeClass('current');
$(this).addClass('current');
// push the hash into the url
location.hash = $(this).attr('href');
// stop the regular href
event.preventDefault();
});
This allows you to place the hash value into the URL, but prevent the browser from actually reloading the page with that hash when the user clicks the link!
Read more about it:
event.preventDefault() | location.hash

Categories

Resources