简体   繁体   中英

Hide div when input is clicked

I wrote a line where if an input is clicked it hides a div. The div is a static utility nav bar that caused an issue with Android's native keyboard. here is the code but the issue is it runs 9 sometimes 10 times and my back end developer says it will be a performance issue. What can i do to prevent this from happening? I am new to javaScript and jQuery so getting this far is good for me.

    function utilityNav() {
  if($(window).width() < 891) {
  //Utility Mobile Nav background-color
  var div = $('.navbar-static-bottom').show();
  $('input').focus(function() {
     $('.navbar-static-bottom').fadeOut();
     $("."+$(this).attr('input')).fadeIn();
  });

  $('input').blur(function() {
     $('.navbar-static-bottom').fadeIn();
  });
  }
}
utilityNav();
$(window).on('resize', utilityNav);
$('input').blur(utilityNav);

The reason why it is running so many times is because if the window resizes you are adding an event ever time.

As you resize the window, the event will fire multiple times. Every time the window resizes you are adding a new event.

you need to do this.

//SETUP

function utilityNav() {
  if($(window).width() < 891) {
  //Utility Mobile Nav background-color
  $('.navbar-static-bottom').show();
}

function Setup(){
  $('input').focus(function() {
     $('.navbar-static-bottom').fadeOut();
     $("."+$(this).attr('input')).fadeIn();
  });

  $('input').blur(function() {
     $('.navbar-static-bottom').fadeIn();
     utilityNav();
  });
  }
}


utilityNav();
$(window).on('resize', utilityNav);

I have not tested this but structurally this is what you need to do. There are still better improvements you need to add. Instead of placing the event on the input tag you should use delegates. You can read up on this.

For example if you were to add a new input box to the page afterwards. This would not work.

      //Setup
  function utilityNav() {
    if($(window).width() < 891) {
      //Utility Mobile Nav background-color
      $('.navbar-static-bottom').show();
    }
  }
  function setupUtil(){
    $('body').on('focus', 'input', debounce(function(e) {
      if($(e.currentTarget).is(':focus')) {
        $('.navbar-static-bottom').fadeOut();
      }
    }, 100));

    $('body').on('blur', 'input', debounce(function(e) {
      if(!$(e.currentTarget).is(':focus')) {
        $('.navbar-static-bottom').fadeIn();
      }
    }, 100));
  }

  setupUtil();
  $(window).on('resize', utilityNav);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM