Adjust the CSS of a different class when the :focus state is triggered

Imagine you have the following code snippet:

HTML

<div class="container">
   <input class="myAwesomeInputBox">
</div>

CSS

.input [type=text]:focus > .//ANY CLASS SOMEWHERE ON THE WEBSITE{
   //Some sweet CSS.
}

This code does not work as expected. I am looking for a way to apply specific CSS styles when focusing on my input box. Is there any way to achieve this?

I'm open to solutions beyond just html/css. Any approach that can accomplish this task is appreciated.

The above code is just a basic example. My question is straightforward - Can we alter the styling of ANY element on a website using the :focus pseudo-class on an input box?

Answer №1

Utilizing pseudo-classes like :hover or :focus to modify different elements is limited to siblings or children of the element with the pseudo-class. This limitation is due to the constraints of CSS child/sibling selectors.

To target a direct child, use the > selector and for a direct sibling, use the + selector. For instance, consider the following HTML example:

<form>
    <input type="text" />
    <input type="submit" />
</form>
<p class="arbitrary">
    This paragraph is not a child or sibling of the text field. It cannot be styled through CSS pseudo-classes but can be targeted using client-side scripting like JavaScript.
</p>

You can style the submit button when the text field is focused (as they are direct siblings), but styling the arbitrary paragraph based on focus of the text field isn't possible through CSS alone (since it's neither a child nor sibling, rather a sibling of their parent) without resorting to client-side scripting like JavaScript or jQuery.

The following CSS snippet demonstrates styling the submit button, which can be adjusted to target any direct or indirect child or sibling:

input[type="text"]:focus + input[type="submit"] {
    /* some cool CSS rules */
    background-color: green;
}

JavaScript allows much more flexibility. The focusin and focusout events enable toggling CSS classes. Here's an example showcasing both CSS and JavaScript methods:

function setFocused() {
  document.querySelectorAll('.arbitrary').forEach((result) => {
    result.classList.add('focused');
  });
}

function unsetFocused() {
  document.querySelectorAll('.arbitrary').forEach((result) => {
    result.classList.remove('focused');
  });
}

document.querySelectorAll('input[type="text"]').forEach((result) => {
  result.addEventListener("focusin", setFocused);
  result.addEventListener("focusout", unsetFocused);
});
input[type="text"]:focus + input[type="submit"] {
  /* some nice CSS */
  background-color: green;
}

.arbitrary.focused {
  /* more nice CSS */
  color: red;
}
<form>
  <input type="text" />
  <input type="submit" />
</form>

<p class="arbitrary">
  This paragraph is neither a child nor sibling of the text field. It cannot be styled by CSS pseudo-classes but can be selected using
  client-side scripting such as JavaScript.
</p>

If you prefer working with jQuery, here's the jQuery equivalent of the code above:

$('input[type="text"]').on('focus', function() {
    $('.arbitrary').addClass('focused');
});

$('input[type="text"]').off('focus', function() {
    $('.arbitrary').removeClass('focused');
});

For similar functionality using a "hover" trigger instead of "focus," you can utilize JavaScript's mouseover and mouseout functions, or jQuery's .hover() function with separate handlers for hover in and out actions.

Answer №2

Perhaps consider including an ID

<div class="container">
   <input class="myAwesomeInputBox" id='myAwesomeId' type="text">
</div>

Furthermore, you can add or remove a class in this manner. Do you think this approach could resolve your issue?

$('#myAwesomeId').on({
    focus: function () {
        $(this).addClass('focused');
    },

    blur: function () {
        $(this).removeClass('focused');
    }
});

CSS

input.focused {
    border:3px solid blue;
}

FIDDLE

Answer №3

If you want to change the css of a sibling element, you can achieve it using the following code snippet:

        <div class="container">
           <input class="myAwesomeInputBox">
           <div className="dls-sibling">
        </div>

        
  .myAwesomeInputBox:focus ~.dls-sibling {
        &::before {
            transform: scale(1);
            border-color:red;
       
  }
}

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

Having trouble with updating AngularJS?

I am facing an issue while updating the guitar object in my AngularJS application. The operation is performed using the updateGuitar controller with ngMock backend. After updating the guitar object, the put request is processed by the carService. However, ...

Is there a way to eliminate the additional gap found at the bottom of a div element?

I've been encountering some difficulty when trying to insert an image into a div without any padding. The issue I'm facing is that the sizing doesn't seem to be correct; there's unnecessary extra space at the bottom. Despite my efforts ...

How to Properly Manipulate DOM Elements in an Angular Directive

