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.
Related
I have created two user-defined functions within the "head" section of an HTML page and I am calling them with a script just before the closing "body" tag. The trouble is that the second function is not working, unless I include an "alert" statement in the first function (which halts the execution until I dismiss the alert).
I am guessing it is caused by the first function not actually finishing completely before the second one starts and by having my alert statement it gives the first function time to finish.
Function one is to build a list of images in DIV tags.
Function two implements FlexSlider to initiate a slideshow of the images.
Calling the below as it is will render a page with all images shown. If I uncomment the alert box and run it again, the screen is rendered with my images, I dismiss the alert box, and then FlexSlider kicks in and starts the slideshow.
Here are the two functions defined in the "head" section.
<script type="text/javascript">
var buildslider = function () {
$.ajax({
type: "GET",
url: "/myImages/homepageslider/PhotoGallery.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('img').each(function() {
var location = '/myImages/homepageslider/';
var url = $(this).attr('src');
var alt = $(this).attr('alt');
$('<div class="slide-group"></div>').html('<img src="'+location+''+url+'" alt="'+alt+'"/>').appendTo('.slides');
});
}
});
//alert("buildslider finished");
};
var runslider = function() {
$('.flexslider').flexslider({
selector: '.slides > .slide-group',
controlNav: false,
directionNav: false
});
};
</script>
And here is the code near the closing "body" tag.
<script>
$(document).ready(function() {
buildslider();
runslider();
});
</script>
What am I doing wrong and how do I correct this so it can be done properly?
Thank you in advance.
David.
Return the ajax() returned object from the first function. This is a jQuery "promise" object which will then expose done and fail methods. These methods take a function, so you can just insert your second function into done. See example below:
<script type="text/javascript">
var buildslider = function () {
return $.ajax({
type: "GET",
url: "/myImages/homepageslider/PhotoGallery.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('img').each(function() {
var location = '/myImages/homepageslider/';
var url = $(this).attr('src');
var alt = $(this).attr('alt');
$('<div class="slide-group"></div>').html('<img src="'+location+''+url+'" alt="'+alt+'"/>').appendTo('.slides');
});
}
});
};
var runslider = function() {
$('.flexslider').flexslider({
selector: '.slides > .slide-group',
controlNav: false,
directionNav: false
});
};
</script>
Then run with:
<script>
$(document).ready(function() {
buildslider().done(runslider);
});
</script>
It also makes it easier to handle failures in a more general way:
<script>
$(document).ready(function() {
buildslider().done(runslider).fail(function(){
alert("#%&£ happens!");
});
});
</script>
Using promises is far more flexible than using callbacks, and supports multiple done() functions, so is now the preferred way to do this.
Note: A simpler shortcut for DOM ready is $(function(){ your code here }); or if you want it to have a locally scoped $ use jQuery(function($){ your code here }); which acts as both a DOM ready handler and provides a locally scoped $ to avoid clashes (e.g. with other plugins).
<script type="text/javascript">
var buildslider = function () {
$.ajax({
type: "GET",
url: "/myImages/homepageslider/PhotoGallery.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('img').each(function() {
var location = '/myImages/homepageslider/';
var url = $(this).attr('src');
var alt = $(this).attr('alt');
$('<div class="slide-group"></div>').html('<img src="'+location+''+url+'" alt="'+alt+'"/>').appendTo('.slides');
});
}
});
//alert("buildslider finished");
};
var runslider = function() {
$('.flexslider').flexslider({
selector: '.slides > .slide-group',
controlNav: false,
directionNav: false
});
};
$( document ).ajaxComplete(function( event, xhr, settings ) {
if ( settings.url === "/myImages/homepageslider/PhotoGallery.xml" ) {
runslider();
}
});
</script>
Now Just call the buildslider() only no need to call the runslider() in your document.ready..
try something like this
var buildslider = function () {
$.ajax({
type: "GET",
url: "/myImages/homepageslider/PhotoGallery.xml",
dataType: "xml",
success: function(xml) {
$(xml).find('img').each(function() {
var location = '/myImages/homepageslider/';
var url = $(this).attr('src');
var alt = $(this).attr('alt');
$('<div class="slide-group"></div>').html('<img src="'+location+''+url+'" alt="'+alt+'"/>').appendTo('.slides');
$('.flexslider').flexslider({
selector: '.slides > .slide-group',
controlNav: false,
directionNav: false
});
});
}
});
};
final script block
$(document).ready(function() {
buildslider();
});
Note : execute slider code after ajax is successfully completed.
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) {}
The code which changes the active class to the currently clicked pagination class. Removing it works but adding the new class doesn't work.
http://jsfiddle.net/spadez/qKyNL/35/
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
url: "/ajax_json_echo/",
type: "GET",
dataType: "json",
timeout: 5000,
beforeSend: function () {
$('#content').fadeTo(500, 0.5);
},
success: function (data, textStatus) {
// TO DO: Load in new content
$('html, body').animate({
scrollTop: '0px'
}, 300);
// TO DO: Change URL
$('#pagination li.active').removeClass("active");
$(this).parent().addClass("active");
},
error: function (x, t, m) {
if (t === "timeout") {
alert("Request timeout");
} else {
alert('Request error');
}
},
complete: function () {
$('#content').fadeTo(500, 1);
}
});
});
Can anyone please tell me where I am going wrong?
The problem is that this in the success callback isn't your element.
You may do this :
$('a').click(function(event){
var element = this; // <= save the clicked element in a variable
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
...
success: function (data, textStatus) {
...
$('#pagination li.active').removeClass("active");
$(element).parent().addClass("active"); // <= use it
},
...
});
});
This this in ajax callback isn't what you expect it to be. Add this to your ajax parameters:
context: this,
No need to build custom object saving system and making code more messy, as jQuery already has this functionality.
Edit: In this case it should look like:
$('a').click(function(event){
event.preventDefault();
var number = $(this).attr('href');
$.ajax({
context: this,
url: "/ajax_json_echo/",
...
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
Why is my jQuery having an error when I put this line in?
<script type="text/javascript">
$(function(){
$(".arrowbutton").click(function(){
id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
$(this).hide();
}
});
return false;
});
});
</script>
When I remove $(this).hide(); it's fine. But, I want it to hide!!!
Because this doesn't refer to you arrow button, but it refers to the AJAX Request object.
$(".arrowbutton").click(function(){
var that = this;
var id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
$(that).hide();
}
});
return false;
});
jQuery calls your success function more or less like this:
handleSuccess: function( s, xhr, status, data ) {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( s.context, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
jQuery.triggerGlobal( s, "ajaxSuccess", [xhr, s] );
}
},
The first argument of the call method sets the this keyword in the success function to s.context
Because $(this) doesn't return what you think it does in the success callback. You could use a closure:
$(function(){
$('.arrowbutton').click(function(){
var button = $(this);
$.ajax({
type: 'POST',
url: '/upvote',
data: { id: this.rel },
beforeSend:function() {
},
success:function(html) {
button.hide();
}
});
return false;
});
});
$(this) is referring to the Ajax request, not the surrounding button.
Try using a closure like so:
<script type="text/javascript">
$(function(){
$(".arrowbutton").click(function(){
var arrowbutton = $(this);
id = $(this).attr('rel');
$.ajax({
type:"POST",
url:"/upvote",
data:{'id':id},
beforeSend:function() {
},
success:function(html){
arrowbutton.hide();
}
});
return false;
});
});
</script>
"this" does mean this in all situations, because you are inside a new function that is the new this.
Check this tutorial out to learn all the different ways you can deal with it:
http://justin.harmonize.fm/index.php/2009/09/an-introduction-to-javascripts-this/