If Input is focused trigger X else trigger Y

92 views Asked by At

I'm trying to trigger an opacity animation on a menu when the search input is focused, and when it is not focused for that menu to return to opacity:1.

My botched code below.

if($('input#edit-keys-2').is(":focus")){
  $('#zone-header ul#nice-menu-1').animate({opacity:0}, 300);
}else{
  $('#zone-header ul#nice-menu-1').animate({opacity:1}, 300);
}   
2

There are 2 answers

1
Dhiraj On BEST ANSWER

Use .focus() and .blur() like this instead

$('input#edit-keys-2').on("focus", function(){
  $('#zone-header ul#nice-menu-1').animate({opacity:0}, 300);
}).on("blur", function(){
  $('#zone-header ul#nice-menu-1').animate({opacity:1}, 300);
});

$('input#edit-keys-2').on("focus", function(){
  $('#nice-menu-1').animate({opacity:0}, 300);
}).on("blur", function(){
  $('#nice-menu-1').animate({opacity:1}, 300);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="focus me" id="edit-keys-2"/>
<div id="nice-menu-1">animate me</div>

0
maraaaaaaaa On

Sounds like you want to use the JQuery events:

.on( "blur", handler )
.on( "focus", handler )

https://api.jquery.com/blur/
https://api.jquery.com/focus/