February 25, 201214 yr Hi, I am trying to learn JavaScript and jQuery so I messing around with if and else. After a lot of messing about I have come to the point where I am wondering if I am doing this correctly or if there is a better way or even a different way. what I am trying to do is to create a variable that starts at 0 and counts to 3 and once its about to go past 3 (ie 4) it will reset the variable to 0 and start counting again this is what I have var i = 0; $( 'a.test' ).click(function(){ if ( i <= 3 ){ //i would like you to do this alert ( i ) //great you did that now add 1 to I i(++i); } else { // reset variable i to 0 and run the function again i = 0 } this works, every time I click on test i get the alert with the number incremented by 1 after the fourth click i == 3 so the if statement is true and it moves to the else which sets i back to 0 but no alert comes up so after some tinkering around I came up with this var i = 0; $( 'a.test' ).click(function(){ if ( i <= 3 ){ //i would like you to do this alert ( i ) //great you did that now add 1 to I i(++i); } else { // reset variable i to 0 and run the function again i = 0 alert ( i ) i(++i); } while this does work I am not sure if there is a better way to do this. So if you are experienced in JavaScript I would like to hear your opinion as I am learning and want to know if I am doing things correctly.
February 25, 201214 yr There is usually a number of different ways of doing anything in javascript and jQuery, and the best method to use really depends on the circumstances, but what you have used above is fine, it gets the job done nicely.
February 25, 201214 yr Just another approach with fewer lines of code: $(document).ready(function(){ var i = 0, max_i = 3; $("a.test").click(function(){ alert(i); if (i <= max_i){ //Do something } i >= max_i ? i = 0 : i++; }); }); Edited February 25, 201214 yr by andyl
February 25, 201214 yr Author Just another approach with fewer lines of code: $(document).ready(function(){ var i = 0, max_i = 3; $("a.test").click(function(){ alert(i); if (i <= max_i){ //Do something } i == max_i ? i = 0 : i++; }); }); Thanks Andy!! This is brilliant. I was trying to do it this way but could not get it to work, I now know what I was doing wrong! thanks!!
February 25, 201214 yr Author No problem, glad to help. Thanks for my 200th rep point ahhhh cool congrats on the double century!!
Create an account or sign in to comment