I’m new to HMTL and I have been stuck on this problem. Say, I have these divs that the same class name and the only thing that differs them is the ID.
How do I make it so that they will display the right popup content upon being clicked? Since these popups share the same class name, only "you clicked the first button" is displayed no matter what I click.
I know this is very wrong but I still don’t understand how to use IDs.
.button {
width: 200px;
height: 200px;
background-color: yellow;
margin-bottom: 100px;
}
.popup {
display: flex;
position: fixed;
width: 0;
height: 100%;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.5);
align-items: center;
justify-content: center;
z-index: 200;
overflow-x: hidden;
}
<div class="button" id="1" onclick="openPopup()">fgdjgdfjgfk
<div class="popup">you clicked the first button</div>
</div>
<div class="button" id="2" onclick="openPopup()">abc
<div class="popup">you clicked the second button</div>
</div>
<script>
function openPopup() {
document.querySelector(".popup").style.width = "100%";
}
</script>
3
Answers
Based on your HTML structure, you can select the popup content inside the clicked element.
You should add the custom popup message to each div
Then in your button handler, you should get the message to display from the element attribute. So
Note: Setting the title field is a built in way to show a popup
The CSS selector to access an element by id is
#id
. Note that an id cannot start with a numerical character. I would also useelement.addEventListener
rather than setting attributes in HTML.I have made a code snippet to help you understand.