Loader auto-fades in (jQuery/javascript/Bootstrap) - javascript

I'm probably an idiot, but I can't find where's problem.
There is a "Suggest a word" button at the bottom of this page.
After filling out the form and clicking on send a loader shows up, however, it doesn't disappear when ajax finishes (it fades out and fades in unexpectedly).
I have no idea why it fades in again and I can't find the reason behind this.
Here is the most important piece of code (I hope so).
$('#suggestQuestionModal').on('show.bs.modal', function (e) {
var currFormGroup = 0;
var maxFormGroups = 4;
//while(currFormGroup < maxFormGroups) {
$('#suggestionSend').click(function() {
if (validator.form()) {
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestLoading").fadeIn('slow');
$("#suggestionSend").attr('disabled', true);
});
if ($("#suggest-email").val() != '' && $("#suggest-want-mail").prop('checked'))
email = $("#suggest-email").val();
else
email = 'NULL';
word = $("#suggest-word").val();
pack = $("#suggest-pack").val();
lang = $("#suggest-lang").val();
var request = $.ajax({
url: "/ajax/suggestQuestion.php",
method: "POST",
data: {word: word, pack: pack, lang: lang, email: email}
});
$("#suggestQuestionModal .form-group").hide().children(':input').val('');
$('#suggestQuestionModal .form-group > :checkbox').prop('checked', false);
request.error(function(xhr,status,error) {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-danger').html("<?=$lg['suggest_error']?> <a class=\"alert-link reset-suggestion\"><br><?=$lg['try_again']?></a>").fadeIn('slow');
setTimeout(function() {
$('#suggestQuestionModal').modal('hide');
}, 10000);
});
});
request.success(function(result, status, xhr) {
if (result == "OK") {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-success').html("<?=$lg['suggest_success']?> <a class=\"alert-link reset-suggestion\"><br><?=$lg['suggest_add_another']?></a>").fadeIn('slow');
});
}
else {
$("#suggestLoading").fadeOut('slow', function() {
$("#suggestQuestionModal .modal-body div.alert").addClass('alert-danger').html("<?=$lg['suggest_error_info']?> "+result+" <a class=\"alert-link reset-suggestion\"><br><?=$lg['try_again']?></a>").fadeIn('slow');
});
}
});
$("#suggestQuestionModal .modal-body").on('click', '.reset-suggestion', function() {
resetSuggestionModal();
});
}
});
showGroups();
function showGroups() {
$('#suggestQuestionModal .form-group > :input').on("change", function() {
if ($(this).parent().index() == currFormGroup) {
if (currFormGroup < maxFormGroups) {
currFormGroup++;
$('#suggestQuestionModal .form-group:eq('+currFormGroup+')').fadeIn('slow');
if (currFormGroup == 4) {
$('#suggest-email').rules('add', {required: true, email: true});
}
}
}
});
}
$('#suggestQuestionModal .form-group:eq(3) > :input').change(function() {
/*if ($(this).checked && $('#suggestQuestionModal .form-group:eq(4)').css('display') == 'none') {
alert("SHOW IT!");
$('#suggestQuestionModal .form-group:eq(4)').fadeIn('slow');
currFormGroup++;
alert(currFormGroup);
} */
if (!$(this).prop('checked') && $('#suggestQuestionModal .form-group:eq(4)').css('display') == 'block') {
$('#suggestQuestionModal .form-group:eq(4)').fadeOut('slow').children(':input').val('');
currFormGroup = currFormGroup - 1;
$('#suggest-email').rules('add', {required: false, email: false});
}
});
//}
AFAIK (I tried to debug it with alerts) something bad happens right before $('#suggestionSend').click closing bracket.
BTW. Yes, I know the code is really a piece of mess.
Any help - greatly appreciated.

You can try using Ajax done instead
request.done(function( result) {
$( "#element" ).fadeout() ;
});

