`Jump-start Your Development with jQuery Lightbox Centering`

Recently, I implemented a lightbox effect for images on my website. However, I encountered an issue where the lightbox was not centering properly in the window upon initial click. Instead, the lightbox would appear at the bottom of the page on the first click and only align correctly upon subsequent clicks.

First Time Clicking the Image:

Second Time Clicking the Image:

The first time caused alignment issues. The second time did not have any alignment problems (without reloading the page). Javascript:

 <script>
                jQuery(document).ready(function() {
                    jQuery("img").click(function() {
                          var img_path;               
            if ($(this).parent('a').length) {

                           img_path = $(this).parent('a').prop('href');
                            }
                        else
                            {
                         img_path = $(this).attr('src');
                            }

                        jQuery(".cplightbox1").html(jQuery("<img>").attr("src", img_path));
                        jQuery(".cpoutter").css('display', 'block');
                        jQuery('.cpoutter').animate({'opacity': '1'});
                        //jQuery('.lightbox').animate({'opacity':'1.00'});
                        var cplightbox = document.getElementsByClassName('cplightbox')[0];
                        var cpoutter = document.getElementsByClassName('cpoutter')[0];
                        cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";
                        return false;
                    });
    });
    </script>

HTML CODE:

Here is the Fiddle http://jsfiddle.net/rCUGD/7/

This script works fine on jsfiddle.net, so there might be an issue with the implementation on my website.

I'm unsure where I went wrong.

EDITED:

Thanks to @JustAnil, here is how the lightbox should look after the second click:

After the second click, it should display normally like this.

Answer №1

Take a look at this functional JSFiddle example.

To achieve the desired result, make adjustments to the code snippet below (specifically where the offset calculation takes place).

Replace the following lines:

 var cplightbox = document.getElementsByClassName('cplightbox')[0];
 var cpoutter = document.getElementsByClassName('cpoutter')[0];
 cplightbox.style.marginTop = ((cpoutter.offsetHeight / 2) - (cplightbox.offsetHeight / 2)) + "px";

With:

var cplightbox = document.getElementsByClassName('cplightbox')[0];

// Obtain the height of the image from the "inner" container
var cplightbox1 = document.getElementsByClassName('cplightbox1')[0]; // New Line

var cpoutter = document.getElementsByClassName('cpoutter')[0];

// Calculate the (negative) offset based on width & height
cplightbox.style.marginLeft = "-"+$(cplightbox1).width() / 2 + "px";
cplightbox.style.marginTop = "-"+$(cplightbox1).height() / 2 + "px";
// ^ Negative offset for vertical and horizontal centering.

Lastly

Update your CSS as follows:

.cplightbox {
    margin-left: auto;
    margin-right:auto;
    width:auto;
    height:auto;
    display:inline-block;
}

Change it to:

.cplightbox {
     position:fixed;
     top:50%;
     left:50%;
     display:inline-block;
 }

Refer to this post on CSS Vertically & Horizontally Center Div (for centering a div in the middle of the screen).

Adjust your javascript accordingly to calculate the negative offset (depending on the image size [e.g., 50% of width & height])

Check out the working example on JSFiddle.

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

Positioning JQuery sliders

I've been working on a jQuery slider for my header, but I'm encountering an issue where the previous image drops down to the next container instead of staying in place and transitioning smoothly. It seems like there might be an error in my HTML/C ...

Ways to turn off .removeClass()

Encountering an issue with jquery-2.1.4.js. Upon integrating a layerslider into my website, the script modified div classes. Attempted using older versions of the script without success. Currently have classes as follows: <a href="#" class="col-md-3 ...

Transform form data from square notation to dot notation using jQuery

