Skip to main content
Practice

Modal Behavior and Interaction

Let's explore how to implement modal behavior and interaction using JavaScript.


Basic Operational Principles

The basic operational principle of a modal is to control its display property, making it visible or hidden to the user. Initially, it is set to display: none;, meaning it is not displayed on the screen.


Show/Hide Modal Using Display Property

You can show or hide a modal by toggling its display property between block and none using JavaScript.

const modal = document.getElementById('modal');

// Show modal
modal.style.display = 'block';

// Hide modal
modal.style.display = 'none';

Enlarge Button Functionality

When the enlarge button is clicked, the size of the modal content is increased.

This can be achieved by adding or removing a specific class (e.g., full).

const sizeBtn = document.querySelector('.size-btn');

sizeBtn.addEventListener('click', function () {
modalContent.classList.toggle('full');
});

Style Changes When Enlarge Button is Clicked

When the full class is applied, the modal content expands to cover the entire screen, and other styles such as background color are adjusted.

CSS
.modal-content.full {
width: 100vw;
height: 100vh;
background-color: transparent;
}

Animation and Transition Effects

To enhance user experience, smooth transition effects are applied when the modal is displayed.

Fade-in and scale effects for the modal: The modal content gradually appears and scales up.

CSS
@keyframes modalContentFadeInScale {
from {
opacity: 0;
transform: scale(0.7);
}
to {
opacity: 1;
transform: scale(1);
}
}

.modal-content {
animation: modalContentFadeInScale 0.3s ease;
}

A shimmering effect is applied to the close icon.

CSS
@keyframes shimmer {
0% {
background: #e6e6e6;
}
50% {
background: #f2f2f2;
}
100% {
background: #e6e6e6;
}
}

.close-img {
animation: shimmer 1.5s infinite;
}

Want to learn more?

Join CodeFriends Plus membership or enroll in a course to start your journey.