4

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

Tushar
  • 85,780
  • 21
  • 159
  • 179
Tom
  • 2,545
  • 5
  • 31
  • 71

2 Answers2

6

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">
Tushar
  • 85,780
  • 21
  • 159
  • 179
  • oh ok thanks but how do I do it if I want to select the one before? and not change the order? – Tom Sep 28 '15 at 03:46
  • @PaulBernhardWagner There is not previous sibling selector in CSS http://stackoverflow.com/questions/1817792/is-there-a-previous-sibling-selector, if you want, you can do the same with Javascript – Tushar Sep 28 '15 at 03:47
  • @PaulBernhardWagner yes you'll have to pure JS or any JS library like jQuery for DOM elements manipulation. – Roko C. Buljan Sep 28 '15 at 03:53
1

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/

Quỳnh MSO
  • 66
  • 1
  • 7