Mariah Weathersby
Mariah Weathersby

Reputation: 101

If Else Troubleshoot

The function is fairly self explanatory, but for some reason I cannot get this to work:

var windowWidth;

$(document).ready( function(){
    windowWidth = $(window).width();
    console.log(windowWidth);
});

$(window).resize( function(){
    windowWidth = $(window).width();
    console.log(windowWidth);
});


if (windowWidth > 600) {
    $('input').click( function(){

        var $inputname = $(this).attr('name');
        $('label[for="' + $inputname + '"]').removeClass('repositioned');

    });
}

else {
    $('input').click( function(){

        var $inputname = $(this).attr('name');
        $('label[for="' + $inputname + '"]').addClass('clear');

    });
}

If the window is larger than 600, the click should run the if statement; and if it is less, than it should run the else statement, but it is not running the second portion? I have looked thoroughly through it, and cannot figure out why it isn't acting appropriately.

Upvotes: 0

Views: 41

Answers (2)

spmurrayzzz
spmurrayzzz

Reputation: 136

You should be doing the if/else branching inside of the event handler function:

var windowWidth;

$(document).ready( function(){
  windowWidth = $(window).width();
  console.log(windowWidth);
});

$(window).resize( function(){
  windowWidth = $(window).width();
  console.log(windowWidth);
});

$('input').click( function(){
  var $inputname;

  if (windowWidth > 600) {
    $inputname = $(this).attr('name');
    $('label[for="' + $inputname + '"]').removeClass('repositioned');
  } else {
    $inputname = $(this).attr('name');
    $('label[for="' + $inputname + '"]').addClass('clear');
  }

}); 

Upvotes: 3

Jesse
Jesse

Reputation: 1262

Change your javascript function to this

$('input').click(function () {
    if (windowWidth > 600) {

        var $inputname = $(this).attr('name');
        $('label[for="' + $inputname + '"]').removeClass('repositioned');
        console.log("> 600");
    } else {

        var $inputname = $(this).attr('name');
        $('label[for="' + $inputname + '"]').addClass('clear');
        console.log("< 600");
    };
});

Upvotes: 0

Related Questions