Moving a Div to the Center of the Screen Using Jquery and Masonry JS

I am currently utilizing Jquery Transit and Masonry JS within my project. Within a specific div, there is a button which, when clicked, is intended to change the container's position to fixed and center it on the screen using Jquery Transit. However, upon clicking the button, the container instead moves to the bottom right corner of the screen.

If you'd like to observe the issue firsthand, please refer to this jsfiddle link.

Here is the relevant javascript code snippet:

  WebFont.load({
    google: { families: [ 'Signika:400,700:latin', 'Open+Sans::latin', 'Hammersmith+One::latin' ]},
    active: triggerMasonry,
    inactive: triggerMasonry
  });
var $container;

function triggerMasonry() {
  // Only proceed if $container has been selected
  if ( !$container ) {
    return;
  }
  
$container.imagesLoaded( function() {
  $container.masonry({
    itemSelector: '.p-small',
    "columnWidth": '.grid-size',
    gutter:10
  });
  });
}

// Trigger masonry once document is ready
  $container = $('#omni-content');
  triggerMasonry();
    var $cards = $('.p-small');
    var cardInFocus = null;

    $cards.each(function(index, elem){
        var $elem = $(elem);
        var pos = $elem.position();
        $(elem).data('orig-x', pos.left);
        $(elem).data('orig-y', pos.top);
    });

    var reset = function(){
        if(cardInFocus){
            $(cardInFocus).transition({x:0,y:0});}      
    };

    $(".o-help").click(function(e) {
        cardInFocus = $(this).closest(".p-small");
        var $doc = $(document);
        var centerX = $doc.width() / 2;
        var centerY = $doc.height() / 2;
        var $card = $(this).closest(".p-small");
        var widthcard = $card.width();
        $(".explain").css('position','fixed');
        $(".explain").css('width', widthcard);
        $card.addClass('explain');
        var origX = $card.data('orig-x');
        var origY = $card.data('orig-y');
        $(".modal-bg").fadeIn("slow");
        $(this).closest(".p-small").transition({x:centerX - origX,y:centerY-origY, duration:750});
    });

    $cards.blur(function(e){
        reset();
    });

Answer №1

The issue lies in the fact that you are shifting the top left corner of the container to the center instead of the actual center of the container. This creates the illusion that it is not properly centered. To correctly center the container, you must adjust by half of both the width and height of the container.

$(".o-help").click(function(e) {
    cardInFocus = $(this).closest(".p-small");
    var $doc = $(document);
    var centerX = $doc.width() / 2;
    var centerY = $doc.height() / 2;
    var destX = centerX - cardInFocus.width()/2;
    var destY = centerY - cardInFocus.height()/2;
    var $card = $(this).closest(".p-small");
    var widthcard = $card.width();
    $(".explain").css('position','fixed');
    $(".explain").css('width', widthcard);
    $card.addClass('explain');
    var origX = $card.data('orig-x');
    var origY = $card.data('orig-y');
    $(".modal-bg").fadeIn("slow");
    $(this).closest(".p-small").transition({x:destX -  origX,y:destY-origY, duration:750});
});

If you want to see the outcome, feel free to visit this fiddle.

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

What are some ways to enhance the speed of my canvas animations?

My code generates imagedata and places it in a canvas. However, when I expand the window size, the rendering slows down significantly. Is there a way to optimize this for smooth operation in fullscreen mode, even though it might seem naive? What would be ...

Assign the same property value to all objects in the array and remove any duplicates

