How to toggle class on click to animate an AJAX page transition - javascript

I'm building a simple practice project where each page is loaded via AJAX and would present a fadeIn, fadeOut transition using CSS animation opacity.
The problem is that the addClass and removeClass are not being executed.
JS (JQuery)
$(document).ready(function() {
// $('.mainSplash').css('height',$(window).height() - 60);
$(".aboutBtn").click(function(e) {
e.preventDefault();
var pageTitle = $(this).text();
var pageUrl = $(this).attr('href');
changePage(pageUrl, true, pageTitle);
}); // click
function changePage(url, bool, pageTitle){
$('#wrapper').addClass('animate');
loadContent(url, bool, pageTitle);
}
function loadContent(url, bool, pageTitle){
$.ajax({
url: './' + url,
type: 'get',
contentType: 'html',
success: function(data){
// load content
$('#content').html(data);
// Change url
if(url != window.location){
window.history.pushState({path: url}, pageTitle, url);
}
},
complete: function(){
$('#wrapper').removeClass('animate');
}
});
}
});
Here's the full Codepen project example

If you are having issues with the animation being removed before it finishes and thus it is not visible. You would want to listen for when the animation event ends, and remove the class in the callback there (if it really needs to be removed) instead of removing it when the page is done loading.

Related

JS script doesn't work when i click back on site

i create a nav on my site. Navigation works good but when i back on the main site all script from js file doesn't work. Script for my nav:
var default_content="";
$(document).ready(function(){
//Ajax navigate
checkURL();
$('footer a').click(function(){
checkURL(this.hash);
});
default_content = $('#login_box').html();
setInterval("checkURL()",250);
.........
Methods:
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#login_box').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$.ajax({
type: "POST",
url: "include/help4meApi.php",
data: 'page='+url+'&tag=navigation',
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#login_box').html(msg);
}
}
});
}
Problem is when i back to the main site scripts doesn't work.
the issue comes from here $('#login_box').html(default_content);. When u calle the .html() the event binded within the element will be cleaned.
When you backspace, back to the main page, the event handler is already not there, so you have to register it again
//For show and hide register values
$("#registerInputsBtn").click(function(){
$(".register_information").hide(1000);
$(".register_values").show(1000);
$("#firstname").focus();
});
register again on the piece of code that you assign the content to #login_box. For example the quick fix:
if(hash==""){
$('#login_box').html(default_content);
$("#registerInputsBtn").click(function(){
$(".register_information").hide(1000);
$(".register_values").show(1000);
$("#firstname").focus();
});
}
but here the codes are not DRY :( rearrange the flow on how the page load and the register the event in the correct flow is recommended.

Using Ajax to pull image into div, how do I add height to div before call, then remove it after image is loaded?

I'm using a form and Ajax to pull an image dynamically to replace another image in the .results div. My first try worked, but the page jumped up when the image was removed and jumped back down when the image was loaded. I figured I could add style attribute to give the div a height, then after the image is loaded remove the style attribute. What I have below works 70% of the time, the other 30% the stye attribute is being removed before the image is loaded and the page jump is still there. Is there a way to remove the style attribute only after the image is completely loaded? Or set a delay or something? I'm a JS and Ajax noob, so please be gentle.
(function($){
$(function(){
var $form = $('#customize'), // Search form
$target = $('.results'), // Results container
rp = 'product_search/results_only_ajax'; // Template for results only
// Function to execute on success
var success = function(data, status, xhr) {
$target.html(data);
$('.loading').html('<p></p>');
// Remove style
$('.results').removeAttr("style");
};
// Hijack the form on submit
$form.submit(function(){
// Tell target we're loading
$('.loading').html('<p>Loading...</p>');
// get height of container, and set height
currentHeight = $('.results').outerHeight();
$('.results').css("height", currentHeight);
// Add custom result page to data
var data = $form.serialize()
+ '&result_page=' + rp;
// Perform the ajax call
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: data,
success: success,
dataType: 'html'
});
// Don't submit the form afterwards
return false;
});
});
})(jQuery);
EDIT:
// Function to execute on success
var success = function(data, status, xhr) {
$target.html(data);
$('.loading').html('<p></p>');
// $('.results').removeAttr("style");
setTimeout(function () {
$('.results').removeAttr("style");
}, 1000);
};
I added a Timeout which is working ok for now.

How to slow page loading inside to div?

