I am attempting to follow the answer here to create a loading animation using jQuery: https://stackoverflow.com/a/1964871/23334971
Unfortunately, no loading animation shows for me and I’m not sure why.
I am using Python/django for my server-side script.
Here is my minimal reproducible example:
HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="script.js"></script>
<link rel="stylesheet" href="stylesheet.css">
</head>
<body>
<article>
<form id="calculatorForm">
<label for="num1">Numbers</label>
<input type="number" name="number1" id="number1">
<input type="number" name="number2" id="number2"><br />
<button type="submit" role="button">Calculate</button><br /><br />
</form>
<div class="modal"></div>
<div id="result"></div>
</article>
</body>
</html>
stylesheet.css: (just copied and pasted from the linked stackoverflow answer)
.modal {
display: none;
position: fixed;
z-index: 1000;
top: 0;
left: 0;
height: 100%;
width: 100%;
background: rgba( 255, 255, 255, .8 )
url('https://i.stack.imgur.com/FhHRx.gif')
50% 50%
no-repeat;
}
/* When the body has the loading class, we turn
the scrollbar off with overflow:hidden */
body.loading .modal {
overflow: hidden;
}
/* Anytime the body has the loading class, our
modal element will be visible */
body.loading .modal {
display: block;
}
script.js:
// this is the code i've copied and pasted from the SO answer
$body = $("body");
$(document).on({
ajaxStart: function() { $body.addClass("loading"); },
ajaxStop: function() { $body.removeClass("loading"); }
});
// this is the code I'm using to connect to my back-end python code and return a result
$(document).ready(function() {
$('#calculatorForm').on('submit', function(event) {
event.preventDefault();
setTimeout(function() {
$.ajax({
url: '',
type: 'get',
data: {
number1: $('#number1').val(),
number2: $('#number2').val(),
},
success: function(response) {
$('#result').html('<b>Result: </b>' + response.result);
}
});
}, 3000);
});
});
2
Answers
I replaced my script with:
I'm not sure why my original code doesn't work, but this does.
Credit: ChatGPT
the code works. You may not see it because the process takes place in a very short time. You can use
setTimeout()
function to see.