I've got no idea of what happened.
Tried several times - no luck.
Then I decided to try with hide() and show() - still no luck.
After I changed it back to fadeIn() and fadeOut() - it suddenly works.
Some serious magic is going on...
EDIT: I've found it. I forgot that I moved fadeIn function outside of .form-group fadeOut, so from this:
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestLoading").fadeIn('fast');
$("#suggestionSend").attr('disabled', true);
});
I got this:
$("#suggestQuestionModal .form-group").fadeOut('slow', function() {
$("#suggestionSend").attr('disabled', true);
});
$("#suggestLoading").fadeIn('fast');
Previously, fadeIn function was being called 4 times (because of those .form-group elements).
Now it works great :)

Related

How do I keep my error message from flashing twice?

I have a little error mechanism that displays an error by fading it in, waiting a few secs, and fading out. It works if I let it run through the whole process, but if I quickly click on a lot of things that show errors, here is where it goes wrong.
The error message shows, then fades in and out. So I tried solving this by adding a var called is_fading to check the current status of the error, but it didnt work. Here is my code:
errors: {
is_fading: false,
render: function (msg) {
GroupManagement.error.html(msg);
if (GroupManagement.errors.is_fading == true)
{
GroupManagement.error.delay(1500).fadeOut();
GroupManagement.errors.is_fading = false;
return;
}
else
{
GroupManagement.error.fadeIn('normal', function()
{
GroupManagement.errors.is_fading = true;
$(this).delay(1500).fadeOut();
GroupManagement.errors.is_fading = false;
});
}
}
},
As mentioned before, this is just what I thought would solve the problem, but doesn't. Does anyone know why?
Credit goes to #Mehdi, the answer is:
errors: {
is_fading: false,
render: function (msg) {
GroupManagement.error.html(msg);
if (GroupManagement.errors.is_fading == true)
{
GroupManagement.error.delay(1500).fadeOut('', function () {
GroupManagement.errors.is_fading = false;
});
return;
}
else
{
GroupManagement.error.fadeIn('normal', function()
{
GroupManagement.errors.is_fading = true;
$(this).delay(1500).fadeOut('', function () {
GroupManagement.errors.is_fading = false;
});
});
}
}
},

Button for a modal form not displaying or functioning

