Learn the technique for displaying various content in pop-up windows when clicking on HTML links

I have a code snippet that I am using and I want to display different content when clicked.

<style>
#overlay_form {
    position: absolute;
    border: 5px solid gray;
    padding: 10px;
    background: white;
    width: 270px;
    height: 190px;
}
#pop {
    display: block;
    border: 1px solid gray;
    width: 65px;
    text-align: center;
    padding: 6px;
    border-radius: 5px;
    text-decoration: none;
    margin: 0 auto;
}
</style>

The javascript code is as follows:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>    
<script type="text/javascript">     
$(document).ready(function () {
    //open popup
    $("#pop").click(function () {
        $("#overlay_form").fadeIn(1000);
        positionPopup();
    });

    //close popup
    $("#close").click(function () {
        $("#overlay_form").fadeOut(500);
    });
});

//position the popup at the center of the page
function positionPopup() {
    if (!$("#overlay_form").is(':visible')) {
        return;
    }
    $("#overlay_form").css({
        left: ($(window).width() - $('#overlay_form').width()) / 2,
        top: ($(window).width() - $('#overlay_form').width()) / 7,
        position: 'absolute'
    });
}

//maintain the popup at center of the page when browser resized
$(window).bind('resize', positionPopup); 
</script>

What I would like is an HTML structure similar to this:

<html>
<div>
    <a href="#" id="pop" >Product Overview</a>
    <br/>
        <div id="overlay_form" style="display:none">
            <a href="#" id="close" >Close</a>
        </div>

    <a href="#" id="pop" >User Interface</a>

        <div id="overlay_form" style="display:none">
            <a href="#" id="close" >Close</a>
        </div>
</div>

</html>

When clicking on different links, I want different content to appear in the pop-up window without repeating the entire JavaScript code with different IDs.

Thank you!

Answer №1

It is important to avoid using the same ID more than once on a single webpage. Currently, you have assigned #pop, #close, and #overlay_form to multiple elements. Consider updating these with different IDs or classes.

One solution could be to nest a div within each a tag to contain your content, allowing you to easily show/hide it upon clicking.

Answer №2

There are multiple approaches to achieve this, but one straightforward method involves transitioning many of your id's to classes within your existing code. Consider the following example:

HTML

<html>
    <div>
        <a href="#" class="pop" popup-id="popup1">Product Overview</a>

        <div class="overlay_form" id="popup1" style="display:none">
            <a href="#" class="close" >Close</a><br />
            Popup1 text.
        </div>

        <a href="#" class="pop" popup-id="popup2">User Interface</a>

        <div class="overlay_form" id="popup2" style="display:none">
            <a href="#" class="close" >Close</a><br />
            Popup2 text.
        </div>
    </div>
</html>

JS

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>    
<script type="text/javascript">     
    $(document).ready(function () {
        //open popup
        $(".pop").click(function () {
            var targetPopup = $(this).attr('popup-id');
            $("#" + targetPopup).fadeIn(1000);
            positionPopup(targetPopup );
        });

        //close popup
        $(".close").click(function () {
            $(this).closest(".overlay_form").fadeOut(500);
        });
    });

    //position the popup at the center of the page
    function positionPopup(targetPopup) {
        $("#" + targetPopup).css({
            left: ($(window).width() - $('#overlay_form').width()) / 2,
            top: ($(window).width() - $('#overlay_form').width()) / 7,
            position: 'absolute'
        });
    }

    //maintain the popup at center of the page when browser resized
    $(window).bind('resize', positionPopup); 
</script>

This strategy allows you to utilize the class attribute for defining a broader set of elements sharing similar behavior (and styles), while still preserving the uniqueness of each popup.

Note: incorporating a custom attribute (popup-id) may lead to validation issues unless you update your DOCTYPE statement to include it. Despite this, many individuals overlook this problem, especially given that HTML5 is gradually accommodating custom attributes.

EDIT: an important detail to address... as you switch from IDs to classes, remember to adjust your CSS selectors from #pop and #overlay_form to .pop and .overlay_form.

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

The react router threw an error, expecting an assignment or function call but instead receiving an expression

Within a Material Table, there is a button that triggers page routing through react routers to navigate to different URLs. The setup involves defining functions, calling the Material Table element <MuiTable>, and rendering a button below the table fo ...

Steps for importing an external .js file into a Vue 2 component

Hello, I am currently working on vue.js 2 and I have come across a problem with the JavaScript part. I would like to include the general.js file in my posts.vue file. Can anyone provide assistance with this? Your help would be greatly appreciated :) Below ...

Challenges when upgrading from Ext JS 3 to Ext JS 4

