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. 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. $('#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 ).

  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. 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.

  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. 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.