Display a modal pop-up containing HTML content

I recently started building a small website using Zurb Foundation. I have created a basic grid layout with large metro style div thumbnails (about 10 on the page).

Now, I want to enhance user interaction by implementing modal windows that appear when a thumbnail is clicked. These modals will display more information about the item clicked, similar to image gallery lightbox plugins.

I am debating between two approaches for achieving this functionality. Should I store the content for the modals in a separate HTML file and load them via AJAX on click? Or should I simply hide and show sections of content on click?

The content inside each modal will vary, containing project names, videos, images, descriptions, etc. I want to find a solution that can be easily applied to all thumbnails without needing individual handlers for each one.

Answer №1

To streamline the process, consider storing dialogues in a separate file and utilizing ajax for loading when prompted by the user. This method enhances organization and simplifies management tasks.

Storing html in hidden divs may result in resource wastage since not all dialogues will be accessed during page load. It can also lead to code maintenance issues if updates are required in both the hidden div section and an external file.

For optimal efficiency, centralize all html content within a php class/function or utilize a php MVC framework for easy integration. By doing so, updates only need to be made in one location to reflect changes site-wide. Additionally, leverage AJAX loading with JSON format to incorporate variables like external scripts, CSS files, and status indicators for organized coding practices.

Answer №2

Below is a self-contained illustration. Upon execution, please pay attention to the following:

  • Make sure to load jQuery/jQueryUI libraries within the <head> tags
  • Determine which image was clicked by: (1) triggering a click event whenever an element of the img class is clicked, and (2) extracting that specific img's ID using jQuery
  • Utilize AJAX to transmit the image ID to the PHP processor file
  • The PHP processor file performs certain actions and returns a result
  • The response from PHP is retrieved within the AJAX success function. All operations involving the received data (from PHP) MUST occur inside the success function, including invoking the JQUI dlg
  • The JQUI dlg initiates as an empty DIV in TEST.PHP, which gets populated with markup within the AJAX success function:
    $('#dlgID').html(data_received_from_PHP);
  • Remember to close the JQUI dlg upon clicking the OK button (alternatively, this command can be placed in the close: section of the JQUI dlg)

To run this straightforward example, two files are required:

File 1: TEST.PHP

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/jquery-ui.min.js"></script>
        <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />

        <style>
        </style>

        <script type="text/javascript">
            $(document).ready(function() {

                $('.img').click(function() {
                    var iid = $(this).attr('id');
                    //alert('You clicked ID: ' + iid);
                    $.ajax({
                        type: "POST",
                        url: "yogibear.php", // "source.php",
                        data: "iid="+iid,
                        success: function(data) {
                            //alert('AJAX recd: ' +data);
                            $('#moddlg').html(data);
                            $('#moddlg').dialog('open');
                        } //END success fn
                    }); //END $.ajax

                });
                $('#moddlg').dialog({
                    autoOpen: false,
                    modal: true,
                    width: 400, //default is 300
                    title: 'This is yer dialog:',
                    buttons: {
                        'Click Me': function() {
                            $(this).dialog('close');
                        }
                    },
                    close: function() {
                        alert('Dlg is closing... I can do more stuff in here, including running another AJAX call');
                    }
                });

            }); //END $(document).ready()

        </script>
    </head>
<body>

    <img id="i-1" class="img" src="http://placehold.it/140x100" />
    <img id="i-2" class="img" src="http://placehold.it/140x100" />
    <img id="i-3" class="img" src="http://placehold.it/140x100" />
    <img id="i-4" class="img" src="http://placehold.it/140x100" />
    <div id="moddlg"></div>

</body>
</html>

File 2: YOGIBEAR.PHP

<?php
    $x = $_POST['iid'];
    die('PHP file recd: ' . $x);
    //Of course, this is where you receive the img id sent via AJAX
    //and look up stuff in MySQL or etc, then return the results
    //simply by putting it all into a variable and ECHOing that
    //variable. Or, you can use JSON to echo an array - but make
    //sure to look up a couple of examples as you must add another
    //couple of params to the AJAX code block

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

Creating resizable SVG elements using HTML or CSS for dynamic width and height

