Home > Software design >  jQuery: if/else statement: it cant read the else statement it reads only first if
jQuery: if/else statement: it cant read the else statement it reads only first if

Time:11-01

I have basic if-else statement. it cant read after if parts which are else if and else. İt only reads first if. this is my code. What might be the problem here.

if (screen.width < 992) {
alert('Less than 992');
 $("#res_img").toggleClass('col-lg-6 col-lg-5');
 $("#res_img_two").toggleClass('col-lg-6 col-lg-7');

 } else if (screen.width < 425) {

 alert('Less than 425');
 $("#res_img").toggleClass('col-5 col-12');
 $("#res_img_two").toggleClass('col-7 col-12');

 }
 else {
   console.log('success');
 }

CodePudding user response:

first of all, your code will run only once every page reload, be aware of that in testing. Second of all, let's rewrite what you wrote in code in plainer "pseudo" instructions:

if width of the screen is less than 2 pixels {
    say 'Less than 2';
 } else if width of the screen is less than 1 pixel {
    say 'Less than 1';
 }
 else {
    say 'success';
 }

Maybe this way it is more clear, that every screen that is less than 1 will be always less than 2 pixels, so, really, there is no real way to separate those two cases, when you ask this way. We can try to rearrange this question like this:

if width of the screen is less than 1 pixels {
    say 'Less than 1';
 } else if width of the screen is less than 2 pixel {
    say 'Less than 2';
 }
 else {
    say 'success';
 }

Then every screen that is less than 1 will be always less than 2 pixels, and if it is more than 1 but less than 2, then only the second statement will be true. But I think our intentions can be written more clearly as:

if width of the screen is less than 2 pixels and width of the screen is more than 1 {
    say 'Less than 2 but more than 1';
 } else if width of the screen is less than 1 pixel {
    say 'Less than 1';
 }
 else {
    say 'success';
 }
  • Related