'Access the html location of all elements from a database with javascript
I display elements from a database with php and my goal is to change the style of the html tags that contain them, when hovering over them with javascript. But the problem is that it works only for the first element displayed. As if the other elements didn't have the same tag class for javascript.
here is code html and php :
<div class="eventsContainers">
<?php
foreach($eventsInfo as $eventInfo)
{
if($eventInfo['pseudo_author'] == $_SESSION['pseudo'])
{?>
<div class="event" align="center">
<div class="headerEvent">
<div class="ppEventContain">
<p><?php echo $eventInfo['title']; ?></p>
<div class="eventDateRegister">
<p><?php echo $eventInfo['paragraphe']; ?></p>
</div>
</div>
</div>
Here is code css:
.eventsContainers
{
background-color: black;
width: 100%;
display: flex;
flex-direction: column;
align-items: center;
}
.event
{
background-color: white;
border-radius: 10px;
width: 50%;
display: flex;
flex-direction: column;
padding-bottom: 10px;
border: 1px solid #848484;
margin-top: 5px;
}
Here is code js:
const event = document.querySelector(".event");
event.addEventListener("mouseover", extendEvent)
function extendEvent()
{
event.style.position = 'absolute';
event.style.width = "28%";
}
here is the source code that it gives:
<div class="event" id="event1 align="center">...</div>
<div class="event" id="event2 align="center">...</div>
<div class="event" id="event3 align="center">...</div>
<div class="event" id="event4 align="center">...</div>
<div class="event" id="event6 align="center">...</div>
<div class="event" id="event7 align="center">...</div>
<div class="event" id="event8 align="center">...</div>
By doing an "event:hover" in the css only id="event1" will react to the event and will have a width = 28% and a position = absolute. With my method they all react to the hover except that again only 1 element has width = 28% and position = absolute. This time it is the last element, id="event8".
Of course it would be much easier if I could know the id of the elements but as the class element can be infinite then it's complicated.
Solution 1:[1]
The way you're doing this is extremely convoluted and definitely not recommended. Instead, please use the CSS hover selector and change your styling directly with CSS. This will also be much more performant than manually adjusting styles with JavaScript. In your case, the stylesheet would look like this:
.event {
background-color: white;
border-radius: 10px;
width: 50%;
display: flex;
flex-direction: column;
padding-bottom: 10px;
border: 1px solid #848484;
margin-top: 5px;
}
.event:hover {
position: absolute;
width: 28%;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | micahlt |
