John
John

Reputation: 83

Affecting another outside element using CSS

I would like to attach a focus event listener to the first element and when it fires, then second element border will be red.

The first element is inside of the second element.

The problem: I cannot attach the event listener to the first element, because it does not exist when javascript / jQuery executes.

Why?: the first element loads long after the page loads because I use long poll on my website.

Because of this, I tried to use jQuery .ready method, but it did not work, because .ready fires too early. The first element loads long after .ready fires (the javascript / jQuery executes still too fast).

After this I tried to use CSS (CSS does not cares if elements exists or not, it works when the element loads after CSS loads), but I found only this: How to affect other elements when one element is hovered

In the previous page the solution can be made with CSS only when second element is inside the first element or they are siblings. In my case the second element is outside of the first element, so I cannot use CSS. What do you think?

Upvotes: 0

Views: 235

Answers (2)

A Haworth
A Haworth

Reputation: 36563

If your structure allows then it can appear to be done with just CSS.

The requirement is that the outer element can be given a position but that the inner element and any intervening elements are not positioned.

That way a pseudo before element on inner can take on the dimensions of outer and thus provide the border.

.outer {
  width: 50vmin;
  height: 50vmin;
  background-color: lime;
  position: relative;
  padding: 0;
  margin: 0;
}

.inner {
  width: 30vmin;
  height: 30vmin;
  background-color: cyan;
  margin: 0 auto;
}

.inner:hover::before {
  content: '';
  position: absolute;
  width: 100%;
  height: 100%;
  border: solid 5px red;
  top: -5px;
  left: -5px;
  padding: 0;
  margin: 0;
}
<div class="outer">
  <div class="inner">Hover over me</div>
</div>

Upvotes: 1

FHJTDSDG
FHJTDSDG

Reputation: 98

This should give you an idea.

You can access the parent element in JS with .parentNode

You should add this JS to your website, and when you create the "first" element, give it these: onfocus="parentStyle(this)" and onblur="parentStyleBack(this)".

let bf;

function parentStyle(el) {
  parent = el.parentNode;
  bf = parent.style.border;
  parent.style.border = "2px solid #FF0000";
}

function parentStyleBack(el) {
  parent = el.parentNode;
  parent.style.border = bf;
}
#outside {
  width: 300px;
  height: 150px;
  display: flex;
  align-items: center;
  justify-content: center;
}

#inside {
  width: 120px;
  height: 20px;
}
<div id="outside">
  <input id="inside" onfocus="parentStyle(this)" onblur="parentStyleBack(this)" placeholder="Click here to focus">
 </div>

Upvotes: 1

Related Questions