Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder
    Join Date
    Jun 2002
    Location
    TEXAS . . . 'nuf said
    Posts
    468
    Thanks
    0
    Thanked 0 Times in 0 Posts

    need simple IF...ELSE for "var" in JS

    Simple JS for many of you...but not for me. Yes, I know I really need to learn these simple JS code writing staples. Getting a quick answer would be great. I know I have bookmarked many sites wherein I could learn this...but I don't have the time right now. Anyway...

    I have the following in a portion of my JavaScript code:

    var boxwidth=530;

    I need to have it set to 530 for +/- 800px resolution, and 670 for 1024px and up.


    I've used the following in my <head> for another script, but couldn't figure out the way to "if...else" it.

    <script type="text/javascript">
    var res =
    (screen.width<=810) ? '800' :
    (screen.width>810) ? '1024' : '';
    document.write('<link rel="stylesheet" type="text/css" href="css' + res + '.css">');
    </script>
    Gordo
    "In the End, we will remember not the words of our enemies, but the silence of our friends."
    - Martin Luther King Jr. (1929-1968)

  • #2
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    What you are trying to use is called the ternary operator. It's format is like this (for assiging values to variables)

    variable = (condition) ? valueIfTrue : valueIfFalse;

    Sooo

    var boxwidth = (screen.width<1024)? 530 : 670;

  • #3
    Regular Coder
    Join Date
    Jun 2002
    Location
    TEXAS . . . 'nuf said
    Posts
    468
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I never thought I'd say this about a little line of JS code, but that is so cool! Just a simple little snipet does exactly what I need it to do.

    THANKS!

    Gordo
    "In the End, we will remember not the words of our enemies, but the silence of our friends."
    - Martin Luther King Jr. (1929-1968)

  • #4
    Senior Coder
    Join Date
    Aug 2002
    Posts
    3,467
    Thanks
    0
    Thanked 0 Times in 0 Posts
    Ya, it is pretty cool. and it's not just for defining variables. for example
    Code:
    function happy()
    	{
    	alert("You are happy! =)");
    	}
    function sad()
    	{
    	alert("You are sad! =(");
    	}
    
    var mood = 'happy';
    (mood == 'happy') ? happy() : sad();
    Ok, silly example, but I think you get the point...
    Last edited by beetle; 08-08-2002 at 04:35 AM.


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •