I would like to attach a focus event listener to 1. element and when it fires, then 2. element border will be red.
The 1. element is inside of 2. element.
The problem: I cannot attach to the 1. element the event listener because the 1. element does not exists when javascript / jqeury executes.
Why? The 1. 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 worked, because .ready fires too early. The 1. element loads long after .ready fires (the javascript / jQeury 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 2. element is inside the 1. element or they are siblings. In my case the 2. element is outside of the 1. element, so I cannot use CSS. What do you think?
CodePudding user response:
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>
CodePudding user response:
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>