Barry Allen
Barry Allen

Reputation: 9

How to change the background color of the div while focusing the text Input field?

In render,

 <div id="container" tabindex="0">
    <input id = "input" type="text" />
  </div>

In css,

#container::focus{
 background-color: "red"
}

I need to make the bg-clr to be fixed in the div when focusing the input field.

Upvotes: 1

Views: 2908

Answers (4)

User863
User863

Reputation: 20039

Try using :focus-within CSS pseudo-class

The :focus-within CSS pseudo-class represents an element that has received focus or contains an element that has received focus.

#container:focus-within {
  background-color: red;
}

#container {
  padding: 30px;
}
<div id="container" tabindex="0">
  <input id="input" type="text" />
</div>

Note: if you don't want to focus div#container directly remove tabindex

Upvotes: 7

Shivani Sonagara
Shivani Sonagara

Reputation: 1307

If you are ready to use the JavaScript, this one can be the one solution. Based on the requirement you can se the color into Focus and Blur event.

$(document).on('focus','.input', function() {
$("#container").css("background-color","black");
})

$(document).on('blur','.input', function() {
$("#container").css("background-color", "white");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
    <input class="input" id="input" type="text" />
  </div>

Upvotes: 1

darius
darius

Reputation: 11

You'll need to add an onfocus event to the element then

 <div id="container" tabindex="0">
    <input id = "input" type="text" onfocus="myFunction(this)" />

<script>
function myFunction(item) {
    item.style.backgroundColor = 'red';
}
</script>

See this page for more info: https://www.w3schools.com/jsref/event_onfocus.asp

Upvotes: 1

Shuvo
Shuvo

Reputation: 1293

What are you trying to achieve isn't possible by css. You need use JavaScript focus and blur event listeners on the input to change the background color of div:

document.querySelector('#input').addEventListener('focus', function(e) {
    e.target.closest("#container").classList.add('focus');
})
document.querySelector('#input').addEventListener('blur', function(e) {
    e.target.closest("#container").classList.remove('focus');
})

CSS:

#container.focus{
 background-color: "red"
}

Upvotes: 1

Related Questions