0

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
}
Henry
  • 2,953
  • 2
  • 21
  • 34
art
  • 59
  • 1
  • 8

4 Answers4

0

 $(".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>
hubman
  • 149
  • 1
  • 15
0
$(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();
        }
    });
});
iman kazemi
  • 522
  • 5
  • 15
0

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>
Roge
  • 94
  • 1
  • 7
0

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>
Deep
  • 9,594
  • 2
  • 21
  • 33
  • but here is a problem,its working just with jquery 2.1.1,right? – art Jan 01 '17 at 16:55
  • it can be modified to use with other version as well. What version are you working with? The logic will not change even if some code change is required. – Deep Jan 01 '17 at 16:56
  • last version 3.1.1 :) – art Jan 01 '17 at 16:58
  • @art no change required with 3.1.1 . Updated the example – Deep Jan 01 '17 at 16:59
  • ohh sorry didnt saw at the start that you changed html,sorry,yeah right of course it works,thanks and Happy New Year too ;) – art Jan 01 '17 at 17:02