What is the best way to display various dialogs based on the specific button that is clicked?

Starting a new project, I foresee the need for numerous dialog boxes and modals.

I've come up with some basic code that displays the dialog when a button is clicked and hides it when the cancel button is pressed.

However, I'm facing the issue of duplicating the code for every single dialog ID. Is there a way to streamline this process using a script that references a href value or assigns an ID to the a tag?

Alternatively, is there a more efficient method of accomplishing this task?

Below is my current code:

HTML:

<a id="create">New</a>

<a id="edit">Edit</a>



<div class="overlay"></div>


<div class="dialog" id="create-new-dialog">
    <header>
        <h1>Create New</h1>
    </header>

    <div class="dialog-content">
        <p>I am some content info</p>
    </div>

    <footer>
        <div class="inner-container">
            <p></p>
            <a id="exit" class="btn-dark-outline dialog-btn cancel">Cancel</a>
        </div>
    </footer>
</div>


<div class="dialog" id="edit-dialog">
    <header>
        <h1>Edit</h1>
    </header>

    <div class="dialog-content">
        <p>I am some content info</p>
    </div>

    <footer>
        <div class="inner-container">
            <p></p>
            <a id="exit" class="btn-dark-outline dialog-btn cancel">Cancel</a>

        </div>
    </footer>
</div>

CSS:

a {
    background:lightpink;
    padding:20px;
    cursor:pointer;
}

.overlay {
    position:absolute;
    top:0;
    right:0;
    bottom:0;
    left:0;
    background:black;
    display:none;
    opacity:0.5;
}
.dialog {
    background:green;
    position:fixed;
    width:50%;
    margin-left:25%;
    border:1px solid #000000;
    z-index:999999;
    display:none;
    top:25%;
}
.dialog header {
    min-height:50px;
    background-color:#e9e9e9;
    text-align:center;
    border-bottom:1px solid #c4c4c4;
}
.dialog header h1 {
    margin:0;
    font-weight:300;
    font-size:22px;
    padding-top:10px;
}
.dialog .dialog-content {
    background-color:#f7f7f7;
    min-height:200px;
    padding:20px;
    margin:0;
}
.dialog footer {
    position:absolute;
    bottom:0;
    background-color:#ececec;
    width:100%;
    border-top:1px solid #acacac;
}
.dialog footer .inner-container {
    padding:10px;
    text-align:right;
}
.dialog footer .inner-container p {
    float:left;
    width:300px;
    text-align:left;
    margin:0;
}
footer .dialog-btn {
    background:#ffffff !important;
    color:#000000 !important;
    padding:13px;
    display:inline-block;
}

SCRIPT:

$(".cancel").click(function(){
   $('.dialog').stop().fadeOut(200);
   $('.overlay').hide();
});


$("#create").click(function(){
   $('#create-new-dialog').stop().fadeIn(300);
   $('.overlay').fadeIn(300);
});

$("#edit").click(function(){
   $('#edit-dialog').stop().fadeIn(300);
   $('.overlay').fadeIn(300);
});

View the example here: https://jsfiddle.net/susannalarsen/28t6t51x/

Answer №1

To implement data attributes with links, you can follow the code snippet below:

$(".cancel").click(function(){
   $('.dialog').stop().fadeOut(200);
   $('.overlay').hide();
});


$(".modalTrigger").click(function(){
    var myModal = $(this).attr("data-modal");
    $('#' + myModal).stop().fadeIn(300);
   $('.overlay').fadeIn(300);
});

The links in the HTML would look like this:

<a class="modalTrigger" data-modal="dialog1">New</a>

<a class="modalTrigger" data-modal="dialog2">Edit</a>

<div class="dialog" id="dialog1">

<div class="dialog" id="dialog2">

For a visual representation of this code, check out the JSFiddle link.

You could also utilize the href attribute in your implementation:

$(".cancel").click(function(){
   $('.dialog').stop().fadeOut(200);
   $('.overlay').hide();
});


$(".modalTrigger").click(function(){
    var myModal = $(this).attr("href");
    $(myModal).stop().fadeIn(300);
   $('.overlay').fadeIn(300);
});

The corresponding HTML for this approach would be:

<a class="modalTrigger" href="#dialog1">New</a>
<a class="modalTrigger" href="#dialog2">Edit</a>

Answer №2

I made some changes to your code snippet in the fiddle. Now, each "a" element includes a class name of btn, and the id needs to match a data-content attribute on the corresponding dialog div. Check out the updated version here: https://jsfiddle.net/28t6t51x/2

