`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

Can HTML and CSS be used to create button text that spans two lines with different fonts?

When working with HTML attribute values, I am facing an issue where I can't get button text to display in two lines with different font sizes. I have attempted using whitespace in CSS for word wrap, but this solution does not solve my problem. I also ...

The placement of the breadcrumb trail is not in the right position

My website includes a menu and breadcrumbs. The menu consists of two submenus: Design Services, Design Portfolio, Design Fees, About Us, Contact Us, Design Resources, Design Vacancies, and Terms. Clicking on Design Services reveals Graphic Design, Logo Des ...

Just for laughs: "The react-redux context value seems to be playing hide and seek; make sure to wrap the component in a <Provider> for it to show up!"

I encountered an issue while attempting to run a basic Jest test on a form React component: ● <LoginForm /> › clicking the validate button › should display page title ...

The challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

What is the method to make a file download using JavaScript?

In my jQuery ajax form, a user inputs their email and upon submission, they should receive an automatic download of a file. Here is the structure of the form: $(".email-form").submit(function(event) { event.preventDefault(); var $form = $(this), ...

Bootstrap dropdown feature automatically rearranges all items in my navigation bar

I recently set up a navbar for my website, but I'm struggling to grasp the concept of positioning items with Bootstrap. One issue I encountered is that when I click on the dropdown button (profile image), it causes all the items in my navbar to shift, ...

Attempting to access a variable without wrapping it in a setTimeout function will

I have a form without any input and my goal is to automatically set the "responsible clerk" field to the currently logged-in user when the component mounts. Here's what I have: <b-form-select v-model="form.responsible_clerk" :op ...

Tips for incorporating multiple jQuery AutoSuggests into one webpage

Thank you for your response. It seems I didn't provide enough details about my issue before, so allow me to explain it fully now. I have successfully created one Autosuggest on my page and I would like to add two more Autosuggests on the same page, m ...

Utilizing AngularJS: Conditionally rendering ngIf within an array of objects containing unique properties

Facing a challenge with the ngIf directive that I have been struggling to resolve despite trying various solutions. In my scenario, I have an array of objects, each containing different properties. The structure is as follows: object = [ { ...

Implementing JavaScript to display specific content when a list is devoid of any items

Currently, I am in the process of developing a basic contact list web application where the contacts are listed within li elements. My aim is to adjust the visibility of the text in the p#no-contacts element based on whether the containing ul has any child ...

Issue with the Navigation in CSS and jQuery

I'm struggling to understand a problem with the desktop navigation on this website, specifically in Safari on certain pages. The issue seems to only occur on Safari for Windows, Mac Desktop, and Mac Laptop. Interestingly, the navigation works perfect ...

Issues with PHP not properly accepting JSON data sent via Ajaxor

I've been attempting to send JSON data to a PHP file using Ajax. Here is the JavaScript code I've written: function updateJSON(){ var xmlhttpa; if (window.XMLHttpRequest){ xmlhttpa = new XMLHttpRequest(); } else { xml ...

Make an ajax call without any parameters and then in PHP, verify if the variable is

I have a code snippet that is currently functional. I am looking to remove the URL and handle the AJAX request on the same page. Since no data is being sent, how can PHP be used to determine when the AJAX function is ready to send a request to the database ...

Transform Unicode characters into HTML using Qt

I am facing an issue with a particular string that includes Unicode characters and special symbols. The string, for instance, looks like this: SYMBOLSU+2510\n The string contains the Unicode character U+2510 and a new line symbol \n. I have a lo ...

Determining the Position of the Cursor Within a Div

When a link is clicked, a pop up is displayed. Here is the code for the pop up: <div class='' id="custom-popover"> <div class="arrow"></div> <h3 class="popover-title">Popover left</h3> <div class="pop ...

Troubleshooting an Issue with MediaStreamRecorder in TypeScript: Dealing with

I've been working on an audio recorder that utilizes the user's PC microphone, and everything seems to be functioning correctly. However, I've encountered an error when attempting to record the audio: audioHandler.ts:45 Uncaught TypeError ...

Reset the button is behaving in the same way as the submit button

I'm having an issue with the script below where the reset button is acting like a submit button as well. Can anyone help me troubleshoot this problem? Thank you. HTML <input type="image" name="submit" value=" " src="image.png"> <input t ...

Button click event is not being triggered by Ajax rendering

I am facing an issue with my Django template that showcases scheduled classes for our training department. Each item in the list has a roster button which, when clicked, should display the class roster in a div. This functionality works perfectly. However, ...

After integrating Redux into React, the map(item) function is unable to send "item" as props to a JSX component

Currently, I am working on integrating Redux into my React application. As part of this process, I have developed four actions to manage the "items" in my application. The initial three actions, namely GET_ITEMS, DELETE_ITEM, and ADD_ITEM, function seamles ...

Utilizing the Python request library to send a jquery AJAX GET request

I've encountered a challenge with a website that I need to scrape. The site uses a jQuery AJAX function to retrieve information from the server. After digging into the code, I was able to successfully receive a response using the following JavaScript: ...