I got a question why my if-else statement is not working.
I got a form with a text input, and when a user types in the size they want it should live edit the picture. I’m using the addclass and removeclass methods from jQuery. This is my script:
function slide() {
var n = Number(document.getElementById('Getal1').value)
if (n >= 101 && n < 201)
$(openDiv1());
else if(n > 200)
$(openDiv2());
else if(n >= 0 && n < 101)
$(closeDiv());
else {
alert("You did not enter a number!")
}
}
$(function openDiv1() {
$( "#ombouw_wrap" ).addClass( "Addclass_ombouw_wrap_2block", 1, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#midden" ).removeClass( "Addclass_ombouw_wrap_1block Addclass_ombouw_wrap_3block" );
}, 0 );
}
$(function openDiv2() {
$( "#ombouw_wrap" ).addClass( "Addclass_ombouw_wrap_3block", 1, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#midden" ).removeClass( "Addclass_ombouw_wrap_1block Addclass_ombouw_wrap_2block" );
}, 0 );
}
$(function closeDiv() {
$( "#ombouw_wrap" ).addClass( "Addclass_ombouw_wrap_1block", 1, callback );
return false;
});
function callback() {
setTimeout(function() {
$( "#midden" ).removeClass( "Addclass_ombouw_wrap_2block Addclass_ombouw_wrap_3block" );
}, 0 );
}
window.onload = closeDiv;
And this is my HTML code:
Lengte: <INPUT TYPE="text" NAME="numeric" onKeyup="slide()" id="Getal1" onKeyPress="return checkIt(evt)">
x Hoogte: <input type="text" ID="Getal2" onKeyPress="return checkIt(evt)">
x Diepte: <input type="text" ID="Getal3" onKeyPress="return checkIt(evt)">
</form>
When you reload the page, you see it is not starting with closedivs, but it starts straight with adding classes without executing the if-else statement.
What am I doing wrong here?
This is because jQuery treats
$(function)as a handy form of$.ready(function): the function-object passed is executed on page load.That is,
$(function openDiv1() {...})defines a function-object which is then passed to jQuery to execute automatically when the page loads. Instead, remove the functions from$(...). For instance,function openDiv1() {...}will suffice. (This will also fix the errors with not being able to callopenDiv1— since it is a function-expression it will not be assigned to a variable/property in scope.)The following describes an issue with the
slidefunction.JavaScript does some coercions; the following show why the else branch will never be reached:
But really, please don’t use
Number(it’s a wrapper-object fornumber), considerparseInt(str, 10)as a replacement. As an added bonus,parseInt("", 10)evaluates toNaN(not 0) and sinceNaN >= 0is false, this will fix the initial problem.Also pay attention to the consistency changes I added. The brackets are not necessary, but I find it aides in writing in a consistent well-formatted/well-indented style. Other things to pay attention to are ordering of if/else statements as well as the comparissons (keep it “flowing”).
Happy coding.