Ajax loading and previous active scripts - javascript

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

Related

Super Simple Slider not working after AJAX load

I am trying to trigger the ready event after the user clicks on #mail-wrap which loads in another page with AJAX so that sss() can be refired. However, it's not refiring. What am I doing wrong?
jQuery(document).ready(function($) {
function sss() {
$(document).trigger('ready');
$('.slider').sss({
speed: 5000
});
}
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sss();
});
$('.slider').sss({
speed: 5000
});
});
Full relevant code (code is surrounded by document ready and the sss() function is outside of it):
(function($) {
var contactButton = $('#contact-button');
// Load the Contact page
function loadContact() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/contact/ #contact-keebs', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').addClass('contact');
$('#projects-list').removeClass('fadeInUp');
$('#contact-info, #clients').addClass('fadeInUp');
});
// Change the Contact button to 'Projects'
$(contactButton).removeClass('contact-button').addClass('project-button').attr('data-title', 'Projects').css('width', '71px').text('Projects').shuffleLetters();
myIcons.to('work');
// Change the title of the document
$('head').find('title').text('Contact | Keebs');
//Reinitialize SSS
sssInit();
}
// Load the Projects page
function loadProjects() {
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"></span>').insertBefore('#content');
}).load(site.url + '/ #primary', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').removeClass('contact');
$('#contact-info, #clients').removeClass('fadeInUp');
$('#projects-list').addClass('fadeInUp');
TweenLite.to("body.single #project-wrapper", 0.3, {height:0, force3D:true, ease:Power4.easeOut});
});
// Change the Projects button to 'Contact'
$(contactButton).removeClass('project-button').addClass('contact-button').attr('data-title', 'Get in touch').css('width', '96px').text('Get in touch').shuffleLetters();
myIcons.to('mail');
// Change the title of the document
$('head').find('title').text(site.title);
}
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
// Prevent accidental double clicks
if (!$(this).data('isClicked')) {
var link = $(this);
if (!contactButton.hasClass('project-button')) {
var data1 = { contact_page: site.url + '/contact/ #contact-keebs' };
History.pushState(data1, 'Contact | Keebs', site.url + '/contact/');
loadContact();
} else {
var data2 = { home_page_contact: site.url + '/ #primary' };
History.pushState(data2, site.title, site.url + '/');
loadProjects();
}
link.data('isClicked', true);
setTimeout(function() {
link.removeData('isClicked');
}, 500);
}
});
})(jQuery);
It's not clear what your Ajax event does and if you are using sss() bound to the jQuery object defining your own function sss is confusing. Did you really mean to do something like this;
function sssInit() {
jQuery('.slider').sss({
speed: 5000
});
}
jQuery(document).ready(function($) {
sssInit();
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sssInit();
});
});
EDIT: You are using .load() so your sssInit call will need to go in the complete function parameter e.g;
$('#content').fadeOut(50, function() {
$('<span class="loading-icon page-loading-icon"> </span>').insertBefore('#content');
}).load(site.url + '/contact/ #contact-keebs', function() {
$('.page-loading-icon').remove();
$(this).fadeIn(50);
$('body').addClass('contact');
$('#projects-list').removeClass('fadeInUp');
$('#contact-info, #clients').addClass('fadeInUp');
sssInit();
});
ISSUE: The Super Simple Slider hooks up it's events using $(window).load(function() { ... }) adding elements to the DOM after load will not get the event handlers and prevents the slider working.
trying to trigger the ready event after the user clicks on #mail-wrap
which loads in another page with AJAX so that sss() can be refired.
However, it's not refiring. What am I doing wrong?
.ready() already called when $(document).trigger('ready'); called ?
Try utilizing $.holdReady()
// do stuff before `.ready()` event called
$.holdReady(true);
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sss();
// call `.ready()` event by setting `$.holdReady()` to `false`
$.holdReady(false);
});
function sss() {
jQuery('.slider').sss({
speed: 5000
});
}
jQuery(document).ready(sss);
e.g.,
$.holdReady(true);
// User event
$('#mail-wrap').on('click', function(e) {
e.preventDefault();
sss("$.holdReady(true) within `click` event", this);
$.holdReady(false);
});
function sss() {
console.log(arguments[1]); // `#mail-wrap` , `document`
$("body").append("<br>" + arguments[0] + " " + $.now())
}
jQuery(document).ready(function($) {
sss("$.holdReady(false) within $(document).ready()", this)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="mail-wrap">click</div>

Wait for document mousedown to complete before element onclick can start

I have a panel that slides open on an element click called "details" and populates the panel via ajax depending on the data attribute value. I also have it setup that if you close outside that panel, it will close. If the panel is open and the user clicks on a different "details" element, I want the panel to close and open again populated with the data from the new data attribute.
Problem is that the codes checks if the panel is visible and won't load the ajax if it is. How can I change this so the click event knows the mousedown event is completed before it does it's thing?
// SLIDING PANEL
$(".details").on("click", function(e){
e.preventDefault();
var panel = $("#DetailsPanel");
var mkey = $(this).data("masterkey-id");
var _self = $(this);
// fetch data ONLY when panel is hidden...
// otherwise it fetches data when the panel is closing
if (!panel.is(':visible')) {
panel.load("/com/franchise/leads.cfc?method=getLeadDetails", { mkey: mkey }, function(response, status, xhr) {
// if the ajax source wasn't loaded properly
if (status !== "success") {
var msg = "<p>Sorry, but there was an error loading the document.</p>";
panel.html(msg);
};
// this is part of the .load() callback so it fills the panel BEFORE opening it
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().addClass("warning");
});
});
} else {
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().removeClass("warning");
});
};
return false;
});
$(document).on("mousedown", function(){
$("#DetailsPanel").hide("slide", { direction: "right" }, "fast", function(){
//_self.parent().parent().removeClass("warning");
});
});
// don't close panel when clicking inside it
$(document).on("mousedown","#DetailsPanel",function(e){e.stopPropagation();});
$(document).on("click", "#ClosePanel", function(){
$("#DetailsPanel").hide("slide", { direction: "right" }, "fast", function(){
$("#LeadsTable tr").removeClass("warning");
});
});
// END SLIDING PANEL
Setting a timeout worked for me in another context:
onclick="window.setTimeout( function(){ DO YOUR STUFF }, 2);"
This solves many problems of this type.
I'm not totally sure about this but if you use "mouseup" instead "click" could work as you expect. Try it and let me know if I'm wrong.
Ok, so I found this little nugget http://www.gmarwaha.com/blog/2009/06/09/jquery-waiting-for-multiple-animations-to-complete/ and it works pretty good. No issues so far.
Here is the new code
$(".details").on("click", function(e){
e.preventDefault();
var panel = $("#DetailsPanel");
var mkey = $(this).data("masterkey-id");
var _self = $(this);
// fetch data ONLY when panel is hidden...
// otherwise it fetches data when the panel is closing
var wait = setInterval(function() {
if( !$("#DetailsPanel").is(":animated") ) {
clearInterval(wait);
// This piece of code will be executed
// after DetailsPanel is complete.
if (!panel.is(':visible')) {
panel.load("/com/franchise/leads.cfc?method=getLeadDetails", { mkey: mkey }, function(response, status, xhr) {
// if the ajax source wasn't loaded properly
if (status !== "success") {
var msg = "<p>Sorry, but there was an error loading the document.</p>";
panel.html(msg);
};
// this is part of the .load() callback so it fills the panel BEFORE opening it
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().addClass("warning");
});
});
} else {
panel.toggle("slide", { direction: "right" }, "fast", function(){
_self.parent().parent().removeClass("warning");
});
};
}
}, 200);
return false;
});