During my ajax operations, I noticed that the data being sent is in JSON format. However, when checking Chrome tools -> network XHR, I observed that the form parameters are displayed within square brackets. Example: source[title]:xxxxxxxxxxxx source[thu ...

Sending a POST request to a Flask server using Stripe and AJAX

I am attempting to implement a function that triggers an ajax request when a stripe form is submitted. However, using the .submit() method doesn't seem to be working as expected. Here is my current code: HTML <form action="/download_data" method= ...

Discover the secret to loading multiple Google charts simultaneously, despite the limitation that Google charts typically only allow one package to load at a time

I currently have a pie chart displaying smoothly on my webpage, but now I am looking to add a treemap as well. The code snippet for the treemap includes the package {'packages':['treemap']}. It has been stated that only one call should ...

applying conditional rendering in vue.js

I'm currently working on developing a chat application using the guidelines outlined in this tutorial: https://socket.io/get-started/private-messaging-part-1/ One of my goals is to customize the appearance of the messages, so that when a message is s ...

Update the designated dropdown menu using its identification number

I have discovered a way to change the selected dropdown item by value, but I am interested in doing it by the option ID instead. The reason for this is that the values are dynamically generated. Currently, I am working on creating a questionnaire that incl ...

What is the purpose of applying the two unique class names (root and disabled) to the DOM in order for it to function correctly?

When it comes to customizing components using material-ui, the process can be a bit tricky. Here's how you can do it: const styles = { root: { '&$disabled': { color: 'white', }, }, disabled: {}, // This is i ...

Looking to understand how to effectively utilize the ContentProtectionCallback in SHAKA PLAYER?

Could someone assist me in understanding how to pass the ContentProtectionCallback in order to manage the preProcessor of a drm license url for shaka player? [ var manifestUri = '<mpd url>'; function initApp() { // Including nece ...

In Javascript, we can increment the current date by utilizing the `getDate()`

I am trying to create an if statement in JavaScript; if (nextProcessingDate > today ) { //do something } nextProcessingDate has a timestamp assigned, like 09/07/2014 12:10:17 To assign today's timestamp to the today variable, I am using this c ...

"Encountering issues with Rails and AJAX where the data returning is showing up

I am facing a challenge while trying to use AJAX in Rails to POST a comment without using remote: true. I am confused as to why my myJSON variable is showing up as undefined, while data is returning as expected. Check out my code below: function submitVi ...

Angular has the feature of a right float button with *ngfor

I've successfully implemented a form using Reactive Forms in Angular. Currently, my form is displayed as follows: <div class="center" appMcard> <form [formGroup]="GroupRMPM_FG"> <div formArrayName="GroupId_Name" *ngFor="let ...

Limiting the style of an input element

How can I mask the input field within an <input type="text" /> tag to restrict the user to a specific format of [].[], with any number of characters allowed between the brackets? For example: "[Analysis].[Analysis]" or another instance: "[Analysi ...

React Router will not remount the component when using this.context.router.push

We have implemented a click handler that utilizes react router 2.0 to update the URL with this.context.router.push(). Here is the code snippet: selectRelatedJob(slug) { JobActionCreators.fetchJobPage(slug); JobsActionCreators.getRelatedJobs({'sl& ...

Can you explain the significance of the ">" symbol within CSS coding?

Seeking some quick points for those in the know. Can someone provide a thorough explanation of the meaning and proper usage of the > symbol? Appreciate it. ...

Designing rows and columns using Angular CSS within an ngFor loop

Is there a way to align items in a row or column based on conditions within an *ngFor loop? I want the input type to display on the next line if it is textarea, and on the same line otherwise. Check out this Stackblitz Demo for dynamically generated HTML ...

typescript throwing an unexpected import/export token error

I'm currently exploring TypeScript for the first time and I find myself puzzled by the import/export mechanisms that differ from what I'm used to with ES6. Here is an interface I'm attempting to export in a file named transformedRowInterfac ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Tips for displaying the Font Awesome icons

I have included Font Awesome icons within the <span> tags and applied the necessary styles in my CSS file. However, the icon is not being displayed correctly. I am looking for a solution to ensure the correct display of the icons. The HTML code wher ...

Is it possible to use JavaScript or jQuery to call a WCF Service and retrieve a collection of System.IO.Stream objects?

I am developing a WCF service that will be utilized by plain JavaScript on the client side, as well as some jQuery JavaScript. 1) How can I set up the plain client JavaScript to call the WCF Service in a manner that retrieves a collection of System.IO.Str ...