Is there a way to give my SVG element dynamic width and height in order to display the entire SVG image? For example, take a look at this CodePen link. <svg width="250" height="250" viewBox="0 0 250 250"> Alternatively, .svg { width : 250px; ...

Issue with three.js memory leak due to malfunctioning .dispose() method or incorrect usage

Greetings! I'm currently facing a memory handling issue. Despite researching various forums, I am still unable to identify the problem in my code. My project involves combining d3.js with three.js to create a visualization of nodes resembling planet ...

Combining Two Collections in Mongoose using Node.js

As a beginner in MEAN Stack, I am currently working on a Node Js application. I have created two collections: var personSchema = Schema({ _id: Number, name: String, age: Number, stories: { type: Array, ref: 'Story' } }); va ...

What is the most efficient way to update a specific element in a redux/vuex store?

What is the most efficient way to update an element(hash) in a list within a store (redux, vuex) using O(1) complexity? The order of the elements must be maintained as I will be adding/removing elements frequently. Updates will occur every millisecond, re ...

Are there any methods to utilize Zod for validating that a number contains a maximum of two decimal places?

How can I ensure that a numeric property in my object has only up to 2 decimal digits? For example: 1 // acceptable 1.1 // acceptable 1.11 // acceptable 1.111 // not acceptable Is there a method to achieve this? I checked Zod's documentation and sea ...

Display or conceal specific fields depending on the selection from a dropdown menu

I'm currently experimenting with using JavaScript and/or jQuery to dynamically hide specific HTML elements based on the selection in a drop down menu. Here is what my page setup looks like: [Drop down menu] [text field 1] [text field 2] [text field ...

I am unable to save the data received from the payment API

I've been working on developing an e-commerce system, but I'm facing an issue with the iyzipay payment API. Although I successfully make a request and receive a response from the server, I'm unable to store the data that comes back. Can anyo ...

Guaranteeing the sequential execution of JavaScript functions

For weeks, I've been struggling with a program that utilizes ajax post methods and dataTables. It has become clear to me that my understanding of how javascript operates is lacking. Below is the javascript code: $('#SaveTimeSheet').click(fu ...

How to incorporate Bootstrap carousel into WordPress without relying on a plugin?

I've successfully integrated the bootstrap carousel into my Wordpress site. The slides are sourced from pages, with a specific page called "carousel" containing subpages where post-thumbnails are extracted. I'm still learning the ropes of using W ...

A guide on switching the status of various inputs in a table based on the selection of a radio button

In the scenario below, let's consider the following HTML structure: <tr> <td> <label for="c1_testRdio">Have you taken any tests in this class?:</label> <br> <label>Yes<input type="rad ...

Arranging fixed-width <div>s in rows of four for a sequential display

Below is the code that I am working with: <div style="margin: 0 auto; display:block; width: 916px; overflow: auto;"> <?php echo ""; echo "<i>Owned: $line->phone </i><br><br>"; $query ...

Is there a way for me to receive user inputs, perform mathematical operations on them, and then display the result of the calculation? Additionally, is there a way to ensure that the output value automatically updates

As a newcomer to HTML and JavaScript, I'm unsure how to approach this task. Here is what I have so far: <div class="inputs"> <label for="#arena2v2">2v2 Arena Rating:&#9;</label><input class="pvp" type="number" step="1" m ...

What is the best way to align a text element to the right and a PNG element to the left within a

I am currently working on setting up a navigation bar with a PNG link in the top left corner, and a text element "menu" in the top right corner. Despite my efforts, I have not been successful in achieving this layout using "float: right;" The code snippet ...

Vertically align all items within the div using Bootstrap to achieve perfect centering

I've been working on centering everything within this div vertically, and I've encountered some challenges along the way. Initially, I ensured that my background view extends my container nicely across the screen. Now, I'm looking to create ...

Recognize different HTML components when an event occurs

My application is equipped with a multitude of buttons, inputs, and other elements that trigger different events. I am looking for a way to easily differentiate between each element and the event it triggers. For instance, consider the following snippet f ...

Tips for distinguishing between the different values

Greetings! I am currently utilizing this code snippet to retrieve values from a Java class. Upon getting the data from Java, it triggers an alert displaying two values separated by spaces. My next goal is to split the values into two separate entities an ...

Employing promises for retrieving ajax data

I've been struggling to make sure my code waits for an ajax call to finish before proceeding, as I need data in an array first. No matter what I try, it seems like promises might be the best solution in this scenario. Currently, the ajax call still oc ...

Selecting list items using the up and down keys in JavaScript/jQuery

As the search terms dynamically populate a list of items, I am looking for a way to make the list items selectable/focused using the up/down keys and hide the dropdown with ESC key. <form> <div> <div class="field"> & ...

Encountering Difficulty Accessing Index.ejs with Express.js

Currently, I am enrolled in a Linkedin course that focuses on building websites using express.js. I have encountered an issue where my index.ejs page is not rendering properly, as the server keeps loading my index.html page instead. I have tried searching ...

Vue JS causing page to flash briefly before disappearing

I recently started exploring Vue and I'm working on creating a basic search function that takes a user input query and displays all matching users. To help me with this, I've been following a video tutorial for guidance. Despite not encounterin ...