Ajax response that slides open a div - javascript

Okay, this is following on from my previous question reguarding performing a simple ajax request that, once the request has returned a readyState of 4 and a status of 200 it inserts the response into a div and slides it down nicely. I don't want it to be performed using a toolkit such as jQuery or scriptalicious.
here is the original question:
Ajax with slide effects onready witout using a toolkit
So far I have managed to get it all working quite nicely. However I have the problem that, the text returned is shown and then the div expands. I need it to work with the div and text expanding together.
Here is my code
function slideDown()
{
document.getElementById('slideDiv').style.visibility = 'hidden';
xmlhttp.open("GET", "parse.php?what=main", true);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById('butt').value = 'hide';
document.getElementById('slideDiv').innerHTML = xmlhttp.responseText;
document.getElementById('slideDiv').style.display = 'block';
var fHeight = document.getElementById('slideDiv').offsetHeight;
document.getElementById('slideDiv').style.height = '0';
document.getElementById('slideDiv').style.visibility = 'hidden';
function timeIt()
{
function bar()
{
timeSlide(fHeight);
}
setTimeout(bar, 10);
}
timeIt();
}
}
xmlhttp.send(null);
}
function timeSlide(fHeight)
{
var fHeight;
var diff;
document.getElementById('slideDiv').style.visibility = 'visible';
var cHeight = document.getElementById('slideDiv').clientHeight;
if (cHeight < fHeight)
{
cHeight = cHeight + 3;
document.getElementById('slideDiv').style.height = cHeight+'px';
function timeIt()
{
function bar()
{
timeSlide(fHeight);
}
setTimeout(bar, 10);
}
timeIt();
}
else
{
endSlide();
}
}
I think this is happening due to using the following to put the returned get request into the div.
document.getElementById('slideDiv').innerHTML = xmlhttp.responseText;
Can someone please put me in the correct direction with this? I'm not particularty good with JavaScript and I'm probably going the complete wrong way about it so any pointers would be great! Thanks in advance!

It's hard to say without seeing it in action but try adding this:
document.getElementById('slideDiv').style.overflow = 'hidden';

Related

Trigger a jQuery function from another file in JS

How I can call/trigger a jQuery function (which is in another file) from JS.
So basically this is the jQuery function (/js/animation.js).
$('#spin').click(function () {
var tickets = Math.floor(Math.random() * 200) + 1;
if(tickets < 51) {
var winner = 155;
}
else {
var winner = 145;
}
rouletteSpin(winner);
});
I know that its based on a codepen Roulette Animation.
Now the problem is that it should not roll without going through an if statement.
The statement should be a variable using Database info.
That's the point.
In my opinion you cant use PHP / select DB Info in jQuery so I decided to go into my index.php to trigger the jQuery function after the if statement in js went through.
So let me show you my HTML Button + JS Function:
onclick="openCase()
into the first HTML Button tag.
Now the JS Function:
<script>
var credits = CodeToGet_MYSQL_DB_Info_here_written_in_php;
function openCase() {
if(credits > 10000) {
spinIt();
}
else {
alert('Something went wrong');
}
}
And changed the jQuery Function (in path /js/animation.js) to the following:
function spinIt () {
var tickets = Math.floor(Math.random() * 200) + 1;
if(tickets < 51) {
var winner = 155;
}
else {
var winner = 145;
}
rouletteSpin(winner);
});
That is not working. I already googled a lot so please don't flame me.
Already used pretty much every method of this post:
calling Jquery function from javascript
Would be nice if someone can help me out!

AJAX load animation for chat?

How do I add the slideDown jquery animation when I knew message is loaded? Perhaps I can't with my method for loading... A file takes user input and inserts into database. Another file pulls from database onto chatbox and styles.
Javascript Code:
var form = document.querySelector('form[name="chatbox"]');
form.addEventListener("submit", function (event) {
event.preventDefault();
});
function submitChat() {
if(chatbox.message.value == '') {
alert('Error: Missing Fields.');
return;
}
var message = chatbox.message.value;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4&&xmlhttp.status==100) {
document.getElementById('chatlog').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET','chat.php?message='+message, true);
xmlhttp.send();
chatbox.reset();
}
$(document).ready(function(e) {
$.ajaxSetup({cache:false});
setInterval(function() {$('#chatlog').load('logs.php');}, 200);
});
Please let me know if you need the PHP attached.. Thanks for the help! :)

