How to change div color in css when another is in focus

I want it to input1change color to blue when it inis in focus. Why is this not working?

<div id="input1">input1:</div>
<input id="in">

css:

body {
    color: red;
}

#in:focus + #input1 {
    color: blue; 
}

I also created jsfiddle

+4
source share
2 answers

You can do this by changing the html markup as follows.

Your selector #in:focus + #input1 {will not work because it +will select the next brother.

#in:focus + #input1will select the element #input1that will be next to #inwhich is focused.

Read more about nearby sibling selector

Updated Fiddle

body {
  color: red;
}
#in:focus + #input1 {
  color: blue;
}
<input id="in">
<div id="input1">input1:</div>
Run codeHide result

CSS sibling, Javascript.

Vanilla JS:

var input = document.getElementById('in'),
  div = document.getElementById('input1');

input.addEventListener('focus', function() {
  div.classList.add('focused');
}, false);

input.addEventListener('blur', function() {
  div.classList.remove('focused');
}, false);
body {
  color: red;
}
.focused {
  color: blue;
}
<div id="input1">input1:</div>
<input id="in">
Hide result

jQuery

$('#in').on('focus', function() {
  $('#input1').addClass('focused');
}).on('blur', function() {
  $('#input1').removeClass('focused');
});
body {
  color: red;
}
.focused {
  color: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>

<div id="input1">input1:</div>
<input id="in">
Hide result
+4

, CSS,

, jQuery

 .ribbon::after {   content: "Look at this orange box.";   background-color: #FFBA10;   border-color: black;   border-style: dotted; }

.ribbon::after {   content: "Look at this orange box.";   background-color: #FFBA10;   border-color: black;   border-style: dotted; }

.ribbon:hover::after {   content: "Look at this orange box.";   background-color: red;   border-color: black;   border-style: dotted; }

http://jsfiddle.net/98f3psLv/5/

+1

Source: https://habr.com/ru/post/1609230/


All Articles