sinanisler logo

Simple Native Popup, NoLib, CSS, JS

Simple Native Popup, NoLib, CSS, JS

if z-index problem happens just put he html part higher in the dom list. like right after the <body>

<!-- Example buttons -->
<button class="button-1">Open Popup 1</button>
<button class="button-2">Open Popup 2</button>
<!-- ... -->

<!-- Example popups -->
<div class="overlay post-popup-1">
    <div class="popup">
        <button class="close-btn">X</button>
        <p>Content for Popup 1</p>
    </div>
</div>

<div class="overlay post-popup-2">
    <div class="popup">
        <button class="close-btn">X</button>
        <p>Content for Popup 2</p>
    </div>
</div>
<!-- ... -->

<style>
.overlay {
    display: none;
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    /* background: rgba(0, 0, 0, 0.5); */
    z-index: 1;
}

.popup {
    position: fixed;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    background-color: white;
    padding: 20px;
    border-radius: 10px;
    z-index: 2;
    width: 80vw;  
    height:80vh;
    box-sizing: border-box;   
}

.close-btn {
    position: absolute;
    top: 10px;
    right: 10px;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 24px;
}

.close-btn:focus {
    outline: none;
}
</style>
<script>
// Get all buttons with a class that starts with "button-"
const buttons = document.querySelectorAll('[class^="button-"]');

for (const button of buttons) {
    button.addEventListener('click', function() {
        // Extract the ID from the button's class
        const id = button.className.split('-')[1];
        
        // Use the ID to find and display the corresponding popup
        document.querySelector('.post-popup-' + id).style.display = 'block';
    });
}

// Close functionality
const closeButtons = document.querySelectorAll('.close-btn');

for (const closeButton of closeButtons) {
    closeButton.addEventListener('click', function() {
        // Find the closest overlay (which is the parent of the popup) and hide it
        closeButton.closest('.overlay').style.display = 'none';
    });
}
</script>

Leave the first comment