Tom
Tom

Reputation: 2661

How to change the color of a div in css when another one is on focus

I want input1 to change the color to blue, when in is on focus. Why does this not work?

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

css:

body {
    color: red;
}

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

I also created a jsfiddle

Upvotes: 4

Views: 9497

Answers (2)

Quỳnh MSO
Quỳnh MSO

Reputation: 66

You can change color only use CSS but it doesn't work with input element

May be you must use 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/

Upvotes: 1

Tushar
Tushar

Reputation: 87233

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

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

#in:focus + #input1 will select the #input1 element that is next to #in element which is focused.

You can read more about adjacent sibling selector

Updated Fiddle

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


As there is no previous sibling selector in CSS, you've to use 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">


If you're using 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">

Upvotes: 6

Related Questions