I am using jquery to fadein div which i animate to get bigger and then i load php file in it using ajax. Problem is that ajax loads php file before div is visible and animated big enough. Therefore php page shows onscreen and after that div loads under it. How can i slow down php page loading or make it visible after div is visible? Toppi and links are variables. Toppi contains position of div and links php page name.
Here is the code i use:
$("#riv1").css("top", + toppi);
$("#riv1").fadeIn();
$("#riv1").animate({height:'600px',opacity:'0.4'},"fast");
$("#riv1").animate({width:'850px',opacity:'0.8'},"fast");
$("#riv1").animate({opacity:'1.0'}, 500);
if (links != '') {
$.ajax({
async:false,
url: links,
cache: false
}).done(function( html ) {
$("#riv1").html(html);
});
}
I have tried
$("#riv1").delay(2000).html(html);
but this does not help.
Try to put the ajax code in a callback function of fadeIn():
$("#riv1").css("top", + toppi);
$("#riv1").fadeIn("slow",function(){
if (links != '') {
$.ajax({
async:false,
url: links,
cache: false
}).done(function( html ) {
$("#riv1").html(html);
});
}
});
$("#riv1").animate({height:'600px',opacity:'0.4'},"fast");
$("#riv1").animate({width:'850px',opacity:'0.8'},"fast");
$("#riv1").animate({opacity:'1.0'}, 500);
the ajax function will be called only when the fadeIn has been finished.
$("#riv1").css("top", + toppi);
$("#riv1").fadeIn();
$("#riv1").animate({height:'600px',opacity:'0.4'},"fast");
$("#riv1").animate({width:'850px',opacity:'0.8'},"fast");
$("#riv1").animate({opacity:'1.0'}, 500,function(){
//calling ajax after animation completed
if (links != '') {
$.ajax({
async:false,
url: links,
cache: false
}).done(function( html ) {
$("#riv1").html(html);
});
}
});
try making a ajax call once the final animation is completed
Happy Coding :)
You can show the loading image before jquery ajax request by using the function
beforeSend and can hide the loading image on success like below
$.ajax({
beforeSend:function(){
//you logic to add the loading image inside the div
}
async:false,
url: links,
cache: false
}).done(function( html ) {
//Hide the images or replace the div with new content
$("#riv1").html(html);
});

Loading Spinner Image too fast at start of Function

I have a function that displays contents of a posts when clicked on. I want the loading spinner to display and delay for few sections before the post content appears. The issue here is when I click on each post, the spinner appears for maybe 1ms and in some cases it disappears long before the content appears.
function showPost(id) {
setTimeout(function() {$('#loader').show();},1);
$('#pcontent').empty();
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
var $postcon = $('<div/>').append([$("<h3>", {html: data.post.title}),$("<p>", {html: data.post.content})]);
$postcon.appendTo('#pcontent');
});
}
Spinner HTML:
<div id='loader'><img src="css/images/loader.gif"/></div>
Try this:
function showPost(id) {
$('#loader').show();
$('#pcontent').empty();
$.ajax({
url: 'http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?',
dataType: 'json',
success: function (data) {
var $postcon = $('<div/>').append([$("<h3>", {
html: data.post.title
}), $("<p>", {
html: data.post.content
})]);
$postcon.appendTo('#pcontent');
$('#loader').hide();
}
});
}
gif image always behave differently on every device..basically it depends upon device's processing speed. so better option is to use image sprites and animate it with javascript..
In your case at page load there is nothing processing..but as page starts to load device's processor cant handle the load and as a result your gif image gets slower
It seems from your last commented line that you are using a timeout to hide the loader. Instead You should handle the hiding inside the callback function of your ajax request, so that loader hides after request is completed, not after a fixed amount of time:
function showPost(id) {
$('#loader').show();
$('#pcontent').empty();
$.getJSON('http://howtodeployit.com/category/daily-devotion/?json=get_post&post_id=' + id + '&callback=?', function(data) {
$('#loader').hide();
var $postcon = $('<div/>').append([$("<h3>", {html: data.post.title}),$("<p>", {html: data.post.content})]);
$postcon.appendTo('#pcontent');
});
}

optimizing colorbox and adding extra jquery

I have two problems
I am trying to open a jQuery colorbox and it is very slow. The reason is I am trying to get html content from a different page (I cannot use iframe because I just need a part of this page). The following code works but it takes time after the button is clicked:
$(document).ready(function() {
$(".cart-link a").click(function(event) {
$(this).colorbox.close();
});
$(".rest-menuitem a").click(function(event) {
event.preventDefault();
var result = null;
var sURL = $(this).attr("href");
$.colorbox({
html: function() {
$.ajax({
url: sURL,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
}
});
return $(result).find('.product');
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
});
});
I want to know if there is a alternative way to do it. I dont mind if the colorbox popup and then takes time to load the content. The above version can be fount at this url (http://delivery3.water-7.com/index.php/restaurants/manufacturers/3/Barcelona-Restaurant-&-Winebar/products).
I am also trying to close the colorbox when a user clicks on add to cart. But some reason it is not triggered. $(".cart-link a").click is not triggered when I click on add to cart. Is there a special way to add jquery to colorbox content?
Try this instead:
$(".rest-menuitem a").colorbox({
href: function(){
return $(this).attr('href') + ' .products';
},
width: '650px',
height: '10px',
onComplete: function() {
$(this).colorbox.resize();
}
});
ColorBox uses jQuery's load() method for it's ajax handling, so you just need to add the desired selector to the link's href.
For your question 2 can you try this ?
$(document).ready(function() {
$(".cart-link a").live('click',function(event) {
$(this).colorbox.close();
});
});
For your question 1..it will be slow since you are fetching it from different page.Use a different logic for that
For your question no 1
$('selector').colorbox({onLoad: function() { /*Intially load a empty color box with only <div id="contenttoload"></div> (No other html content */
$.ajax({
url :'Your url',
data : {}, //data to send if any
type : "POST" //or get
success:function(data){ /*data means the stuff you want to show in color box which you must return from the other page*/
$('#contenttoload').html(data); //data should be well formatted i mean add your css,classes etc from the server itself */
}
});
}});

Categories

Resources