Skip to content

Instantly share code, notes, and snippets.

@david-mears-2
Last active November 7, 2023 14:53
Show Gist options
  • Save david-mears-2/a96ff2d0f4a93f03b25901fc6747eb96 to your computer and use it in GitHub Desktop.
Save david-mears-2/a96ff2d0f4a93f03b25901fc6747eb96 to your computer and use it in GitHub Desktop.
console.log('Running script hosted at https://gist.github.com/david-mears-2/a96ff2d0f4a93f03b25901fc6747eb96')
// Create the div element with the specified HTML
const modalDiv = document.createElement('div');
modalDiv.id = 'team-modal--modal';
modalDiv.className = 'team-modal--modal';
modalDiv.innerHTML = '<div class="team-modal--content"><p>Content</p><span class="team-modal--close">×</span></div>';
// Find an existing element to append the new element to
// For example, you can append it to the body element
const body = document.body;
// Append the newly created element to the body
body.appendChild(modalDiv);
const modal = document.getElementById('team-modal--modal');
const modalContentP = modal.querySelector('.team-modal--content p');
const teamImages = document.querySelectorAll('#team img');
const teamParagraphs = document.querySelectorAll('#team p');
// Initially hide all elements within #team
teamParagraphs.forEach(p => p.style.display = 'none');
// Loop through each image and add click event
teamImages.forEach(img => {
img.addEventListener('click', function() {
// Find the uncle/aunt for the clicked image (assuming they are contained within the same parent container)
const parentElement = img.parentElement;
let uncleOrAuntP = null;
// Look through the siblings of the parent element to find a element
let nextElement = parentElement.nextElementSibling;
while(nextElement) {
if(nextElement.tagName.toLowerCase() === 'p') {
uncleOrAuntP = nextElement;
break; // Found the element, exit loop
}
nextElement = nextElement.nextElementSibling;
}
if(uncleOrAuntP.innerHTML) {
// Set the text of the modal's to the text from the sibling
modalContentP.innerHTML = uncleOrAuntP.innerHTML;
// Show only the current in the modal
modalContentP.style.display = 'block';
// Display the modal
modal.style.display = "block";
}
});
});
// Get the <span> element that closes the modal
const span = document.getElementsByClassName("team-modal--close")[0];
// When the user clicks on <span> (x), close the modal and hide the modal's
span.onclick = function() {
modalContentP.style.display = "none"; // Hide the element when modal is closed
modal.style.display = "none";
}
// Also close the modal when user clicks anywhere outside of the modal content
window.onclick = function(event) {
if (event.target == modal) {
modalContentP.style.display = "none"; // Hide the element when modal is closed
modal.style.display = "none";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment