jQuery if / else statements

There is no such thing as a jQuery if / else statement. Shocking, isn’t it? You might be thinking something like: “There must be! In fact, I’m 99% sure there is!“.

They don’t exist. This is because jQuery is javascript. What you’re looking for is a javascript if/else statement.

Why I decided to write about jQuery if

This article exists because when I started out with jQuery, I looked everywhere for a ‘jQuery if / else statement‘. It blew my mind that something as important as an if statement didn’t exist on the web. It took me a while to realize that I couldn’t find it because I was looking in the wrong place. It was because of this giant journey problem I decided to write an article for anyone following a similar path.

looking for useful jQuery tutorials?

Before I go on, if you’re looking for some pretty useful jQuery tutorials, have a look at

What is jQuery?

jQuery is a one of many javascript libraries. Very simply, these libraries are shortcuts created by people with crazy javascript skills for people like you and I. You could look at these libraries as one giant javascript plugin which make writing javascript 100 times more simple.

jQuery syntax is javascript, and therefore a lot of the things you do in jQuery are pretty much the same in plain ol’ javascript. ‘jQuery if statements’ are written the same way as javascript if statements, since it IS javascript.

The basic syntax

if(condition) {
	// code to be executed if condition is true
} 
else {
	// code to be executed if condition is false
}

The javascript (jQuery) if / else statement is almost identical to the PHP if / else statement.

$a = 5;
$b = 10;

if($a > $b) {
	echo "<p>A is larger than B</p>";
}
elseif($a == $b) {
	echo "<p>A is equal to B</p>";
}
else {
	echo "<p>B is larger than A</p>";
}

And the javascript(jQuery) if / else version is:

var	a = 5,
	b = 10;

if(a > b) {
	$("body").html("<p>A is larger than B</p>");
}
else if(a == b) {
	$("body").html("<p>A is equal to B</p>");
}
else {
	$("body").html("<p>B is larger than A</p>");
}

Note: The jQuery function html() is not equal to echo.

Explanation of another example if statement

HTML

<div id="example">
	<div></div>
	<div></div>
</div>

jQuery/javascript

$(document).ready(function(){ 

	var n = $("#example div").length;

	if (n < 2) {
		$("body").css("background", "green");
	} 
	else {
		$("body").css("background", "orange");
	}

});

Very basically the above is saying: Count the amount of div’s within the ID #example, and if it is less than 2, change the body’s background colour to green, otherwise change the background colour to orange.

What do you think the outcome would be?

If you guessed orange… Then you would be right.

Javascript shorthand if statement

As Stefan has commented and pointed out to me, there is a shorthand javascript if statement which we could use instead of the above:

var n = $("#example div").length;
$("body").css("background", (n < 2) ? "green" : "orange");

Now that is pretty handy! Creating a javascript if statement couldn’t be more simple.

Conclusion

What is a ‘jQuery if statement’? – It is a ‘javascript if statement’ that happens to contain some jQuery.

