Input focus and blur

1k Views Asked by At

I have this code https://fiddle.jshell.net/cabeqaky/26/ The question is how to make that on first div click, input get focus and on second div click input get unfocused. How to do that? :)

HTML

<input class="inp" type="text">
<div class="box"></div>

CSS

.box{
width:50px;
height:50px;
background-color:green;
margin-top:10px;
border:1px black solid;
cursor:pointer
}
4

There are 4 best solutions below

5
On BEST ANSWER

You can use mousedown event on div and check for if the input has focus. e.preventDefault() is used to avoid the focus to be on div element on mousedown event.

$("div").on("mousedown",function(e){  
  e.preventDefault();
  if($(".inp:focus").is(':focus'))
    $(".inp").blur();
  else
   $(".inp").focus();
})
.box{
width:50px;
height:50px;
background-color:green;
margin-top:10px;
border:1px black solid;
cursor:pointer
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<input class="inp" type="text">
<div class="box"></div>

0
On

 $(".box").click(function(){
    document.getElementsByClassName("inp")[0].focus();

})
    .box{
    width:50px;
    height:50px;
    background-color:green;
    margin-top:10px;
    border:1px black solid;
    cursor:pointer
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

    <input class="inp" type="text">
    <div class="box"></div>

2
On
$(document).ready(function(){
    $("div.box").data("toggle", 0);
    $("div.box").click(function(){
        var toggle = $("div.box").data("toggle");
        if(toggle === 0){
            $("div.box").data("toggle", 1);
            $("input.inp").focus();
        } else {
            $("div.box").data("toggle", 0);
            $("input.inp").blur();
        }
    });
});
0
On

use a javascript function on the div :

var focus = false;

function toggleFocus() {
  focus = !focus;
  if (focus) {
    document.getElementById("focusedInput").focus();
  }
}
<input class="inp" id="focusedInput" type="text">
<div class="box" onclick='toggleFocus()'></div>