Learn how to adjust the background color of a div when the text input field is in focus

When rendering the page,

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

In the CSS stylesheet,

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

I am looking to have a fixed background color in the div when focusing on the input field.

Answer №1

Consider implementing the :focus-within CSS pseudo-class for improved design

The :focus-within CSS pseudo-class is useful for styling an element that has received focus or contains a focused element.

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

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

Note: To avoid direct focusing on div#container, consider removing the tabindex attribute

Answer №2

It is not possible to achieve your goal using only CSS. In order to change the background color of a div when an input is focused, you will need to use JavaScript event listeners for the focus and blur events on the input element:

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');
})

Here is the CSS code to style the div when it is in focus:

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

Answer №3

Make sure to include an onfocus event in the element

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

<script>
function myCustomFunction(element) {
    element.style.backgroundColor = 'blue';
}
</script>

To learn more, visit: https://www.w3schools.com/jsref/event_onfocus.asp

Answer №4

If you're looking to implement some functionality in JavaScript, this code snippet might just do the trick. Depending on your requirements, it allows you to adjust the color for both the Focus and Blur events.

$(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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating fresh texts by pairing the values in constants with variables

Make sure to carefully read the question before proceeding. I have attempted multiple commands in order to retrieve a single variable from the server [TSE](https://old.tsetmc.com/Loader.aspx?ParTree=15131F) which serves Stock Exchange information. The pag ...

The RequiredFieldValidator in my textbox is triggered, however, it fails to prevent the postback when I include JavaScript in the

I have a required field validator that is functioning correctly when it's on its own and stops the post back. However, when I add JavaScript to enable the "next" button upon checking a checkbox, the required field validator will trigger when clicking ...

Scroll the div that is dynamically filled without affecting the scrolling of the main page

My current struggle involves using iScroll in my web project. The goal is to populate a list with articles and slide in a div over the list to display the selected article. While the basic functionality is in place, I face an issue where scrolling through ...

I am creating a website for online tutorials using react.js. Each course on the website is broken down into several subtopics. Is there a quicker way to write the code for this structure that I have created

I have a large number of import components (38 imports) and routes (38 routes) in my code. Is there a way to simplify these into fewer imports and routes? function App() { return ( <Router> <SideBar> <Routes> ...

What are the best practices for utilizing the createPages API to generate pages through programming?

In the process of developing my portfolio, I envisioned having distinct tabs for my blogs and projects. My goal was to dynamically generate pages for each item in these tabs. Following the Gatsby official tutorials, I successfully implemented this functio ...

Wrapper for Material UI - leverage TypeScript types for a specific property

Apologies if this question has been addressed previously as I was unable to locate an answer. Currently, the app I am developing utilizes a wrapper for certain material-ui components. For example, I have a MyCompanyButton component which acts as a wrapper ...

Tips for inserting a page break after every item in a loop in Visualforce when generating a PDF document

I need help with rendering a VF page as PDF. The VF page iterates over a list of account records using the repeat tag. I want to apply a page break for each element in the repeat tag. The code below is working, but it has an issue - it shows an empty PDF p ...

Are there any SVG libraries available that can create line graphs similar to those seen in Google Analytics?

The line graph in Google Analytics that is created using SVG is quite impressive. Are there any libraries available that can generate similar line graphs to those in Google Analytics? ...

Unable to transfer information from a PHP form to a MYSQL database when registering

Currently struggling to troubleshoot a piece of code that is not functioning as expected. I have all the necessary HTML, JS, and PHP in place, but after submitting the form, the data does not get sent to the SQL database as intended. Any assistance would b ...

Monitor the redux dispatch function

As a newcomer to jest, I am in the process of writing unit tests for my react application. This application utilizes redux and has been built using Typescript. Within my container component, I have the following code snippet: const mapDispatchToProps = ( ...

Excess space appearing at the right of my Next.js component

I'm currently diving into Next.js as I work on building out my portfolio. I have a solid foundation in HTML, CSS, and I've been honing my JavaScript skills through back-end development with Express.js. Check out this code snippet: export const W ...

JavaScript button with an event listener to enable sorting functionality

I am looking to implement a button that will reset all the filters on my page. Any ideas? Currently, I have multiple radio buttons for filtering items based on price, size, and color. My goal is to create a reset button that will remove all filters and r ...

Tips for Showing Websocket Response On Web Browser Using Node.js

Just starting out with NodeJS and here's my code snippet: const webSocket= require('ws'); const express = require('express'); const app=express(); Var url = "wss://stream.binance.com:9443/BTCUSDT@trade`" const ws = new webS ...

The Iframe is malfunctioning and not displaying properly

Thank you for the insights on header issues. I have a follow-up question: Is it possible to identify header problems that prevent me from displaying content in an iframe just by looking at the link? If so, can I display a different page for those problemat ...

Tips for preserving the value retrieved from a $http request when navigating back in the browser

In my application, I have a "search" button that retrieves an array of objects from a REST service. These values are then populated into a table using the ng-repeat directive. When a column is clicked, the page navigates to the next page with more details ...

Is there a way to pause the current page rendering process when moving to a different page?

In my Vuejs application, I have a page that displays many elements. While these elements are being rendered, I click on a link to navigate to another page. However, the navigation does not occur until the current page is fully rendered. Is there a way to ...

Instructions for utilizing the nav-pill with nav-justified components in Bootstrap3x without incorporating any responsive capabilities

I'm eager to incorporate this into my project : <div class="container"> <ul class="nav nav-pills nav-justified"> <li class="active"><a href="#">Home</a></li> <li><a href="#"> ...

Implementing a Material UI button within a stepper progress step

I am trying to create a clickable element that is visible within each step of Material UI's stepper at all times, not just when the step is active. Unfortunately, setting all steps to active is not an option due to UX reasons. Here's a snippet o ...

The data on the map is failing to display in React.js

I've managed to successfully retrieve data from an API and store it in a list. However, when I try to render the data using my return statement, nothing shows up on the screen even though the console.log displays the data correctly. The information is ...

When the button/link is clicked, I must dynamically create a modal popup that includes a user control

I am currently working on improving an asp.net web forms website by incorporating popup modals to display the rental rates for available equipment. The challenge arises when dealing with pages where each piece of equipment has different rates, requiring a ...