I am currently developing a Twitter fetcher application and have encountered some issues with the scrolling functionality, particularly due to oversized images. I would like to implement image restrictions similar to what Twitter uses.
https://i.sstatic.net/XjdhX.png
However, I am unsure of the best approach to achieve this. My current strategy involves building a lightbox where images with a specific class are displayed, and then adding the class dynamically using JavaScript. Is there a simpler method to accomplish this task?
Although I have made progress in implementing this solution, I am facing difficulties in enabling the ability to close the lightbox by clicking anywhere on the screen. Currently, the close button functionality appears to be malfunctioning.
Below is the HTML code snippet:
<!-- empty div for twitter fetch -->
<div id="config"></div>
<!-- lightbox popup modal -->
<div class="lightModal">
<div class="lightModal-inner">
<button class="lightModal-close" role="button">×</button>
<h3 class="lightModal-title">Title here</h3>
<img class="lightModal-image" src="http://placehold.it/350x150" alt="Title here">
</div>
</div>
JavaScript Code:
// Lightbox
// Get all links
var links = document.querySelectorAll('.lightCustom'),
// Convert NodeList to array
arrayOfLinks = Array.prototype.slice.call(links);
// Loop through each link
Array.prototype.forEach.call(arrayOfLinks,function(obj,index){
// Open modal on click
obj.addEventListener('click',function(e){
e.preventDefault();
// Check if title exists or display 'No Title'
var title = (obj.title) ? obj.title : 'This does not have a title';
// Add 'show' class to display modal
document.querySelector('.lightModal').classList.add('show');
// Display title in the modal header
document.querySelector('.lightModal-title').innerHTML = title;
// Get image URL from link and set it in the modal
document.querySelector('.lightModal-image').src = obj.href;
// Set title as alt attribute for the image
document.querySelector('.lightModal-image').alt = title;
});
// Close modal
document.querySelector('.lightModal-close').addEventListener('click',function(e){
e.preventDefault();
// Remove 'show' class to hide modal
document.querySelector('.lightModal').classList.remove('show');
// Reset title content
document.querySelector('.lightModal-title').innerHTML = '';
// Reset image source
document.querySelector('.lightModal-image').src = '';
// Reset image alt text
document.querySelector('.lightModal-image').alt = '';
});
});
If you want to view a Working CodePen example, feel free to check it out.
Your assistance is greatly appreciated. Thank you!