0

I have two inputs in a div, and set tabindex=1 to make it focusable.

<div class="wrapper" tabindex="1">
  <input class="input" type="text">
  <input class="input" type="text">
</div>

And my SCSS:

div {
  border: solid 1px lightgray;
  padding:3px;
  display: inline-block;
  background-color: #fff;
  &:focus {
    outline: none;
    border: solid 1px blue;
  }
}
input {
  border: solid 1px transparent;
  &:focus {
    outline: none;
    border-bottom: solid 1px red;
  }
}

This way, div will not focus when inputs were focus. So, I use jQuery to make this. div's border is red when input is focus

(function($) {
  $(".input").on("focus", function() {
    $(this).parent("div").addClass("focus");
  });
  $(".input").on("focusout", function() {
    $(this).parent("div").removeClass("focus");
  });
})(jQuery);

I wonder if there is a better way to make this?

Here is my JSFiddle.

user7393973
  • 1,978
  • 13
  • 44
Cony LuLu
  • 49
  • 8
  • The code already achieves what you are trying to do. What exactly do you want to make "better"? Are you going for speed, or are you going for legibility? Either way, your function is already pretty much the best way of going about what you're trying to do... Or are you trying to change the border of `.wrapper` on input focus? – Obsidian Age Mar 02 '17 at 02:39
  • @ObsidianAge Is it possible to make this without js? And yes, I'm trying to change the border of `.wrapper` on input focus. – Cony LuLu Mar 02 '17 at 02:47
  • Why do you want to make the DIV focusable? It's a bit confusing to the user if they tab to it and it changes colour from grey to blue but they still can't type until they tab one more time to an input that they can't see. (Also, tabindex of 1 pulls it out of the standard tab sequence, which is often a bad idea.) – nnnnnn Mar 02 '17 at 02:50
  • @nnnnnn At first, I just want to make it have focus status(when the input focus, and make div focus at same time). Now, I think it's really a bad way! – Cony LuLu Mar 02 '17 at 03:00

1 Answers1

0

Currently tabbing selects the div (giving it a blue border). But you can't type anything in there so you have to hit tab again, which seems pointless to me. So I'd give the inputs a tabindex, rather than the wrapper:

<div class="wrapper">
  <input class="input" tabindex="1" type="text">
  <input class="input" tabindex="2" type="text">
</div>

But apart from that I don't know of any way to make the wrapper highlight except with javascript, as you have already done.

K Scandrett
  • 15,287
  • 4
  • 33
  • 59
  • Thanks, I haven't thought about this point!! At first, I just want to make it have focus status(when the input focus, and make div focus at same time). – Cony LuLu Mar 02 '17 at 02:59
  • http://stackoverflow.com/a/1014958/1544886 confirming as of Feb '17 there is no parent selector, so JS is the only option (for `focus` anyway... `hover` can use a CSS tick to affect a parent element.) – K Scandrett Mar 02 '17 at 03:03