setInterval to read text file

I have some troubles to read a number from a text file with JavaScript.
setInterval("readTextFile()", 500);
function readTextFile() {
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "zoom.txt", false);
rawFile.onreadystatechange = function() {
if (rawFile.readyState === 4) {
if (rawFile.status === 200 || rawFile.status == 0) {
var allText = rawFile.responseText;
document.getElementById('boldStuff').innerHTML = allText;
writeln(allText);
}
}
}
rawFile.send(null);
}
The goal is to read a value into zoom.txt every 500ms, but this code doesn't work.
The value from the text file isn't refresh on F5 but only when I open (or refresh) zoom.txt in my browser.
I find something strange, this code works the first time I used it on Midori. Could you help me please ?
Thanks,
EDIT :
I tried that :
setInterval(readTextFile, 500);
setInterval(test, 500);
function readTextFile()
{
var rawFile = new XMLHttpRequest();
rawFile.open("GET", "zoom.txt", false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
document.getElementById('boldStuff').innerHTML = allText;
}
}
}
rawFile.send(null);
}
function test(){
document.getElementById('boldStuff').innerHTML = '';
}
My value is blinking on the screen but don't change even if I modify it.
First parameter to the setInterval should be a function and not function call.
setInterval(readTextFile, 500); //No need of quotes
If it is fetching the data from the text file on page refresh means that your code is working fine.
Now, you need to change the text in your text file so that it will get new value from the text file.
To check the content every interval you need to empty the html of your div like,
function readTextFile() {
// empty the div first to get the new value from text file
document.getElementById('boldStuff').innerHTML = '';
...
Okay, I empty the cache of Firefox and avoid to use it and the code is working fine.

switch checked check-box with time interval in javascript

I'm a total noob at javascript and currently having issues with a project.
I'm trying to make a picture slide with specific transitions. The slide builds on and tags for the transition (check-boxes). I tried making a script that changes the checked box after every 5s.
I already got a good chunk of help from a friend but I can't get it to work at all.
This is the script:
var slider_i = 1;
function slider_change(){
if(++slider_i > 4){
slider_i=1;
}
document.getElementById('select-img-'+slider_i).checked = true;
setTimeout(slider_change, 5000);
}
slider_change();
Here is the slider I'm talking about:
http://demo.br-photography.ch/Portal/transitions/index_3.html
I made a jsfiddle, easier to test cause then we can see if the checkboxes without the css properties actually switch. They do, but my slide on the testsite is not switching the images as it should...?
https://jsfiddle.net/t4eapmgb/
For your information, setTimeout(, 50000) is triggerd after 50000 ms = 50sec.
If you want to wait 5 sec you have to write setTimeout(, 5000)
Just place script from top to bottom. There is reference error because elements(checkboxes) are not available when initially page is loaded.
Or you may also add try catch block for this issue as follows:
replace this
var slider_i = 1;
function slider_change(){
if(++slider_i > 4){
slider_i=1;
}
document.getElementById('select-img-'+slider_i).checked = true;
setTimeout(slider_change, 5000);
}
slider_change();
With this one:-
var slider_i = 1;
function slider_change(){
if(++slider_i > 4){
slider_i=1;
}
try{
document.getElementById('select-img-'+slider_i).checked = true;
}catch(err){}
setTimeout(slider_change, 5000);
}
slider_change();
try:
var slider_i = 0; // !!!
var slider_change = function (){
if(++slider_i > 4){
slider_i=0;
}
document.getElementById('select-img-'+slider_i).checked = true;
setTimeout(slider_change, 50000);
};
slider_change();
or
var slider_i = 1;
var slider_change = function (){
if(slider_i++ > 3){ // !!!
slider_i=1;
}
document.getElementById('select-img-'+slider_i).checked = true;
setTimeout(slider_change, 50000);
};
slider_change();
what's actually happening with your code:
slider_i is set to 1.
function slider_change is called
it first increments the slider_i because of ++slider_i
now slider_i has the value of 2
it now checks against <4
if not true, it checks an element with id select-img-<value of slider_i>
The last step generates the id of select-img-2.
select-img-1 will never be reached. I don't know whether this is causing any subsequent errors.
Use
//Repeats forever
var variable = setInterval(functionYouWantToCall, 5000);
//Cancel the interval
clearInterval(variable);

xhr.status and xhr.readyState is 0

I'm working with HTML5 multiple file uploader. For some purpose I'm queuing the requests into a JavaScript array and I'm trying with two approaches here, one is, sending all the requests by a loop using a for loop and the next approach is like starting the next request after the previous request got finished. Here is the code,
function processUploads(i)
{
if(typeof(i)=="undefined")
return;
if(i==0)
{
for(i=0;i<4;i++)
{
xhrQ[i].open("POST",FUurl,true);
xhrQ[i].send(fdQ[i]);
xhrQ[i].onreadystatechange = function() {
if (xhrQ[i].readyState == 4 && xhrQ[i].status == 200) {
uploadComplete(xhrQ[i],i);
}
}
}
}
else
{
xhrQ[i].open("POST",FUurl,true);
xhrQ[i].send(fdQ[i]);
xhrQ[i].onreadystatechange = function() {
if (xhrQ[i].readyState == 4 && xhrQ[i].status == 200) {
uploadComplete(xhrQ[i],i);
}
}
}
}
function uploadComplete(xhr,i)
{
//processUploads(i+1);
var responseJSON = eval('(' + xhr.responseText + ')');
var upldrID = responseJSON.data.queueId;
var fileProgElem = $("#file_content").find("div[file-count="+upldrID+"]");
fileProgElem.attr("upload","finished");
fileProgElem.find("input[id=asset_id]").val(responseJSON.data.asset_id);
if(typeof(responseJSON)=="undefined") {
return;
}
$("#bar"+upldrID).css("width: 100%");
$("#progress_text"+upldrID).addClass("hide");
$("#progress_bar"+upldrID).html("Upload Complete!");
var pagename = $("#pagename").attr('value');
var cover_art = "<img src='"+responseJSON.data.thumb_location+"' alt='"+$.trim($("#file_name"+upldrID).html())+"' />";
$("#cover_art"+upldrID).html(cover_art);
//Hide the cross icon and enable the save
var action_divs = '<div id="done'+upldrID+'" class="hide enable">'
+'<a id="delete_file_'+upldrID+'" onclick="saveWorkspaceFileDetails(\''+responseJSON.data.project_id+'\',\''+responseJSON.data.asset_id+'\',\''+upldrID+'\',\''+responseJSON.data.file_name+'\',\''+responseJSON.data.size+'\',\'delete\',\''+pagename+'\')">'
+'<i class="tl-icon-20-close-gray"></i>'
+'</a>'
+'</div>';
$("#cancel_upload"+upldrID).append(action_divs);
$("#progress_cancel"+upldrID).addClass("hide").removeClass("show");
$("#done"+upldrID).addClass("show").removeClass("hide");
//To show the post and cancel button
$("#submitFileUpload").removeClass("hide").addClass("show");
//Updating the title with the default value of file_name
var file_title = $.trim($("#file[file-count='"+upldrID+"']").find("#file_title").val());
if (file_title == "" && file_title != undefined){
$("#file[file-count='"+upldrID+"']").find("#file_title").val(responseJSON.data.file_name);
}
//For other category we need to enable the dropdown
if(responseJSON.data.category_id=='999')
{
$("#select_category"+upldrID).removeClass("hide").addClass("show");
}
//totSelFiles is a number of selected files that i sets as a global variable
if(i<(totSelFiles-1))
{
processUploads(i+1);
}
else
return;
}
But the problem is i'm getting the readyState and status as 0 in the if loop. But the file is getting uploaded to the server and the else condition is also working well if i only enable that block. So what could be the problem. I'm greatly confused. Any help would be greatly appreciate.
The problem is related to the closure you create with the anonymous function you use for onreadystatechange. It will have access to the value of i, but not from the time of creation of the closure but rather from the time of its execution. At that point of time i is always 4 and xhrQ[i] will not refer to the correct object. Use this instead
xhrQ[i].onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
}
}
The problem is that you want to continue with the index i inside the uploadComplete() function. For this you might need to create another inner closure with an immediately executing function that will create a local copy of the current index.
xhrQ[i].onreadystatechange = (function(_innerI) {
var that = this;
return function() {
if(that.readyState == 4 && that.status == 200) {
uploadComplete(that, _innerI);
}
}
})(i);

Categories