Activate lightbox on click to swap image source temporarily

I have implemented the Materialize CSS "Material Box" lightbox plugin, but I am facing an issue. I want all the thumbnails to be uniform in size, and when clicked, the full photo should be displayed.

Currently, I am using the onclick function to change the image source. However, I am unsure how to revert back to the thumbnail image once the large photo is closed (either by clicking or pressing the escape key).

<div class="col s6 m3">
    <img class="materialboxed responsive-img" src="images/thumb1.jpg" onclick='this.src="images/photo1"'>              
</div>

Here is the Material Box JavaScript code:

      document.addEventListener('DOMContentLoaded', function() {
        var elems = document.querySelectorAll('.materialboxed');
        var options = {}
        var instances = M.Materialbox.init(elems, options);
      });

      // Using jQuery

      $(document).ready(function(){
        $('.materialboxed').materialbox();
      });

You can find more information about Materialize CSS at

I have explored various options, but haven't found a straightforward way to achieve the desired lightbox effect with cropped square thumbnails. Any suggestions or tips would be greatly appreciated!

Answer №1

If you're looking for a solution to track the state of an image click, here is one example that may work for you.

$(document).ready(function(){
    $('.image-click').click(function(){
        // Image sources
        const thumbnail = '/images/thumb1.jpg';
        const fullImage = '/images/photo1.jpg';

        // Click state
        let clicked = false;

        $(this).attr('src', clicked ? fullImage : thumbnail);
        clicked = !clicked;
    });
});

Answer №2

There's no need to rely on the onclick event in this scenario. Materialize already takes care of binding onclick for those images. It offers native methods that can be used with pure JavaScript (no jQuery) to achieve exactly what you want:

onOpenStart Function null: Callback function called before materialbox is opened.

onCloseEnd Function null: Callback function called after materialbox is closed.

In the example below, let's assume there is a standard materialboxed photo gallery with thumbnails named thumb_whatever.jpg, while also serving the original-sized photo named whatever.jpg in the same directory.

We are dynamically changing the src attribute by removing the thumb_ prefix to display the original image, which will then immediately be lightboxed by Materialize.

After closing the lightbox, we set the src attribute back again without the thumb_ prefix.

This is achieved during the initialization of Materialbox:

// Initializing Materialbox
const mb = document.querySelectorAll('.materialboxed')
M.Materialbox.init(mb, {
  onOpenStart: (el) => {
    var src = el.getAttribute('src') // obtain the src
    var path = src.substring(0,src.lastIndexOf('/')) // extract the path from the src
    var fileName = src.substring(src.lastIndexOf('/')).replace('thumb_','') // get the filename and remove 'thumb_' prefix
    var newSrc = path+fileName // reassemble without the 'thumb_' prefix

    el.setAttribute('src', newSrc)
  },
  onCloseEnd: (el) => {
    var src = el.getAttribute('src') // obtain the src
    var path = src.substring(0,src.lastIndexOf('/')) // extract the path from the src
    var fileName = src.substring(src.lastIndexOf('/')).replace('/', '/thumb_') // get the filename and add 'thumb_' prefix
    var newSrc = path+fileName // reassemble with the 'thumb_' prefix
    
    el.setAttribute('src', newSrc)
  }
})

This approach works flawlessly for me across different platforms.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a variable in a for loop with Django

I am a beginner in the world of Python and Django framework and I am encountering a small hurdle when trying to assign a variable to my for loop. Within my html file, there are buttons and a list (generated through a loop). For example: Buttons <li&g ...

How can I create spacing between squares in an HTML div element?

Currently, I am working on my project using Laravel 5. I retrieve some integer values from a database and use them to create square divs in HTML. Below is the current output of my work. https://i.stack.imgur.com/sy2ru.png You may notice that there is spa ...

The utilization of useState can potentially trigger an endless loop

Currently, I am in the process of developing a web application using Next.js and Tailwind CSS. My goal is to pass a set of data between methods by utilizing useState. However, I have encountered an issue where the application loads indefinitely with excess ...

The Photoswipe default user interface cannot be located

