P. Rennings
P. Rennings

Reputation: 13

Jquery check for integer?

I have this code:

    jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

    // Move the damn autocue

 $('a.goDown').click(function(){
        alert($moveSpeed);
  $.scrollTo('#footer', $moveSpeed);
  return false;
 });

    $('a.goUp').click(function(){
        alert($moveSpeed);
  $.scrollTo('#header', $moveSpeed);
  return false;
 });


    // Speed settings for autocue

    $('a.changeSpeed').click(function(){
  $moveSpeed = $(this).attr('speed');
  return false;
 });
});

</script>

and if the changeSpeed is clicked, the alert box shows it is changed to the given number but it aint an integer, is there a way to convert a variable in to an integer?

thx :)

Upvotes: 1

Views: 11034

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1073968

I don't think it's the actual problem you're having, so I'm making this answer a CW, but FYI:

jQuery(function( $ ){

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        var $moveSpeed = 4000;
    }

That if statement is completely non-functional, the body of it is always run. The !$moveSpeed condition will always be true. This is because var declares a variable within the current function, regardless of where the var statement actually is or whether it's inside a condition or loop. More details in this article, but basically the interpreter sees that code like this:

jQuery(function( $ ){
    var $moveSpeed;

    // If no speed is set (when loading the page) set default speed

    if (!$moveSpeed) {
        $moveSpeed = 4000;
    }

...and since the value of a variable that isn't initialized yet is undefined, and !undefined is true, you'll always set $moveSpeed to 4000.

Upvotes: 1

Jamiec
Jamiec

Reputation: 136074

$('a.changeSpeed').click(function(){
  $moveSpeed = parseInt($(this).attr('speed'),10);
  return false;
 });

Javascript parseInt Function

Upvotes: 10

Related Questions