What say you?

  1. Stefan says:

    Interesting article, almost in very programming language the conditional statements are the same, another useful one would be the switch statement.

    There’s also a short-hand for a simple if statement one can use.

    var n = $(“#example div”).length;
    $(“body”).css(“background”, (n < 2) ? "green" : "orange");

    1. Jamy Golden says:

      That is awesome! I didn’t know about the shorthand version. I’ve just added that snippet to the article.

  2. These are not “jQuery” if…else statements, they’re standard JavaScript. The post’s title is a bit misleading, that’s all.

    1. Jamy Golden says:

      Yeah, the article is for absolute jQuery/javascript beginners and I actually address what you’ve just said multiple times.

  3. simon says:

    how would i do

    IF (class is moved 1000 pixels dont animate,
    else animate 102 pixels

    1. Jamy Golden says:

      I actually use something like that within this image slider tutorial.

      if(jQuery("#gallery").position().left > stopPosition){
      	jQuery("#gallery").animate({left : "-=" + imageWidth + "px"});
      }
    2. Mário says:

      how would i do

      if(".item".css height:"515px"){
         $(".item").animate({height:"0px"},300);
      }else{
          $(".item").animate({height:"515px"},300);
      }
    3. Jamy Golden says:
      if ( $('.item').height() == 515 ) {
         $(".item").animate({height:"0px"},300);
      }else{
          $(".item").animate({height:"515px"},300);
      }
    4. whidy says:

      hello, i hope to get a margin value how can i do ,such as $(‘.item’).margin-top() == 500,,

  4. WOW says:

    yes the shorthand if statement is, by using a ternary operator

  5. Billy Squall says:

    What about using the shorthand method for say, 5 different conditional checks?

    1. Jamy Golden says:

      The shorthand method distinguishes between a simple true/false. So you would need to make use of the if(){}else if(){}else() method.

    2. Stefan Bar says:

      A switch statement may be better as its faster than running through a if/else statement.

      var test = "male";
      switch (test) {
      	case "female":
      		// do something...
      		break;
      	case "male":
      		// do something else...
      		break;
      	default:
      		// do something if no match is found...
      		break; // always break on default to keep consistency 
      }
    3. Pecks says:

      Jamy, that is actually not true. You may do it like this:

      $(“body”).css(“background”, (n== 1) ? “green”: (n== 2) ? “black” : “orange”);

      You can nest this as well. :-)

    4. Jamy Golden says:

      Oh interesting, I’ve never tried that before. Do you know if it has any performance improvements over a normal if, else if statement?

    5. Andrew Smith says:

      Very interested to learn of if/else jQuery shorthand!

      I’m trying to convert the following if/else statement into such shorthand…without much success so far. Any ideas?

      var yourName = $('input#yourName').val(); // get value of "yourName" field
      
      if ((yourName == '') || (yourName == 'your name')) { // check if the field is empty or untouched
      
      	alert("Please enter your name"); // prompt user to enter name
      	$('input#yourName').css('border-color','#FFFF00'); // highlight input field by border-color
      	 event.preventDefault();
      
      }
      else {
      
      	return true;
      	
      }
    6. Jamy Golden says:

      Shorthand wouldn’t really be ideal for that situation, but you could do something like this:

      function alertName( event ) {
      	alert("Please enter your name"); 
      	$('#yourName').css('border-color','#FFFF00');
      	 event.preventDefault()
      }
      
      var yourName = $('input#yourName').val();
      
      yourName == '' || yourName == 'your name' ?  alertName( event ) : return true;

      The shorthand works nicely for things like:

      totalWidth > totalHeight ? $('#foo').height( totalWidth ) : $('#foo').height( totalHeight );

      Obviously those values could be anything, but my point is it’s a relatively short statement. A semi-colon within that will break the shorthand statement.

    7. Andrew Smith says:

      Very neat! Thanks!

  6. 29. Thank you for the info you have shared to us. One thing my sister fined this write-up very significant and it truly helps her in a lot of ways particularly dealing with her job.

  7. X-man says:

    How do you compare particular property of a div or an html element
    in jQuery in order to use it in if-else block…???

    1. Jamy Golden says:

      What exactly do you mean by ‘compare’? Could you give an example of what you are trying to do?

  8. Naaz says:

    my script this line (document.getElementById('Footer').style.marginTop='40px';)is working fine in IE7 ,IE8 and opera but footer is not going down in mozilla.can somebody suggest

    1. Jamy Golden says:

      This works in all major browsers:

      <html>
      <body>
      <div id="footer">
      	test
      </div>
      <script type="text/javascript">
      	document.getElementById('footer').style.color='red';
      </script>
      </body>
      </html>
    2. Eoin says:

      Consider the margin differences across all browsers?

      Consider adding * {margin: 0px} at the top of your CSS?

      (I’m no pro BTW, but it’s worth a try)

    3. @Eoin Yeah, a reset could be the problem, however, now that I look at Naaz’s script again I’m pretty sure the reason he’s having problems is due to the capital ‘F’ in document.getElementById('Footer').

  9. Naaz says:

    My req is to bring the Footer down when Accordion grows and my code is

    function footerAllignment() {  
    try{
    if (document.getElementById) {
        var windowHeight = getWindowHeight();
        
        if (windowHeight > 0) {
            var contentHeight = document.getElementById('ContentArea').offsetHeight;
            var QuoteSummaryContentHeight=document.getElementById('QuoteSummaryContent').offsetHeight;
            var alldivsHeight=document.getElementById('alldivs').offsetHeight;
            var accordionHeight=QuoteSummaryContentHeight+alldivsHeight;
            var LocalAgentHeight=document.getElementById('LocalAgent').offsetHeight;
            var footerElement = document.getElementById('Footer');
            var footerHeight  = footerElement.offsetHeight;
            if (windowHeight - (contentHeight + footerHeight) >= 0) {
                if(accordionHeight>contentHeight){
                    var resultFooter=accordionHeight-contentHeight;
                    if(resultFooter>0&&resultFooter100&&resultFooter200&&resultFooter290&&resultFooter350&&resultFooter450&&resultFooter<550){
                        document.getElementById('Footer').style.marginTop='260px';
                }
            }
            footerElement.style.top = (windowHeight - (contentHeight + footerHeight)) + 'px';
            }
            else{
                var resultFooter=accordionHeight-contentHeight;
                
                if(resultFootercontentHeight){
                    if(resultFooter100&&resultFooter200&&resultFooter290&&resultFooter350&&resultFooter450&&resultFooter550&&resultFooter<650){
                        document.getElementById('Footer').style.marginTop='320px';
                    }
                }
            }
        }
    }
    }
    catch(err){}
    }

    which am calling on onLoad of Page.footer is going down based on pixels in IE and opera but marginTop is not supported by Mozilla and Chrome.
    can somebody suggest???????

  10. Stefan says:

    If the margin value is constant why not use a css class rather than using the marginTop attribute.

    document.getElementById("footer").className = "marginClass";

    Otherwise the use of jquery will cater for cross browser in-compatibilities for you.

    $("#footer").css("margin-top", 100 + "px");

    Or you could use the following:

    var el = document.getElementById("footer");
    
    // for most browsers
    el.setAttribute("style", "margin: " + 100 + "px;");
    
    // for IE, harmless to other browsers.
    el.setAttribute("className", "margin: " + 100 + "px;");

    Hope that helps.

  11. Stefan says:

    Ignore the last line.

    // for IE, harmless to other browsers.
    el.setAttribute(“className”, “margin: ” + 100 + “px;”);

  12. Thierry Eamon says:

    thanks alot for this explanation!!

    I’ve been told you can reload a page content with javascript/jquery without actually refreshing the browser.

    I’m trying to do following:

    <a href="#" rel="nofollow">show grid</a>
    <a href="#" rel="nofollow">show list</a>
    $(document).ready(function(){ 
    
    	var viewType = grid or list; (this has to be declared by the links above)
    
    	if (viewType == 'grid') {
    		include the grid loop;
    	}
            elseif (viewType == 'list') {
    		include the list loop;
    	}
    	else {
    		include the list loop;
    	}
    
    });

    Basically what I want is the abbility to switch (back and forth) between two view modes on a category page without a refresh (wordpress).

    I hope it makes sense and someone can/ is willing to help me out

    Thierry

    1. Jamy Golden says:

      Hey Thierry, I’m a mod on the CSS-Tricks Forums and I answer as much questions as I can along with a bunch of other great people. Ask the question there and you will probably get an answer within about a day or two.

    2. Stefan says:

      Hi Thierry

      If the two view types need to be build via the backend.

      $(document).ready(function(){
      	$("#sidebar .view").html("Place your loader here...");
      	var viewType = "grid.php" or "list.php";
      	$.get(viewType, function(data) {
      		$("#sidebar .view").html(data);
      	});
      });

      Otherwise, adding a class two the viewType object to change the appearance might work better.

      $(document).ready(function(){
      	var viewType = "grid" or "list";
      	if (viewType == 'grid') {
      		$("#sidebar .view").removeClass("list").addClass(viewType);
      	} else {
      		$("#sidebar .view").removeClass("grid").addClass(viewType);
      	}
      });

      Hope this helps.

  13. Ganesh Kondalkar says:

    Hi Jamy,

    Thanks a lot!

    I was searching for a code which will help me in adding a class if there is only a single HTML element is available…

    I m new to the scripting but somehow copeup with sytax if get some clues from the net…. :)

    Thanks a lot!

  14. Dianilla says:

    Hi Jamy, thank you for the info, I have a question actually I need one if/else for hide or show one div, I had wrote the following function but it didn’t work:

    jQuery(document).ready(function(){   /*show div OtraUniversidad when option:selected = 165*/
      var optionValue = $("#Universidad option:selected").val();
      $("#OtraUniversidad").hide();  
      if(optionValue == '165'){
        $("#OtraUniversidad").show();
      }	
    });

    I don’t know what’s wrong I’m new in javascript and jquery :(
    some help is always welcome, thanks a lot!

    1. Jamy Golden says:

      Hi Dianilla :)

      The reason your javascript isn’t working like you want it to is because it is being run as the page is loaded and not again after that. So as the page loads it looks to see if the selected option is 165, it’s not so the div isn’t show. And that’s it.

      I’ve created a jsfiddle for you. It’s basically the same as your script with an added event, change().

      Hopefully this solves your problem!

    2. Dianilla says:

      HI!!! thank you so much, you save my life :) that solve my problem
      thank you!!! thank you!!! thank you!!! thank you!!!

  15. Caps says:

    Hello. I’m having an issue, How do I use an if statement to execute a php script if the location of a click is within a range?

    $(document).ready(function() {
      $('img').click(function(e) {
        var offset = $(this).offset();
        alert(e.clientX - offset.left);
        alert(e.clientY - offset.top);
      });
    });

    I want to not have to alert pop-up, and I want if say, a is between 100 and 200 and b is between 500 and 600, then do this:

    $(document).ready(function() {
    $('#5').click(function() {
     $.get("test.php");
    })});

    Help would be appreciated!

    1. You could do something like this:

      $(document).ready(function() {
        $('img').click(function(e) {
          var offset = $(this).offset();
          alert(e.clientX - offset.left);
          alert(e.clientY - offset.top);
      
          // If offset.left is between 100 and 200 and offset.top is between 500 and 600
          if ( offset.left > 100 && offset.left < 200 && offset.top > 500 && offset.top < 600 ) {
      
              $('#5').click(function() {
                  $.get("test.php");
              });
      
          };
      
        });
      });

      That may not be 100% what you were trying to do, but I'm sure it will help you to do what you're trying to do.

  16. Hrishikesh says:

    Good article. It helped to clear-out mt vision…Thanks a lot.

  17. PLa5teRz says:

    Who can help me to build this if/else situation?
    Situation:-
    1 survey, if user answer = “A”, the “Next” button will direct him to page “2A”, if the user answer = “B”, the “Next” button will direct him to page “2B”.

    1. if ( answer == 'A' ) {
          $('#next').attr('href', 'http://custom-url-for-a.com');
      } else if ( answer == 'B' ) {
          $('#next').attr('href', 'http://custom-url-for-b.com');
      };
  18. Alex says:

    Hello i’m having an issue with an if statement. I am trying to get the marginLeft value of a div and based on that trigger an alert however it dosent seem to be working. What am i doing wrong?

    $(document).ready(function() {
    
    	// load the first page automatic so its not blank 
    	loadfirst();
    
    	// event listeners 
    										
    	$('.control').bind('click', function() {	
    											
    		var position = $('#slideInner').css('marginLeft');
    											
    		if ( position== -936) { 
    			alert('margin left is 936')
    		}
    		
    	});		
    
    	function loadfirst() { 
    		$('#homes').load('pageone.html #homepage');
    	}
    });
    1. You must remember that .css() returns actual CSS values. so it would be returning something like ’936px’.

      In your if statement, you’re essentially saying:

      if ’936px’ is equal to 936

      And that will always return false because the two aren’t equal.

      Change it to this:

      if ( position == '-936px') {

      That should work!

  19. Henry says:

    This is what i need. Thanks!

  20. Warren says:

    How would I use an if else statement to do this.

    If the submit button is clicked when a certain radio button is selected display lightbox.

    1. Jamy Golden says:
      $('#form-id').submit(function(e){
          if ( !$('#radio-button-id').is(':checked') ){
          	e.preventDefault();
          };
      });

      Where ‘form’ is your ‘#form-id’ and ‘#radio-button-id’ are the corresponding ID’s.

      The code says this:
      On submit of the form, check to see if #radio-button-id is checked. If not, prevent the default functionality of the form ( aka don’t submit ).

    2. Warren says:

      Hey thanks for your help!

      Not to be a bother, but I have just one more little issue. I downloaded, and I’m in the process of using Lightbox 2. I was wondering if there is a way I could change the function of the exit button on the lightbox so on exit it could go to another webpage instead of back to the original.

  21. Travis says:

    i have a div that toggles up and down and i want it so when you click anywhere outside of the div for it to toggle back up. this is what i got so far.

    Any help would be appreciated.

    $(document).ready(function() {
    		
    		$("a.contact-btn").toggle(
          		function () {
           			 $("#contact").animate( {"top": "0"}, 900, "linear" );
         		 },
          		function () {
            		$("#contact").animate( {"top": "-400px"}, 900, "linear" );
        	});
        	  
    
    		$('body').bind('click', function() {
    			
    			var position = $('#contact').css('marginTop');
    
    			if ( position == '-400px') {
    				alert('margin top is equal to -400px')
    			}
    
    		});		
    });
    1. Jamy Golden says:

      Hey Travis, I’ve created a JSFiddle that does what you’re explaining. Let me know if you need some explaining or if I’ve misunderstood you.

    2. Travis says:

      Thank you for the reply and help. I was able to figure it out. I am stuck on why the background-image of the class uparrow isn’t showing up when i hover over the contact button(a.contact-btn).
      if you could help me out with why this is not working that would be awesome.

      If you have thoughts on if this is a bad idea or is annoying let me know.Basically im being stubborn and wanting to know why its not working;)

      Here is the link to my page again. Also i added some improvements since the last time you looked.
      travismichael.net/new_tmdesigns/index.php

  22. Andy says:

    hi all, i’m using a jQuery player for a client’s site, and on some pages, I need to have multiple instances of the player. what i have right now is that if i press a play button, all 5 instances play simultaneously, so I need to figure out a way to play only one instance at a time. Originally the jQuery goes like this:

    $(document).ready(function() {
            $("#jquery_jplayer_1").jPlayer({
                ready: function(event) {
                    $(this).jPlayer("setMedia", {
                        mp3: "http://somefile.mp3"
                    });
                },
                swfPath: "http://www.jplayer.org/2.1.0/js",
                supplied: "mp3"
            });

    So I assumed by adding ids like #jquery_jplayer_2, #jquery_jplayer_3, etc. would make it work. But still all instances play simultaneously. Do you think the solution would be to use if statements, and if yes, could you please show me how? Thanks!

    1. Jamy Golden says:

      This should work:

      $(document).ready(function(){
      
      	$("#jquery_jplayer_1").jPlayer({
      		ready: function () {
      			$(this).jPlayer("setMedia", {
      				m4a: "http://www.jplayer.org/audio/m4a/Miaow-07-Bubble.m4a",
      				oga: "http://www.jplayer.org/audio/ogg/Miaow-07-Bubble.ogg"
      			}).jPlayer("play");
      		},
      		ended: function (event) {
      			$("#jquery_jplayer_2").jPlayer("play", 0); // This stops #jquery_jplayer_2 from playing
      		},
      		swfPath: "js",
      		supplied: "m4a, oga"
      	})
      	.bind($.jPlayer.event.play, function() { // Using a jPlayer event to avoid both jPlayers playing together.
      			$(this).jPlayer("pauseOthers");
      	});
      
      	$("#jquery_jplayer_2").jPlayer({
      		ready: function () {
      			$(this).jPlayer("setMedia", {
      				m4a: "http://www.jplayer.org/audio/m4a/Miaow-07-Bubble.m4a",
      				oga: "http://www.jplayer.org/audio/ogg/Miaow-07-Bubble.ogg"
      			}).jPlayer("play");
      		},
      		ended: function (event) {
      			$("#jquery_jplayer_1").jPlayer("play", 0); // This stops #jquery_jplayer_1 from playing
      		},
      		swfPath: "js",
      		supplied: "m4a, oga"
      	})
      	.bind($.jPlayer.event.play, function() { // Using a jPlayer event to avoid both jPlayers playing together.
      			$(this).jPlayer("pauseOthers");
      	});
      
      });

      I’ve added a comments in the js so you can see what’s going on.

  23. Dawn Hanson says:

    So this may seem really lame – but I am just starting covering this topic with kids in my class – and I am having a hard time coming up with concrete examples so that they can see if statements in action, so I came across this site in my searches. I get what the concept it – but what other information do you need in order for this basic script to work with the CSS and HTML page to actually make the background color changed based on the value of the div tags –

    Also – how can I create a textfield that I could put a value in that could be compared to my if else statement and true output be shown on a HTML page?

    I am used to doing this all in flash with actionscript and creating dynamic textboxes so trying to move it over to this environment while the basic idea of coding is the same I am finding out – how to incorporate textfields and interpreting values is giving me some grief. Any hep would be great!

    1. Jamy Golden says:

      Hey Dawn. I’ve created a demo page ( which is now attached to this article ). I’ve commented all the javascript so you can see exactly what is going on. Let me know if that answers your questions, and if not I’ll see if I can clarify more clearly.

  24. David Scott says:

    I am trying to get a statement to show if all of the “inclusion” radio buttons are yes but if any one are no then the other statemnet shows. The code below does what ever the last radio button selected is. So basically I need the if($(this).val() == ‘yes’) to be true only if all three statements are yes

    $("['#inclusion']:radio").click(function(){			
    	if($(this).val() == 'yes'){
    		$("[name=criteria_met]").show();
    		$("[name=criteria_not_met]").hide();
    						
    	} else if($(this).val() == 'no'){
    		$("[name=criteria_met]").hide();
    		$("[name=criteria_not_met]").show();

    any suggestions?

    1. Jamy Golden says:

      I think you should look into the change() jQuery function.

      var $inclusionRadios = $("#inclusion").find("input[type='radio']");
      $inclusionRadios.change(function(){
      	if( $inclusionRadios.val() == 'no'){
      		$("[name=criteria_met]").hide();
      		$("[name=criteria_not_met]").show();
      	} else {
      		$("[name=criteria_met]").show();
      		$("[name=criteria_not_met]").hide();
      	}
      });

      That would find any radio button within the #inclusion element. If at any point they all become ‘yes’, everything in the ‘else’ area would take effect.

  25. ALi says:

    Hey

    How can I use the If statement in this case.

    I have an image with price.. and facebook share and tweet button with counters under the image.

    I want to reduce the price 1% after every 100 tweet
    and reduce the price 2% after every 100 facebook share

    foe example:

    price = 100$

    if tweet counter 100 < 200 than price= price – price * 1/100

    If share 100< 200 than price = price – price * 2/100

    sorry but i know an old programing language called qbasic :) thats why i wrote them in this way.

    thanks

    1. Jamy Golden says:

      Hi Ali,

      I’d do this:

      var price, // You should define whatever the price should be here
          tweetHundred = Math.floor(tweetTotal / 100), // This divides the amount of tweets by 100 and rounds it down to the closest whole number. You should define whatever the tweetTotal is
          shareHundred = Math.floor(shareTotal / 100), // Same here, but with the shares. You should define whatever the shareTotal is
          tweetDiscount = price * 0.1, // 10% of the price.
          shareDiscount = price * 0.2; // 20% of the price
      if(tweetHundred > 1) { // if there are at least more than 100 tweets
          price = price - (tweetHundred * tweetDiscount); // multiply the amount of hundreds there are by the tweet discount and subtract the total price
      }
      if(shareHundred > 1) {
          price = price - (shareHundred * shareDiscount); // Do this again, but with shares. The tweets and shares will work together.
      }
  26. Santosh Shelke says:

    Superb…. :)

  27. Melissa L. says:

    Hi! I have this sitemap, and I’m currently trying to switch from Ground level and Mezzanine level with a click of a button, using this:

    $('a.switchMezza').click(function() {
    	if("#levels").attr(
    		$("#levels").fadeOut(function() {
    		$(this).attr("src","../img/service/mezzanine.png").fadeIn();
    	});
    });

    This is working fine, but when, let’s say, the Switch to Mezzanine button is clicked twice, it fades out and in again with the same image. I would like to create a conditional statement to check if the current attribute is “../img/service/mezzanine.png,” and not to have fade it out and in again, but to just stay put.

    Thanks!!

    1. Melissa L. says:

      Oops! Ignore the “if(“#levels”).attr(” line.. I was trying it out!

      Here’s the code:

      $('a.switchMezza').click(function() {
      	$('#levels').fadeOut(function() {
      		$(this).attr('src','../img/service/mezzanine.png').fadeIn();
      	});
      });
  28. Santosh says:

    BIG Thank you!!
    I came here searching for jquery if-then-else.. lol.

  29. Shahz says:

    Hi Jamy,

    That article was really helpful. I was trying something similar which I managed to achieve without using if else though, but nevertheless, this was very helpful :) thanks!

    1. Jamy Golden says:

      Great! I’m glad it was helpful even if it didn’t help directly haha

  30. whidy says:

    thx , i have solute it..

    $(".up").click(function(){
        if ( $(".content").css("margin-top") == "0px" ) {
            $(".content").stop();
        } else {
            $(".content").animate({"margin-top": "+=100px"}, "slow");
        }
    });
  31. buxified says:

    Wow this is awesome. Thanks

    I am working on a responsive design and would like to display a different ad only when the viewport width is less or equal to 480px. Can you help?

    Thanks again

    1. Jamy Golden says:

      Hey :)

      $(document).ready(function(){
          var window_width = $(window).width();
      
          if(window_width < = 480){
              // show small add
          } else {
              // show larger add
          }
      });
  32. Gary Jonesd says:

    I am using 123ContactForms to create various forms on a number of my sites. This site (cmhoa.ca) requires a membership application. I have several drop down fields like “City” “Province” and “Park”. What I’m searching for is something that will use an IF/THEN routine to select other fields, such as IF the “City” is “Calgary” THEN select the “Province” as “AB”. More importantly, I don’t want the list of parks to be for the whole country, so it would be IF the “City” is “Kelowna” THEN the “Parks” list would only include parks in Kelowna.

    Am I dreaming that there is something out there? It would seem to have a lot of applications.

    Thanks.

  33. César says:

    Hi, i’m having troubles with this code, can some one help me?

    $('#sobre-mi').click(function(){
    	$('#box-metro').animate({top: '0'}, 'easeOutExpo');
    	if( $('#box-metro').css('top') == '0px') {
    		$('#box-metro').animate({top: '100px'});
    		}
    });
    1. Jamy Golden says:

      Hey, try something like this:

      $('#sobre-mi').click(function(){
      	var $boxMetro = $('#box-metro');
      	if( $boxMetro.css('top') == '0px') {
      		$boxMetro.animate({top: '100px'});
      	} else {
      		$boxMetro.animate({top: '0'});
      	}
      });

      I added the inital animate to an if statement and I replaced the easing with a standard linear motion incase you don’t have easing.js loaded up.

  34. César says:

    Hi, thanks for your answer, I solved my problem in this way:

    function Pos1(){
    $(‘#box-metro’).animate({top: ’0′}, 1000, ‘easeOutExpo’);
    $(‘#prev’).animate({opacity: “0″, left: ’182′}, 1000, ‘easeOutExpo’);
    $(‘#next’).animate({opacity: “0″, left: ’772′}, 1000, ‘easeOutExpo’);
    setTimeout(function(){$(‘#worker-icon’).animate({opacity: “1″, top: “70″}, 1500, ‘easeOutExpo’);},500);
    setTimeout(function(){$(‘#map’).animate({opacity: “1″, top: “220″}, 2000, ‘easeOutExpo’);},1800);
    setTimeout(function(){$(‘#info’).animate({opacity: “1″, top: “190″}, 1500, ‘easeOutQuad’);},1200);
    setTimeout(function(){$(‘#pin’).animate({opacity: “1″, left: “198″}, 2000, ‘easeOutElastic’);},2500);
    };

    function Pos2(){
    $(‘#box-metro’).animate({top: ‘-470′}, 1000, ‘easeOutExpo’);
    $(‘#prev’).animate({opacity: “1″, left: ’202′}, 1000, ‘easeOutExpo’);
    $(‘#next’).animate({opacity: “1″, left: ’752′}, 1000, ‘easeOutExpo’);
    $(‘.gallery-control’).css(‘display’, ‘block’);
    };

    $(‘#sobre-mi’).click(Pos1);
    $(‘#portfolio’).click(Pos2);

    You can check it on underlog.com, that’s my portfolio that i’m currently developing, thanks a lot!

  35. Cory says:

    Thanks for the article Jamy! I was wondering if this would work for a menu I am trying to style.

    When I hover over a in the menu, I’d like to change the style of the items before and after the being hovered.

    Eg; if (hover over ); + 1 and – 1 change border radius to 8px. Thanks!

    1. Jamy Golden says:

      Hey, you would do something like this:

      if(randomVar >= 1){
          $('.class-name-here').css('border-radius', '5px');
      };
      
  36. nasta geoga says:
    if(var < '100') {
    
    ................
    
    if(var < '20') {
    
    if(ocp_tab < '10') {
    
    var div = '#div';
    
    } else { var div = '#div_10'; }
    
    } else { var div = '#div_20'; }
    
    ...........
    } else {
    
    alert('no');
    
    }
  37. Thomas says:

    how would i do:

    if(if the size of the target div is 1270px)

    1. Jamy Golden says:
      if($('#target-div').width() === 1270){
          // do stuff
      };
  38. nhojcire says:

    A very helpful and ease to understand tuts, TWO THUMBS UP! ! !

  39. Fahed says:

    Thank you

    After being searchnig for several hours, finally a clear and comprehensive tutorial.

  40. RHan says:

    can i

    $(document).ready(function(){
        $('#button').click(function(){
            var toAdd = $('input[name=checkListItem]').val();
            var dict = function(){
               switch(toAdd){
                   case "apple":
                       return "a fruit";
                       break;
                   case "blah":
                       return "a word';
                       break;
                   default:
                       return "I didn't understand!"; 
                  }
           $('.list').append('' + toAdd + '');
        };
    });
    });
    1. Jamy Golden says:

      I don’t see why not.

  41. thatlarkin says:

    I can’t tell if any of the threads actually addressed my concern, but I’m trying to do this:

    if ($(‘#div’) is clicked {do something} else {fadeOut after 180000 seconds}

    Good tutorial. Thanks.

    1. Jamy Golden says:

      This should do the trick:

      // Set timer for 18
      var fadeTimer = window.setTimeout(function(){
      
          // Once timer is complete, fadeout div
          $('#div').fadeOut();
      
      }, 18000);
      
      // When #div is clicked
      $('#div').click(function(){
          // Clear/remove the timeOut set previously
          window.clearTimeout(fadeTimer);
          
          // Do something
      });
  42. Jared says:

    Nice little article. It was helpful to me as I am just learning javascript/jQuery.

  43. pete says:

    that was helpful overall, except i was baffled by your inclusion of PHP code as a reference, and no other PHP anywhere. i was looking back through everything to figure out what i missed

    1. Jamy Golden says:

      Hi Pete. Yeah the PHP inclusion is a bit random but the idea was to show how similar the languages are.

  44. Dorian says:

    I have figured it out myself…

    The conditions we’re not running, cause they we’re wrong. I altered the code a bit:
    ($(“//firstdiv”) .is(‘:visible’)) {

    // do this

    }

  45. Jordan Smith says:

    Hi Jamy,

    Thanks for taking the time to write this! Very Helpful!

  46. anaCvetkovic says:

    How would you write if else statement for 3 dropdowns where only one can be open on click. When one is open other two is closed? Thanks