Set active regions on a country map on click and highlight them with color using JavaScript to improve map interactivity
Task:
Make the map active when clicked, highlight it with color, and maintain this state.
Solution:
This functionality is implemented using JavaScript. When you click on a region of the map, it becomes active, highlighted with color, and the state is preserved.
CSS code:
/* FOR MAP ON MAIN PAGE { */
.active-region {
fill: #000000 !important;
cursor: pointer;
}
/* } FOR MAP ON MAIN PAGE */
JavaScript code:
document.addEventListener("DOMContentLoaded", function () {
setTimeout(() => {
document.querySelectorAll('.imapsSprite-group.imapsContainer-group.imapsMapObject-group.imapsMapPolygon-group')
.forEach((element) => {
// Check if the element has the desired 'fill' attribute
if (element.getAttribute('fill') === '#ffed00') {
// Protection against adding event listeners multiple times
if (!element.dataset.listenerAttached) {
element.dataset.listenerAttached = 'true';
element.addEventListener('click', function () {
// Remove class from all
document.querySelectorAll('.imapsSprite-group.imapsContainer-group.imapsMapObject-group.imapsMapPolygon-group')
.forEach((el) => el.classList.remove('active-region'));
// Add class to the clicked element
this.classList.add('active-region');
// Output the region ID (uncomment if needed)
// console.log('Clicked region ID:', this.id);
});
}
}
});
}, 1500);
});
1