why this code is not loading pages ajax jquery

Guys What I am trying to do is load a page on navigation click with ajax and put some delay in it loading
when nothing is clicked I want load home page following loading animation with jquery and a delay with PHP code
and if something on nav is clicked I want to load that particular file
but this code don't seem to be working
var res = {
loader: $('<div />', {class: 'loader' } ),
container: $('.content')
};
$(document).ready(function(){
$.ajax({
url: 'templates/delay.php',
beforeSend, function(){
res.container.append(res.loader);
},
success, function(){
res.container.find(res.loader).remove();
$('.content').load('templates/pages/home.php');
}
});
$('ul#nav_a li a').click(function(){
$.ajax({
url: 'templates/delay.php',
beforeSend, function(){
res.container.append(res.loader);
},
success, function(){
res.container.find(res.loader).remove();
var page=$(this).attr('href');
$('.content').load('templates/pages/'+page+'.php');
return false;
});
});
}
});
I will not discuss the code itself, but just improve it.
Try this code and tell me if you get what you want : ( comments inside the js code )
$(document).ready(function(){
$.ajax({
url: 'templates/delay.php',
// old code : beforeSend,
beforeSend: function(){
res.container.append(res.loader);
},
// old code : success,
success: function(){
res.container.find(res.loader).remove();
$('.content').load('templates/pages/home.php');
}
// beforeSend and success are keys with functions as values that's why we use ":" and not ","
// the "," comma is used to separate ajax settings
});
$('ul#nav_a li a').click(function(){
var page = $(this).attr('href');
$.ajax({
url: 'templates/delay.php',
// old code : beforeSend,
beforeSend: function(){
res.container.append(res.loader);
},
// old code : success,
success: function(){
res.container.find(res.loader).remove();
$('.content').load('templates/pages/'+page+'.php');
// old code
// return false;
// });
// we close our ajax.success function
}
})
// old code
// }
// return false is used to prevent browser to run the a href that's why we use it in the a.click function and not inside the ajax block
return false;
})
})
var res = {
loader: $('<div />', {class: 'loader' } ),
container: $('.content')
};
$(document).ready(function(){
res.container.append(res.loader);
$('.content').load( "templates/pages/home.php", function() {
res.container.find(res.loader).remove();
});
$('ul#nav_a li a').click(function(){
var page=$(this).attr('href');
$('.content').load( 'templates/pages/'+page+'.php', function() {
res.container.find(res.loader).remove();
});
});
}
});
Just copy and paste it.

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

