0

Ok, this is probably really a noob question, but I'll ask anyway!

At the moment, my function is defined like this:

function checkSize(size, otherSize, el) {
    if ($(el).width() <= 800) {
        size = otherSize;
    }

    alert(size);
}

but this wont work.
What does work is:

function checkSize(size, otherSize, el) {
    if ($(el).width() <= 800) {
        size = otherSize;
    } else {
        size = 5;
    }

    alert(size);
}

But that hardcoded value there is obviously really bad.
So actually, I want size only to be otherSize if the condition is true, else size should pass unaffected. How do I do it?

9
  • 1
    "size should pass unaffected" - excuse me ? In your first snippet, size will be exactly what was passed into the function invocation, when the condition does not match. Commented Mar 12, 2013 at 12:18
  • No problem. If the condition does not match, nothing should happen to the value of size. Commented Mar 12, 2013 at 12:19
  • 1
    code fine... show us where are u calling htis function Commented Mar 12, 2013 at 12:20
  • you tried to leave out the size = 5; overall? Commented Mar 12, 2013 at 12:20
  • 1
    Maybe you have a variable type casting problem, have you tried to make sure the size you are using as argument is and integer and not a string? Commented Mar 12, 2013 at 12:23

2 Answers 2

1

You should make sure the argument is an int before using it, but just in case you can try to force it into an integer if it's not:

function checkSize(size, otherSize, el) {
    if(typeof size != 'number'){
        size = parseInt(size, 10); // 10 is to define you are using a decimal system
    }

    if ($(el).width() <= 800) {
        size = otherSize;
    }

    alert(size);
}
Sign up to request clarification or add additional context in comments.

Comments

0

isn't this what you are looking for:

function checkSize(size, otherSize, el) {
    if ($(el).width() <= 800) {
        size = otherSize;
    } else {
        size = $(el)width();
    }

    alert(size);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.