I am looking to upgrade my code from Ext JS 3 to Ext JS 4. I used the Ext.Updater class in Ext JS 3, but I cannot seem to locate a similar functionality in Ext JS 4. Can anyone provide assistance with this transition? ...

Generate a dot density map with the help of Google Maps

I am looking to create a dot density map using Google Maps for my state. I have all the counties outlined with their respective populations, and I want to scatter dots randomly within each county to represent the population. The goal is to make a dot densi ...

Positioning the filters in jQuery Datatables

I'm currently working with jQuery datatables and I'm attempting to align the filter/search box on the same row as the header of the container holding the datatable. Attached is a screenshot for reference: https://i.stack.imgur.com/nzbIl.png He ...

What is the best way to efficiently import multiple variables from a separate file in Vue.JS?

When working with a Vue.JS application and implementing the Vuex Store, I encountered an issue in my state.js file where I needed to import configurations from another custom file, specifically config.js. Upon running it, I received the following warning ...

Retrieve JSON information from a URL via AJAX if applicable

Is there a way to retrieve the JSON data from the following URL and incorporate it into my webpage in some capacity? (Disclaimer: I do not own this website, I am simply utilizing the data for a basic free app.) Although entering the URL directly into the ...

Moving from the end to the beginning with a jQuery slider transition

Instead of relying on external plugins, I built this slider from scratch: function customSlider(selector, interval, index) { var slider = this; this.ind = index; this.selector = selector; this.slides = []; this.activeSlide = 0; this.amount; ...

Perform a series of consecutive AJAX requests using jQuery

Currently, I am dealing with an endpoint that is not functioning well. It's important to note that I do not have the ability to modify how this particular endpoint works. The specific ajax call in question is: POST /doStupidThing/. I have a list of ...

Learn how to use a function in Google Maps to calculate and display distances

I have a script obtained from this link here and I am trying to create a function that returns the distance. This is my current script: var calcRoute = function(origin, destination) { var dist; var directionsDisplay; var directionsService = ne ...

PHP selectively incorporates a section of a document

Hey there, I've been encountering a strange issue on my website. I have a foot.php file that I include at the end of some pages so that any changes made to it will affect all pages on the site. While this works perfectly on most pages, there are certa ...

HTML - implementing a login system without the use of PHP

While I am aware that the answer may lean towards being negative, I am currently in the process of developing a series of web pages for an IST assignment in Year 9. Unfortunately, the web page cannot be hosted and our assessor lacks the expertise to utiliz ...

The functionality of the Ajax call ceases to function properly on mobile devices after a period of time

I'm currently developing a mobile application using Cordova, AngularJS, and jQuery. My issue lies in trying to retrieve two files from the same directory. The first file retrieval is successful and occurs immediately after the page loads. However, t ...

An unusual syntax issue triggered within the jquery file resulted in an error being thrown

While browsing my website, I encountered an error and found myself looking at the following snippet of code (located within a jQuery .js file): trigger: function() { return this !== _() && this.focus ? (this.focus(), !1) : void 0 } I am curious ...

Are you looking to connect with Yahoo Weather, Yahoo GeoPlant, Google Weather, or any other API using JavaScript?

I am looking for a solution to retrieve the current weather data for a specific city using JavaScript. Can anyone recommend an API that would be best for this task? Alternatively, are there any applications that allow you to make an AJAX request to obtain ...

Avoiding HTML (JSX) tag duplication in React Component

Having the same code in my React component multiple times is becoming repetitive and inefficient. Is there a way to follow the DRY principle and avoid repeating this code? While creating a landing page with Sass styling, I noticed that I am duplicating t ...

When you click, a new webpage opens within my website, similar to the feature on Facebook

When using Facebook on mobile, clicking on a link to a person's website opens the website in front of the Facebook page. However, when users press the X in the top left corner, it deletes the webpage but keeps Facebook open. On my desktop computer, I ...

Generate interactive HTML content and showcase JSON data within it

I am working on an AJAX API call that returns JSON format data. My goal is to display each value on the screen using HTML elements. Although I have achieved this, the design is not dynamic as needed. Additionally, I want to show a message ("No data avail ...

Create eye-catching banners, images, iframes, and more!

I am the owner of a PHP MySQL website and I'm looking to offer users banners and images that they can display on their own websites or forums. Similar to Facebook's feature, I want to allow users to use dynamic banners with links. This means the ...

Issue with Node.js Mongoose: Attempting to store a date in UTC Timezone, but it is being saved in the local time

I am relatively new to using nodejs and mongodb. I am encountering an issue with dates while using mongoose for mongodb - whenever I attempt to save a date into the database, it automatically gets converted to the local timezone, which is not the desired b ...