I've already been on here for a similar question, but moved this interaction in my code and have the same issue... but I believe with a different cause.
I have a page that has an "Email Me" button at the bottom of it:
http://danux.me/
When you click the "Email Me" button, an overlay should appear and with an email form in the middle of it. I had it working on a test page, and then moved all the items over to my index.html and it's not working.
My goal right now is just to get the overlay and form to pop up in the page.
I checked my paths to make sure they were right and I think they are, but I don't know how to parse or inspect php with Google's emulator to see where something might not be working.
I checked my index.html head link to the css, the javascript at the end of my index.html and then in the contact.js, there's a GET link that points down to the php file.
Also, I am unsure in the HTML how to "call"(?) the php or jquery on that button and if that's the issue. It worked before as is and I am assuming that class="contact" is what's making all this work? I don't know. I'd be interested to know how a class triggers a javascript file.
I also got ripped earlier for not having PHP, but I didn't know until today that can't be viewed, so I'll put it below. I'm not sure if it's helpful or not.
jQuery(function ($) {
var contact = {
message: null,
init: function () {
$('#contact-form input.contact, #contact-form a.contact').click(function (e) {
e.preventDefault();
// load the contact form using ajax
$.get("contact/data/contact.php", function(data){
// create a modal dialog with the data
$(data).modal({
closeHTML: "<a href='#' title='Close' class='modal-close'>x</a>",
position: ["15%",],
overlayId: 'contact-overlay',
containerId: 'contact-container',
onOpen: contact.open,
onShow: contact.show,
onClose: contact.close
});
});
});
},
open: function (dialog) {
// dynamically determine height
var h = 280;
if ($('#contact-subject').length) {
h += 26;
}
if ($('#contact-cc').length) {
h += 22;
}
var title = $('#contact-container .contact-title').html();
$('#contact-container .contact-title').html('Loading...');
dialog.overlay.fadeIn(200, function () {
dialog.container.fadeIn(200, function () {
dialog.data.fadeIn(200, function () {
$('#contact-container .contact-content').animate({
height: h
}, function () {
$('#contact-container .contact-title').html(title);
$('#contact-container form').fadeIn(200, function () {
$('#contact-container #contact-name').focus();
$('#contact-container .contact-cc').click(function () {
var cc = $('#contact-container #contact-cc');
cc.is(':checked') ? cc.attr('checked', '') : cc.attr('checked', 'checked');
});
});
});
});
});
});
},
show: function (dialog) {
$('#contact-container .contact-send').click(function (e) {
e.preventDefault();
// validate form
if (contact.validate()) {
var msg = $('#contact-container .contact-message');
msg.fadeOut(function () {
msg.removeClass('contact-error').empty();
});
$('#contact-container .contact-title').html('Sending...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: '80px'
}, function () {
$('#contact-container .contact-loading').fadeIn(200, function () {
$.ajax({
url: '/contact/data/contact.php',
data: $('#contact-container form').serialize() + '&action=send',
type: 'post',
cache: false,
dataType: 'html',
success: function (data) {
$('#contact-container .contact-loading').fadeOut(200, function () {
$('#contact-container .contact-title').html('Thank you!');
msg.html(data).fadeIn(200);
});
},
error: contact.error
});
});
});
}
else {
if ($('#contact-container .contact-message:visible').length > 0) {
var msg = $('#contact-container .contact-message div');
msg.fadeOut(200, function () {
msg.empty();
contact.showError();
msg.fadeIn(200);
});
}
else {
$('#contact-container .contact-message').animate({
height: '30px'
}, contact.showError);
}
}
});
},
close: function (dialog) {
$('#contact-container .contact-message').fadeOut();
$('#contact-container .contact-title').html('Goodbye...');
$('#contact-container form').fadeOut(200);
$('#contact-container .contact-content').animate({
height: 40
}, function () {
dialog.data.fadeOut(200, function () {
dialog.container.fadeOut(200, function () {
dialog.overlay.fadeOut(200, function () {
$.modal.close();
});
});
});
});
},
error: function (xhr) {
alert(xhr.statusText);
},
validate: function () {
contact.message = '';
if (!$('#contact-container #contact-name').val()) {
contact.message += 'Name is required. ';
}
var email = $('#contact-container #contact-email').val();
if (!email) {
contact.message += 'Email is required. ';
}
else {
if (!contact.validateEmail(email)) {
contact.message += 'Email is invalid. ';
}
}
if (!$('#contact-container #contact-message').val()) {
contact.message += 'Message is required.';
}
if (contact.message.length > 0) {
return false;
}
else {
return true;
}
},
validateEmail: function (email) {
var at = email.lastIndexOf("#");
// Make sure the at (#) sybmol exists and
// it is not the first or last character
if (at < 1 || (at + 1) === email.length)
return false;
// Make sure there aren't multiple periods together
if (/(\.{2,})/.test(email))
return false;
// Break up the local and domain portions
var local = email.substring(0, at);
var domain = email.substring(at + 1);
// Check lengths
if (local.length < 1 || local.length > 64 || domain.length < 4 || domain.length > 255)
return false;
// Make sure local and domain don't start with or end with a period
if (/(^\.|\.$)/.test(local) || /(^\.|\.$)/.test(domain))
return false;
// Check for quoted-string addresses
// Since almost anything is allowed in a quoted-string address,
// we're just going to let them go through
if (!/^"(.+)"$/.test(local)) {
// It's a dot-string address...check for valid characters
if (!/^[-a-zA-Z0-9!#$%*\/?|^{}`~&'+=_\.]*$/.test(local))
return false;
}
// Make sure domain contains only valid characters and at least one period
if (!/^[-a-zA-Z0-9\.]*$/.test(domain) || domain.indexOf(".") === -1)
return false;
return true;
},
showError: function () {
$('#contact-container .contact-message')
.html($('<div class="contact-error"></div>').append(contact.message))
.fadeIn(200);
}
};
contact.init();
});
Is this the functionality you are looking for?
See:
http://www.joecodeman.com/ITServices/Demos/jQuery/ShowDemo_v01a.html
If this is the effect dgbenner is looking for... then it is just a matter of organizing his/her code so it works correctly.
The basic effect dgbenner is trying to achieve is very simple. Therefore, the code just needs to be organized correctly.
This is the basic code / pseudo code:
//1) run the currently selected effect
function runEffect() {
//2) Hide the button`
$( "#eMailButton" ).fadeOut();
//3) Show the email form
$( "#effect" ).show( selectedEffect, options, 500, callback );
//4) Hide the email form and show the button again ( 4 seconds later in this demo...)
// other effects and actions can be coded when the user submits his/her info..)
function callback() {
setTimeout(function() {
$( "#effect:visible" ).removeAttr( "style" ).fadeOut();
$( "#eMailButton" ).fadeIn();
}, 4000 );
};

jQuery - If browser tab is focused, then do AJAX - Not working

I have a code that determines if current browser window or tab is active. If it's active, the title of the tab says "active" and if not it says "blurred"
It is working fine. Here's the code:
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
document.title = 'focus';
}
}
$(this).data("prevType", e.type);
})
The code above is working fine.
Now if I add AJAX to it, it doesn't work.
$(window).on("blur focus", function (e) {
var prevType = $(this).data("prevType");
if (prevType != e.type) { // reduce double fire issues
if (e.type == "blur") {
document.title = 'blurred';
} else if (e.type = "focus") {
var interval = function () {
$.ajax({
url: "<?php echo base_url('home/get') ?>",
cache: false,
success: function (html) {
$("#text").val(html);
document.title ='focus';
},
});
};
setInterval(interval, <?php echo $int ?>);
}
}
$(this).data("prevType", e.type);
})
It says focused if it's in focus. If I go out of focus, it says "blurred" for less than a second, then says focus again. I don't know why. I want it to say blurred if it's not in focus. Adding the AJAX code doesn't make it work.
Please help. Thanks.
You need to use clearTimeout() in your blur event. My code continuously polls my server for data, but when I go out of the page, it stops polling. Please look at the implementation below. I have done the similar one in my application here:
$(window).blur(function() {
clearTimeout(getJsonTmr);
clearTimeout(updatePreviewTmr);
}).focus(StartTimers);
function StartTimers () {
// Every half a second,
getJsonTmr = setInterval(function () {
$.get("/doodles/update?getJson&DoodleID=" + DoodleOptions.DoodleID, function (data) {
data = JSON.parse(data);
if (!DoodleOptions.isActive)
clearDoodleCanvas();
$.each(data, function (index) {
drawFromStream(data[index]);
});
});
}, 500);
updatePreviewTmr = setInterval(function () {
$.post("/doodles/update?updatePreview", {
"DoodleID": DoodleOptions.DoodleID,
"DoodlePreview": canvas.toDataURL()
});
}, 5000);
}
StartTimers();
You can use the above code as reference and change yours.
A simple reference implementation for you...
function timers() {
tmrAjax = setInterval(function () {
$.get(/* ... */);
}, 1000);
}
timers();
$(window).blur(function () {
clearInterval(tmrAjax);
}).focus(timers);

