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
}
$(".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>
$(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();
}
});
});
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>
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>
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.