$(".btn").click(function () {
var id = $(this).attr("id");
$("div.dialog").each(function () {
    if ($(this).attr("data-content") === id) {
        $(this).stop().fadeIn(300);
        $('.overlay').fadeIn(300);
    }
});

Answer №3

Yes, absolutely! You have the option to create a helper function that accepts an ID (example):

function displayDialog(dialogId){
   $('#' + dialogId).stop().fadeIn(300);
   $('.overlay').fadeIn(300);
}

$("#create").click(function(){
   displayDialog('create-new-dialog');
});

$("#edit").click(function(){
   displayDialog('edit-dialog');
});

Alternatively, using a similar approach, you can utilize one dialog box and simply change the content dynamically based on the button clicked (example):

function displayDialog(content){
   $('#content p').text(content);
   $('#my-dialog').stop().fadeIn(300);
   $('.overlay').fadeIn(300);
}

$("#create").click(function(){
   displayDialog('foo');
});

$("#edit").click(function(){
   displayDialog('bar');
});

The complexity of your implementation will depend on the number of buttons, dialogs, or other elements that you expect to incorporate.

Answer №4

To display a dialog when an element is clicked, you can retrieve the id of the clicked element and then append the dialog.

$("a:not(#exit)").click(function(){
    var btnId=$(this).attr('id');
    var dialogType=btnId+"-dialog";
   $('#'+dialogType).stop().fadeIn(300);
   $('.overlay').fadeIn(300);
});

To make it work, you need to update the id of the create tag to 'create-new'. Check out this example on jsfiddle for reference.

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

Is there a way to showcase the search outcomes of employee information stored in my text document using PHP?

i was tasked with creating a PHP file that could search for an employee's ID number and display the results on the same page from a text file. The expected output should look like this: Expected Output (results on the same page): Search Employee Rec ...

Retrieve the post ID from the existing URL via AJAX in order to fetch data associated with that particular ID

Currently, I am facing an issue while trying to pass the id from the current URL to the select.php page. The error displayed is 'id not defined' and as a result, no data is being fetched. My goal is to retrieve data for the suporder index from th ...

Photo on vertical display

I have been working on displaying dynamic photos from a backend file and looping through them. I have successfully displayed the images vertically using CSS. vertical-align: middle; However, when I tried to add a photo name for each image, the positionin ...

What is the method for defining a CSS property for the ::before pseudo element within an Angular component?

Can TypeScript variables be accessed in SCSS code within an Angular component? I am looking to achieve the following: <style type="text/css"> .source-status-{{ event.status.id }}::before { border-left: 20px solid {{ event.status.colo ...

Trigger functions when the window is scrolled, resized, or when the document is fully loaded

I have a few functions that need to be executed under specific conditions: window.scroll window.resize document.ready For example: <script> function myFunction1(data){ /*code*/ } function myFunction2(data){ /*code*/ } ...

What methods can I employ to utilize a JSON response generated by PHP within jQuery?

Currently, I am in the process of creating a website and I'm working on gathering all the reviews stored in the database. Initially, my approach was to utilize PHP in the following manner: function get_all_reviews(){ $db = dbConnection(); $db ...

Struggling to make the Bootstrap 4 Datatables example work on my website

Trying to implement the code example from the second snippet in the answer of this thread Bootstrap - How to sort table columns. Should I just insert the js snippet into a script tag in the html or am I misunderstanding how it should be done? I also attemp ...

What is the best way to eliminate the blue color from a Boostrap 5.3 accordion item when it is opened?

As shown in these two images, I am looking to remove the blue color and blue border when opened: https://i.sstatic.net/vOIna.png https://i.sstatic.net/7eLfK.png <div class="accordion-item"> ...

What is the best way to incorporate HTML styling into a PHP email tutorial focused on Swift Mail?

I recently created a competition page for a client, and they have requested that the email sent to customers be more visually appealing than just plain text. The tutorial I followed only included basic text within the 'send body message' section. ...

The text-decoration is here to stay

Currently, I am facing an issue with the customization of a wordpress theme related to the styling of links within posts. Although I have tried to change the color and remove underlining using CSS rules, I am unsuccessful so far: a, .entry-meta a, entry-c ...

How to Conceal the Search Bar in jQuery DataTables

I am having trouble hiding the default search bar in DataTables. Despite trying solutions from this thread, using bFilter:false completely disables filtering, rendering my search boxes in the footer non-functional. I have created a jsfiddle demonstration. ...

Add the data object list to the serialized format

I am looking to map a list of data objects with serialized form data in my backend, which is .Net. I have a Model class set up to map the parameters. Below is the jQuery object I am currently using: var MultiAssignGarageCampaign = []; var obj = {}; ...

Using webpack to load the css dependency of a requirejs module

Working with webpack and needing to incorporate libraries designed for requirejs has been smooth sailing so far. However, a bump in the road appeared when one of the libraries introduced a css dependency: define(["css!./stylesheet.css"], function(){ &bsol ...

Integrating dual Google Maps onto a single HTML page

I'm facing an issue with implementing two Google maps on a single page where the second map seems to be malfunctioning. Below is the code I am currently using: <style> #map-london { width: 500px; height: 400px; } #map-belgium { wi ...

Issue with OnChange event in HTML and Adding Content with Jquery

I'm currently working on an app that includes a dynamic dropdown feature using jQuery and the append() method to display changing numbers dynamically. Everything seems to be functioning well in the first field of the form, but when I try to add more f ...

Ways to adjust the size of the parent element based on the height of a specific element

I am faced with a situation where I need to identify all elements belonging to a specific class and adjust the padding-bottom of their parent div based on the height of the matched element. For example, consider the following structure: <div class=&ap ...

Showing fetched data from Firebase in an Ionic 3 HTML file

Looking for assistance on how to display data retrieved from my firebase database in my HTML file. I need help with organizing the data, starting with displaying customer user's data. Eventually, I want to make it clickable and put the user's dat ...

The right padding on an HTML table is not functioning properly when the table width is larger than

I am facing an issue with a table that has multiple columns. I want each column to have the same width, resulting in the total table width being wider than the page width. This is fine as it prompts the browser to display a horizontal scrollbar. However, d ...

How to align a div in the center of a cell with Bootstrap

I am currently working with Bootstrap 3 and I have a specific requirement to center a div within a cell in the container row. Most resources I found only mention how to center a div within the entire container, which is not what I am looking for. My goal i ...

Unraveling the Enigma of Event Handlers: Mastering the Organization of a Sprawling jQuery File within an AJAX

I've created a web application that heavily relies on AJAX and jQuery for DOM manipulation and making AJAX requests. However, I'm facing a problem with my JavaScript file: The issue is that my JavaScript file consists of a huge collection of eve ...