Need to change code to periodically execute (autosave)

This is working code. If click button, code executes
$(document).ready(function() {
$("#register").click(function(){
if ($("#is_row_changed1").val() > 0) {
$.post(
"_autosave.php",
$("#form1").serialize(),
function(data) {
$('#load').html(data);
document.getElementById('is_row_changed1').value = 0;
}//function(data) {
);//$.post(
//var str = $("#form1").serialize();//this will display in #stage2 all input values like date_day1=22&date_month1=04
//$("#stage2").text(str);
}//if ($("#is_row_changed1").val() > 0) {
});//$("#register").click(function(event){
});//$(document).ready(function() {
I need it execute periodically, for example each 5 seconds
If $(document).ready(function() { change to function autosave() {
var t = setTimeout("autosave()", 5000); nothing happens.
What would be correct code?
Update
Seems got working code. Please, any comments (may be something incorrect/not good)
$(document).ready(function() {
$(function() {
setTimeout(autoSavePost, 5000);
});
function autoSavePost() {
//$("#register").click(function(){
if ($("#is_row_changed1").val() > 0) {
$.post(
"_autosave.php",
$("#form1").serialize(),
function(data) {
$('#load').html(data);
document.getElementById('is_row_changed1').value = 0;
}//function(data) {
);//$.post(
//var str = $("#form1").serialize();//this will display in #stage2 all input values like date_day1=22&date_month1=04
//$("#stage2").text(str);
}//if ($("#is_row_changed1").val() > 0) {
setTimeout(autoSavePost, 5000);
}//function autoSavePost() {
//});//$("#register").click(function(event){
});//$(document).ready(function() {
It seems fine, one change that i might do will be is to use setInterval
$(document).ready(function() {
function autoSavePost() {
if ($("#is_row_changed1").val() > 0) {
$.post("_autosave.php", $("#form1").serialize(), function(data) {
$('#load').html(data);
$('#is_row_changed1').val(0)
});
}
}
setInterval(autoSavePost, 5000);
});

Jquery Toggle states issue

I'm having a problem with the following code -
function slideContactDetails() {
if (sliderState == "closed") {
$(".sliderBlock").animate({width:400}, 'slow',function() {$("div.sliderForm").fadeIn("fast"); });
sliderState = "open";
setTimeout(function(){switchImg("first")},300);
}
else if (sliderState =="open") {
$(".sliderBlock").animate({width:0}, 'slow',function() {$("div.sliderForm").fadeIn("fast"); });
sliderState="closed";
setTimeout(function(){switchImg("second")},300);
}
};
var firstState = "images/closeTab.png";
var secondState = "images/contact_us.png"
function switchImg(imgNo){
if (imgNo == "first"){
$('.contactBtnBtn img').attr("src", firstState);
$('.sliderBlockForm').show();
}
else if (imgNo == "second"){
$('.contactBtnBtn img').attr("src", secondState);
$('.sliderBlockForm').hide();
}
}
basically I'm trying to open and close an animated 'contact us' div. When opened I want the image to switch to a close image and visa-versa on close.
The issue I have is that the image switches as requested, but only for a split second as the sliderstate variable has now altered the 'else if' also appears to action and changes the image back again! I have tried to fix using timeouts, this works in all broswers apart from Chrome!
Any advise greatly received!!
Cheers
Paul
$("div.sliderForm").click(
$(this).toggle('slow');
);
Couldn't you just place the image switching in the if/else block, and remove the need for the setTimeout()?
function slideContactDetails() {
if (sliderState == "closed") {
$(".sliderBlock").animate({
width: 400
}, 'slow', function () {
$("div.sliderForm").fadeIn("fast");
});
sliderState = "open";
$('.contactBtnBtn img').attr("src", firstState);
$('.sliderBlockForm').show();
} else {
$(".sliderBlock").animate({
width: 0
}, 'slow', function () {
$("div.sliderForm").fadeIn("fast");
});
sliderState = "closed";
$('.contactBtnBtn img').attr("src", secondState);
$('.sliderBlockForm').hide();
}
};
the following worked for me based on Coding Freaks's answer.
$(".sliderBlock").hide();
$('img.slider').toggle(
function()
{
$(".sliderBlock").animate({width:400}, 'slow',function() {$('.contactBtnBtn img').attr("src", "images/closeTab.png");$('.sliderBlockForm').show();});
},
function()
{
$('.sliderBlockForm').hide();
$(".sliderBlock").animate({width:0}, 'slow',function() {$('.contactBtnBtn img').attr("src", "images/contact_us.png");});
});

Categories

Resources