I am currently working with an object that contains nested objects: { "0": { "boardingGate": "exit_0", "departureTerminal": "1", "terminalArea": 0, "arrivalGate": "enter_0", "arrivalTerminal": "2", "terminalArea": 0 }, "1": { ...

Setting radio buttons as active dynamically can be achieved using jQuery Mobile

Currently, I am utilizing jQuery mobile's horizontal control group for radio buttons. I am facing an issue with setting the first radio button as active. Below are the two radio buttons: <input type="radio" name="rating" id="radio-mini-1" value=" ...

Sending images from an external source to a client using Node.js and Express

I'm struggling with a problem. Assuming I have an external image URL, like this one from IMDb.com, . How can I display this image for the client? Currently, I have this: res.write('<img src="/http://ia.media-imdb.com/images/M/MV5BMTMyMzA5ODI ...

Concealing a div depending on the price variation

I'm looking for a way to dynamically show or hide a div based on the price of selected variations in my online store. Let's take a product with options priced at £359 and £455 as an example. In addition, there is a finance plugin with a minim ...

JSX conditional rendering not behaving unexpectedly

Having difficulty with a conditional JSX statement causing an element to not display properly unless the window is resized. Please note that it works fine in development mode but does not show correctly after building. The goal is to show navigation links ...

Using Javascript or Jquery, you can submit a form without the need for a button

I'm attempting to submit a form without using a button by invoking a JavaScript function and processing the form with JQUERY/PHP. My goal is for the form to be submitted silently on the backend without causing the page to reload. However, I keep encou ...

Unable to alter the background color of the text box

I am currently struggling with my code where I am trying to overlay a text box on an image. Even after setting the background color to white, it still shows up as transparent. I have successfully done this in the past, but for some reason, it is not work ...

Achieve uniform display across browsers: Implement Chrome's overflow ellipsis feature on Firefox

I am seeking a CSS solution to achieve the same "overflow: hidden" and "text-overflow: ellipsis" behavior in Firefox as I get in Chrome. In Chrome, when the width of the tag is reduced, the text gets hidden and replaced with an ellipsis. However, in Firefo ...

Issue: Error in hook call | Unable to retrieve data using context in getStaticProps in Next.js

I am a beginner in react/next and I am attempting to load my post using getStaticProps. However, I face the issue when trying to use "useAppContext" or even "useContext(AppContext)". Error - Error: Invalid hook call. Hooks can only be called inside of th ...

The "track by" feature in Angular doesn't seem to be functioning properly when used with an array from $

Within the method of my factory, I am retrieving an array from the server using Angular's $resource: var resource = $resource("vm", { session: function() { return Auth.token(); }, all: '@all', vmId: '@vmId' ...

What is the quickest method for importing React.js Material Icons in a single line of code?

While working on my initial react.js project as a beginner, I encountered the frustration of having to import Material UI icons individually. This process made my code unnecessarily long and required me to repeatedly visit the browser to copy the icon li ...

Mastering the Art of Sending Multiple Values via Ajax

I'm having trouble passing multiple values using ajax in my code snippet. Here is the code I am working with: $(".ajax-button").change(function(event){ $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': '{{ ...

Using Three.js to create smooth rotations for objects

I have a logo in .obj format that I am loading onto a canvas using three.js. The logo is an integral part of the website's loading section that I am currently developing. Within this section, there is a 'Click to Enter' button. My goal is fo ...

Making an Ajax request to a RESTful web service from a different domain

Similar Question: Exploring methods to work around the same-origin policy I need to communicate with a RESTful web service from a different IP address using an AJAX request on my HTML page. Unfortunately, AJAX does not support cross-domain requests. ...

How come the value isn't displaying on my input slider?

I've been grappling with this issue for some time now. It's puzzling because I'm confident the JS code is correct. There must be something missing, considering I've tested it on both Chrome and Mozilla. I've organized the files in ...

Trouble encountered while trying to assign text to an option within a jQuery loop

Here is the code I am working with: $('#selectid option').each(function(){ if( this.text.indexOf("abcxyz") >= 0){ var lable = this.text.replace("abcxyz", ""); this.text(lable); ...

Identifying Hashtags with Javascript

I am trying to identify hashtags (#example) in a string using javascript and convert them to <a href='#/tags/example'>example</a> Currently, I have this code: var text = '#hello This is an #example of some text'; text.r ...

Animate the jQuery display property to show a table without changing any specified spatial dimensions

When utilizing jQuery's $.animate() on an element styled with display:table, any spatial dimensions that are not explicitly specified to change will animate. Check out the fiddle here In the scenario presented, the width is defined for animation, bu ...

What is the maximum number of rows that Handsontable can handle at once?

Issue encountered in queued task: Security check failed - Too many TRs. Please specify table height to enable scrollbars. at WalkontableTable._doDraw (client/libs/handsontable-0.10.5/jquery.handsontable.full.js?37b46fd989b9a974c3501865b51effd7adec37e4:1285 ...