I have this simple JQuery addition program with animation on keyup event of 2nd #num2 input type text, I am getting proper answer but animation is not showing.
$(document).ready(function() {
$('#num2').keyup(function() {
let num1 = parseFloat($('#num1').val());
let num2 = parseFloat($('#num2').val());
if (!isNaN(num1) && !isNaN(num2)) {
let sum = num1 + num2;
$('#add').text(sum);
$('#add').slideDown(4000);
} else {
$('#add').text("Please enter valid numbers");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
<input type="number" id="num1" placeholder="Enter first number">
<input type="number" id="num2" placeholder="Enter second number">
<h3 id="add"></h3><br/>
<h3 id="sub"></h3><br/>
<h3 id="mul"></h3><br/>
<h3 id="div"></h3><br/>
2
Answers
If I understood you correctly, you want to display the addition result with the animation effect of
slideDown
. The issue I am seeing here is that when you add the text to theh3
, it’s already down theinput
elements. Sliding it down will not take it anywhere else. If you want the animation ofslideDown
to work, probably, you canslideUp
first and then slide it down.I have added
h3
for showing the error because using the sameh3
for showing thesum
and theerror message
may not give you the right effect (at least in my opinion; I welcome others to correct me here)I tried to show here how it will work:
Since the element is visible at all time, slideDown() won’t give any visible changes.
Make sure to either do a slideUp() or hide() at the start of your keyup event, so that when your slideDown() happens, it can add the sliding effect you are looking for.
Also, add
display:none
to your elements in which you are going to show the output.