My directive, powerEntry, has different CSS classes that I want to add or remove based on the model state. Currently, in my link function, I have some logic like this: Script.JS if (calcState.availablePoints > 0 && isHighEnoughLevel) { ...

Extract specific data points from external API responses on a webpage crafted in HTML

I require assistance on how to extract individual values from an HTML page. I received a response from the PAYU payment gateway team in HTML format, but I need to retrieve specific attribute values related to the transaction details. Below is the response ...

Utilizing jQuery to determine the placement of a tooltip within a slider

I am currently utilizing both a jQuery Tooltip and a jQuery Slider (jQueryUI) simultaneously. While the slider is functioning correctly, I am encountering an issue where tooltips are being displayed in the wrong position after scrolling (view screenshot or ...

Is it possible for a typo3 website to automatically redirect users to a mobile-friendly version?

I have put together a landing page for my website with numerous content elements using only HTML and then pasted it into my typo3 backend. I ended up with separate HTML codes for desktop view and mobile view because I couldn't figure out how to make t ...

The iPad Overlay fails to fully extend across the screen

I have implemented a modal div as an overlay to disable the background page while the overlay DIV is open. Below is the code I am using: #TB_overlay { height: 100%; left: 0; position: fixed; top: 0; width: 100%; z-index: 100; } Al ...

Understanding the concept of displaying labels even when the field is empty in React

One issue I am facing is with a label that displays a string from a text input filled in by the user. The string is saved in a variable called question and shown as: <label className={css('form-title-label')}> {question} </label ...

Utilizing an undefined constant in angular programming may lead to unexpected errors

Seeking assistance in generating random first and last names based on gender for a form using Angular. I am relatively new to Angular and keep encountering this error whenever the Use of undefined constant firstName - assumed 'firstName' Here ...

Difficulties arise when attempting to display an input within a Bootstrap modal

Upon clicking an icon, I aim to display a bootstrap modal prompting the user to input text and a date. I have adapted code from W3Schools to create the necessary form. Unfortunately, when the button is clicked, only the labels and text area are shown, not ...

Mobile device causing issues with sticky footer functionality

Can anyone help me troubleshoot an issue with my sticky/floating bottom footer on a calorie calculator? It works fine on desktop but not on mobile. Any ideas what might be causing the problem? HTML: <footer class="footer"> <div class="summar ...

I'm wondering how I can design a utility function within my Redux module that can extract a specific subset of read-only data from the current state

I am currently utilizing redux to create a "helper function" inside my redux module that is responsible for fetching filtered data from the state based on a specified index. This specific data will be used to generate a form consisting of inputs depending ...

Toggle two elements simultaneously by clicking on one of them - displaying one element while hiding the other

I am facing an issue with toggling the visibility of two divs using a button click event. One div is initially hidden with a display property set to none, while the other div is visible. My goal is to have this behavior toggle on each click event - the fi ...

The color of the button in HTML5 will remain constant and not shift

I have several buttons that function like radio buttons - only one can be selected at a time: <button id="btn-bronze" name="btn-bronze" type="button" class="blue-selected">Bronze</button> <button id="btn-silver" name="btn-silver" type="butt ...

Python executing Javascript code syntax

I am currently working on a project where I need to execute javascript code within Python, but I seem to be running into syntax issues. It seems like the problem lies with the use of single and double quotation marks. Here's a more detailed explanati ...

Creating Dynamic Graphs Using Vanilla JavaScript

My web application is in need of dynamic charts and graphs. I've come across HighCharts in pure javascript, but it's not free for SAAS apps. Are there any other reliable, free, pure-javascript chart solutions available that I can use right away ...

What could have occurred if you reassigned setInterval to a variable within the useEffect hook?

Can multiple setInterval functions be defined repeatedly to the same variable in a React hook useEffect? After checking, I found that the variable has a new setInterval id value every time it is defined. However, I am curious if there are any instances re ...

Unable to retrieve data from my json file in React

I have successfully created a menu with a submenu and a third child element. Initially, I had hard-coded the data in a local constant called json, which is now commented out. However, I am facing an issue as I now need to fetch the data from my JSON file b ...

Moving the mouse over a div will alter the heading of another div

Trying to find a solution for a unique problem. I have 5 boxes and need to style one box with a different heading color. As I hover over the other 4 boxes, I want the active box heading to change to a new color. The color should remain even after moving th ...

Is there a way to retrieve just the parent's value?

<div class="island biz-owner-reply clearfix"> <div class="biz-owner-reply-header arrange arrange--6"> <div class="arrange_unit biz-owner-reply-photo"> <div class="photo-box pb-30s"> <a hre ...