While attempting to incorporate PhotoSwipe into my website, I encountered an uncaught reference error related to The PhotoswipeUI_Default is not defined at the openPhotoSwipe function Below is the code snippet that I have been working on: <!doctyp ...

Having difficulty retrieving items from Mongoose-Node database

I am currently working with a Mongodb database that stores resume objects. These objects contain various skills information and I have set up a node-express server to query the database based on specific skills. For example, when querying for a skill like ...

What is the destination for next() in Express js?

I'm new to javascript, nodejs, and express, and facing confusion with the usage of next(). I am trying to make my code progress to the next router using next(), but it seems to be moving to the next then instead. This is what my code looks like: // ...

Running cy.task after all test suites can be done by adding the task in a

I need some guidance on running cy.task after executing all test suites. I have a file generated at the start of the tests that I would like to remove once they are completed. Regardless of whether any tests passed or failed, I want to trigger cy.task im ...

Halt execution of routes using backbone.js

Is it feasible to halt route execution within backbone.js solely using the router? I understand there is a callback function for each route where I could verify if routing is permitted, but I am unsure how to prevent execution based on a property (such as ...

What is the best way to remove any objects in this array that have empty strings as values?

I have been developing a form using Angular 14. The form consists of a primary section, which includes the user's necessary information, and a secondary section where users can input additional data (an array of residences displayed in a table) befor ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

Can you explain the significance of the res.render callback parameter in Express 4.0 for Node.js?

Can you explain the role of the res.render callback argument? When would it be necessary to use this callback argument, especially when there is already a template specified as the first argument? The following code snippet is taken from the official doc ...

Troubleshooting Angular 2: Instances of Classes Not Being Updated When Retrieving Parameters

I am facing an issue with the following code snippet: testFunction() { let params = <any>{}; if (this.searchTerm) { params.search = this.searchTerm; } // change the URL this.router.navigate(['job-search'], {q ...

mention a numerical value/heading within a JSON list

I encountered an issue while searching through a JSON array filled with Google fonts. The fonts are structured by family -> files -> filename. However, I noticed that sometimes the filename is saved as a number. For example (refer to the bottom of th ...

Headers error encountered during sending request

When making a request with this method, an error labeled as "[ERR_HTTP_HEADERS_SENT] Cannot set headers after they are sent to the client" occurs. I recently started learning about express and might have made some progress. Can you please help me identif ...

Error Message "Alexa.create is not a valid function" encountered while using the Alexa HTML Web API on the Echo Show 10

Here is the HTML code for my custom Alexa Skill. <head> <script src="https://cdn.myalexaskills.com/latest/alexa-html.js"> </script> </head> <body> var alexaClient; Alexa.create({version: '1.0'}) .t ...

Difficulty encountered while executing JavaScript in Chrome 78 with Python and Selenium, as pages are not switching

I have encountered an issue with my script that switches between site pages containing tables. Everything was working smoothly for months with Chrome version 76, but after updating to the new Chrome version 78.0.3904.70, an error has arisen: driver.execu ...

The tooltip popup does not appear within the nz-tabs

Looking to enhance my two tabs with an info icon preceding the tab text, along with a tooltip popup that appears when hovering over the icon. Despite trying different methods, I have yet to achieve the desired outcome. <nz-tabset [nzLinkRouter]=&qu ...

FullCalendar jQuery caught in an endless loop

After successfully implementing drag and drop deletion, I encountered a new issue. Whenever I delete an event, the removal process functions properly but then the code gets stuck in a loop within the eventDragStop function causing the calendar to freeze ...

Transferring data from AJAX to PHP class methods

Q. Is it feasible to transfer data from ajax to a specific php class with functions? For instance, verifying a username on the registration form to check if the user already exists. This form is straightforward and will gather a username input along with ...

I encountered an error message stating "Unexpected token {" while trying to import the module "express-fileupload"

Struggling to implement file uploading with NodeJS on Ubuntu, encountering errors. Upon adding const fileUpload = require('express-fileupload'); the app fails to compile, throwing this syntax error: 2|theproje | /home/asgeir/nodejs/first_test ...