Div moves out of window when resized

Whenever i resize the browser, the div moves out of window. I use jquery scroll to plugin for navigating through divs. But when i resize the #home div it works fine, but when i resize other divs, it gets out of window.
Please help me out, here is the link to the website.
Here is the code i used,
$(document).ready(function()
{
$("#bg-home").backstretch("images/Bg-home3.jpg");
var images = ['1.jpg', '2.jpg','3.jpg'];
$("#container").backstretch('images/' + images[Math.floor(Math.random() * images.length)]);
$( "#draggable" ).draggable({
drag: function() {
$(".scrolldown span").css("color","lightgreen").html("Drop");
},
stop: function() {
$(".scrolldown span").css("color","white").html("Drag");
},axis: "x",containment:"#menu",scroll: false//,grid: [ 159,0 ]
});
$(".content,.content1").droppable({drop: function() {
var $url = $(this);
document.title = $url.attr('alt');
$('html, body').scrollTo($url.attr('id'),500,"easeInOutExpo");
//event.preventDefault();
}});
$("#welcome").effect("slide",3000);
$("#welcome").click(function()
{
$("#welcome").animate({left: "-1000px"},"easeInOutBounce");
$(".about_w").animate({left: "100px"},"easeInOutBounce");
$(".about_w").delay(4000).animate({left: "-800px"});
$("#welcome").delay(4500).animate({left: "100px"});
});
$('#menu a').bind('click',function(event){
var $url = $(this);
document.title = $url.attr('alt');
$('html, body').scrollTo($url.attr('href'),500,"easeInOutExpo");
event.preventDefault();
});
$("#about .text p").vertiscroll({ width:6, color:'#f07','cover': 200,'areacursor': 'pointer' });
$('.side_container').slimScroll({
height:"88%",
color: '#fff',
start: $('.side_container'),
alwaysVisible: false
});
$('#container_wrap_metro').slimScroll({
height:"400px",
color: '#fff',
railVisible: false,
alwaysVisible: false
});
$(".menu nav").click(function(){
$url = $(this);
$(".text p").load($url.attr('id'));
});
function loading_show()
{
$('#loading').html("<p style='color:white;'>Loading</p><br><img src='images/loading.gif'/>").fadeIn('fast');
}
function loading_hide()
{
$('#loading').fadeOut();
}
//Status
function loadData(page)
{
loading_show();
$("#container_wrap_metro").html("");
$.ajax({
url: "load_data.php",
type: "post",
data: "page="+page,
success: function(data){
loading_hide();
$("#container_wrap_metro").html(data);
},
error:function(){
alert("failure");
$("#container_wrap_metro").html('Unable to process request!');
}
});
}
function loads(page)
{
$.ajax({
url: "load_10.php",
type: "post",
data: "page="+page,
success: function(data){
$(".side_container").html(data);
},
error:function(){
alert("failure");
$(".side_container").html('Unable to process request!');
}
});
}
loads(1);
//Search
$("#result").keyup(function(){
$(".side_container").html('<center><i>Fetching...</i></center>')
var q = $(this).val();
$.get("results.php?q="+q, function(data){
if(q){
$(".side_container").html(data);
}
else {
loads(1);
}
});
});
});
Try editing the following lines:
$("#welcome").animate({left: "-1000px"},"easeInOutBounce");
$(".about_w").animate({left: "100px"},"easeInOutBounce");
$(".about_w").delay(4000).animate({left: "-800px"});
$("#welcome").delay(4500).animate({left: "100px"});
And:
height:"400px",
The earlier response is right. When it comes to responsive web design, use em or % when setting the sizes. You can use 100% instead or 40 em. You can change the values until you get the desired output.
For this you need responsive designs and for that you need to give widths as in "%" everywhere But in your script you are using left:..px like that....Its creating the problem.So First thing better to give them responsively or second thing replace it with the responsive one..
Try this LINK

Categories

Resources