Animating a Bootstrap 4 card to the center of the screen

I am attempting to achieve the following effect:

  • Display a grid of bootstrap 4 cards
  • Upon clicking a button within a card, animate it by rotating 180 degrees, adjusting its height/width from 400px - 350px to the entire screen, and positioning it at the center of the screen.

Currently, I have figured out how to implement the rotation using:

rotateY(180deg)

when the button is clicked:

$('#enlarge').on('click',
    function() {
        $('#kidCard').toggleClass("flipper");
    });

The rotation effect is set in the 'flipper' class, but I need assistance with the rest of the desired animation. Can anyone provide guidance?

Update:

Here is the current HTML code:

<div class="flip-container">
    <div class="card text-white bg-primary mb-3 kid-card" id="kidCard">
        <div class="card-header">
            Child name: ...
            <i class="fa fa-trash-o" aria-hidden="true" style="cursor: pointer"></i>
        </div>
        <div class="card-body kid-card-content">
            <div class="kid-card-content-image">
                <img src="~/Content/download.png" width="110" height="110"/>
            </div>
            <div class="kid-card-content-description">
                <p class="card-text">
                    Age: ...
                </p>
                <p class="card-text">
                    Gender: ...
                </p>
                <p class="card-text">
                    Height: ...
                </p>
                <p class="card-text">
                    Weight: ...
                </p>
            </div>
        </div>
        <div class="card-footer">
            <button class="btn btn-secondary" id="enlarge">Edit</button>
        </div>
    </div>
</div>

JavaScript file:

$('#enlarge').on('click',
    function() {
        $('#kidCard').toggleClass("flipper");
    });

Current CSS code:

.flip-container .flipper {
    transform: rotateY(180deg);
}

.flipper {
    transition: 2s;
    transform-style: preserve-3d;
    position: relative;
}

I also tried using

translateY(calc(50vh - 50%)) translateX(calc(50vh - 50%))
in the transform property to center the element on the screen, but it did not work as expected.

SOLUTION:

I was able to make it work with the following code (thanks to all for your contributions):

JS file:

$.fn.toggleZindex= function() {
            const $this = $(this);
            if($this.css("z-index")=="auto") {
                $this.css("z-index", "99999");
            }else {
                $this.css("z-index", "auto");
            }

            return this;
        };

        $.fn.animateRotate = function(angle, duration, easing, startingDegree, complete) {
            var args = $.speed(duration, easing, complete);
            var step = args.step;
            return this.each(function(i, e) {
                args.complete = $.proxy(args.complete, e);
                args.step = function(now) {
                    $.style(e, 'transform', 'rotateY(' + now + 'deg)');
                    if (step) return step.apply(e, arguments);
                };

                $({ deg: startingDegree}).animate({deg: angle}, args);
            });
        };

        function getRotationDegrees(obj) {
            const matrix = obj.css("-webkit-transform") ||
                obj.css("-moz-transform")    ||
                obj.css("-ms-transform")     ||
                obj.css("-o-transform")      ||
                obj.css("transform");
            if(matrix !== 'none') {
                const values = matrix.split('(')[1].split(')')[0].split(',');
                const a = values[0];
                const b = values[1];
                var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
            } else { var angle = 0; }
                    return (angle < 0) ? angle + 360 : angle;
        }

        $('.editChildButton').on('click',
            function () {
                const idOfChild = $(this).attr('ChildId');
                const tc = $(window).height() / 2 - $('.item').height() / 2 - $(this.closest('.item')).offset().top;
                const lc = $(window).width() / 2 - $('.item').width() / 2 - $(this.closest('.item')).offset().left;

                $(this.closest('.item')).toggleZindex();

                const startingDegree = getRotationDegrees($(this.closest('.item')));

                $(this.closest('.item')).animateRotate(startingDegree == 0 ? 180 : 0, 2000, 'swing', startingDegree);

                $(this.closest('.item')).animate({
                    left: lc,
                    top: tc
                }, 2000, function () {
                    $(this.closest('.item')).css({ position: 'fixed', left: $(this.closest('.item')).offset().left, top: $(this.closest('.item')).offset().top });
                    $(this.closest('.item')).animate({
                        left: 0,
                        top: 0,
                        width: '100vw',
                        height: '100vh'
                    },2000);
                });
            });

Answer №1

If you're looking to optimize the movement of cards, consider utilizing the position: absolute property.

When centering a div on screen, understanding the element's dimensions is crucial during transitions. If manual dimension setting is feasible, use:

left: calc(50% - manuallySetWidth);
top: calc(50% - manuallySetHeight);

If manual setting isn't an option, explore alternative methods like CSS variables which offer flexibility in positioning elements. Check out this resource for a guide on using CSS variables effectively.

The code includes comments for clarity.

//define vars for css usage
$('#kidCard')[0].style.setProperty('--width', $('#kidCard').width()+'px');
$('#kidCard')[0].style.setProperty('--height', $('#kidCard').height()+'px');

$('#enlarge').on('click',
  function() {
    $('#kidCard').toggleClass("flipper");
    $('body').toggleClass("shady");
});
body{
  transition: 1s;
}

body.shady{
  background: rgba(0,0,0,.8);
  
}

.flip-container .card {
  left: 0;/*manually set each card's left and top in order for the translation to work smoothly, */
  top: 0;/*if you have them in a grid you could use i and j to do this */
  text-align: center;
  border: 1px solid red;
  transition: 1s;
  position: absolute;
  background: white;
}

.flip-container .card.flipper {
  transform: rotateY(360deg);
  left: calc(50% - var(--width)/2); /*use the variables set in js*/
  top: calc(50% - var(--height)/2);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flip-container">
<div class="card text-white bg-primary mb-3 kid-card" id="kidCard">
<div class="card-header">
Child name: ...
<i class="fa fa-trash-o" aria-hidden="true" style="cursor: pointer"></i>
</div>
<div class="card-body kid-card-content">
<div class="kid-card-content-image">
<img src="~/Content/download.png" width="110" height="110"/>
</div>
<div class="kid-card-content-description">
<p class="card-text">
Age: ...
</p>
<p class="card-text">
Gender: ...
</p>
<p class="card-text">
Height: ...
</p>
<p class="card-text">
Weight: ...
</p>
</div>
</div>
<div class="card-footer">
<button class="btn btn-secondary" id="enlarge">Edit</button>
</div>
</div>
</div>

Answer №2

I believe that achieving a specific effect may require more than just CSS animations. One approach could be to adjust the positioning to fixed, center the card, and scale it according to your needs. You can see a demonstration here.

While the example provided is for a single card, it should also work with multiple cards in different positions. When clicking on the card:

  1. It rotates 180 degrees (although the reason for this exact rotation is unclear),
  2. Moves to the center of the viewport,
  3. Changes size to occupy the entire viewport.

The animation functions bidirectionally.

HTML:

<div class="flip-container">
    <div class="card text-white bg-primary mb-3 kid-card" id="kidCard">
        <div class="card-header">
            Child name: ...
            <i class="fa fa-trash-o" aria-hidden="true" style="cursor: pointer"></i>
        </div>
        <div class="card-body kid-card-content">
            <div class="kid-card-content-image">
                <img src="~/Content/download.png" width="110" height="110"/>
            </div>
            <div class="kid-card-content-description">
                <p class="card-text">
                    Age: ...
                </p>
                <p class="card-text">
                    Gender: ...
                </p>
                <p class="card-text">
                    Height: ...
                </p>
                <p class="card-text">
                    Weight: ...
                </p>
            </div>
        </div>
        <div class="card-footer">
            <button class="btn btn-secondary" id="enlarge">Edit</button>
        </div>
    </div>
</div>

CSS:

.flip-container {
  width: 400px;
}

.flip-container .flipper {
    transform: rotateY(180deg);
}

.card {
  transition-duration: 2s;
}

.movement {
  transform: translate(-50%,-50%) rotateY(180deg);
}

JS:

var element = $('#kidCard');
var w = element.width();
var h = element.height();

$('#enlarge').on('click',
  function() {
    if(element.hasClass('movement')) {
      element.removeClass('movement');
      element.css({width: w, height: h, top: 0, left: 0});
    } else {
      var left = element.offset().left;
      var top = element.offset().top;
      element.css({position: 'fixed', left: left, top: top, width: w, height: h});
      element.addClass('movement');
      element.css({width: '100vw', height: '100vh', top: '50%', left: '50%'});
   }
});

Answer №3

To center a block level element, one approach is to specify a width for your flipper class and set the margins to auto. By setting both a width value and margin:auto, you can achieve center alignment.

.flip-container .flipper {
    transform: rotateY(180deg);
}

.flipper {
    transition: 2s;
    margin: auto;
    width:400px;
    height:400px;
    transform-style: preserve-3d;
    position: relative;
}

Here is a fiddle

Alternatively, if you prefer a flexbox solution, you can use the following code:

.flip-container .flipper {
    transform: rotateY(180deg);
}

.flipper {
    transition: 2s;
    transform-style: preserve-3d;
    position: relative;
    width:400px;
    height:400px;
}

.body-flipper {
  display:flex;
  justify-content: center;
}

body, html{
  width:100% !important;
  height: 100% !important;
  margin:0;
}

Here is a 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

Error message 'Access is Denied' occurs when using Angular.js xhr.open()

Currently, I am developing an angular web application that needs to be compatible with IE10. One of the requirements is to make a cross-domain call to our enterprise salesforce server. When using Chrome (not officially supported but commonly used for devel ...

Managing browser cache while developing locally

During development testing, how can you selectively disable caching for local scripts and styles while keeping cache enabled for external ones? Ideally in Firefox. When editing css, js, or sprite files on my developmental site, I find myself needing to fr ...

Eliminate unnecessary spacing from the sticky container

Trying to implement a sticky menu in an angular 14 project using angular material 14 has been quite challenging for me. Initially, I attempted to use the 'fixed' position, but encountered issues where the menu would consistently return to the to ...

Displaying the blog post title in the metadata information

Currently, I am facing a challenge with my Jekyll site's Search Engine Optimization because I am having difficulty setting meta information. ... <meta name="og:title" content="{{ seo_title }}" /> ... <!-- now in my for post-loop: --> {% f ...

How can I add content to the body of a modal in Bootstrap 3?

My application has a button that, when clicked, is supposed to trigger a modal popup containing some data. I want the data in the modal to come from another application via a PHP file accessed through a URL. How can this be achieved? <?php echo '& ...

In JavaScript, the function will return a different object if the string in an array matches the

My task involves working with a simple array of string ids and objects. Upon initial load, I am matching these Ids with the objects and setting the checked property to true. const Ids = ['743156', '743157'] [ { "id&quo ...

I am looking to implement a straightforward drag-and-drop feature using jQuery

Is it possible to drag and select 4 buttons in a browser, similar to how you would do on Windows, using jQuery locally? ...

Applying CSS selectors to target child elements within a select option

I am looking to apply a CSS selector only on select option child values. I have assigned an id to the selector and now I want to apply different CSS styles to each child (child 1, child 2, etc). <select name="options[81]" id="select_81" class="required ...

Tips for concealing a parent element while inside a span with jquery

Beginner asking for help! Take a look at what I've coded: <div class="Links"> <a href="/testthis1.html" data-id="button1"> <img class="icon" src="/test1.png" alt="test1"> <span>Test 1</span> < ...

Discovering the Modification of a Variable Value in angularJS

Within my HTML markup, I have the following input field: <input id="Search" type="text" placeholder="Search Images.." ng-model="data" ng-keypress="($event.charCode==13)? searchMore() : return"> This input field serves as a search bar for us ...

Avoid reloading javascript if functions are already present to guarantee synchronous loading

By utilizing JQuery.load(), I have the ability to update the content of my website's mainWindow, enabling users to easily switch between tabs. Each tab contains one or more scripts that house functions which are executed once the tab content has been ...

The element is not occupying the full width within the div container

I'm working with a div that contains some elements. My goal is to have these elements span the entire width of the container div. .container { height: 100px; width: 100px; display: flex; flex-direction: column; overflow: scroll; borde ...

I'm currently facing difficulties transferring data as I'm unable to pinpoint the error in my jQuery Ajax code

I am currently working on my index page and I have a requirement to submit form data without reloading the page. To achieve this, I want to utilize AJAX with jQuery for a seamless user experience. Could you provide feedback on my implementation using jQue ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Is it possible to execute JavaScript in VSCode without the need for Node.js?

Is there a way to run JavaScript in VSCode using a school-issued laptop that does not allow the download of Node.js? I have searched for alternatives, but most tutorials recommend downloading Node.js. ...

Ways to block WebSocket access on a personal computer

Is it possible to protect my server resources from being accessed by other websites, such as example.com, via WebSocket? I want to prevent them from accessing the server using a URL like "ws://47.80.151.189:1234", and utilizing its resources (bandwidth, me ...

Issues with Navigating through a Scrollable Menu

I'm having a difficult time grasping the concept and implementing a functional scrolling mechanism. Objective: Develop a large image viewer/gallery where users can navigate through images by clicking arrow keys or thumbnails in a menu. The gallery an ...

When trying to log the parsed JSON, it unexpectedly returns undefined even though it appears to be in good

Everything was working fine until a couple of days ago. Let's consider this as my PHP script: echo json_encode(array('stat'=>'ok')); I am sending an AJAX request to this script: $.post(base_url+'line/finalize/', {t ...

Exploring CSS3 animations: customizing animations for individual elements based on scroll movements

Can you help me with CSS3 animations triggered by scrolling? I came across a code that reveals a DIV element as the user scrolls down: <script type="text/javascript"> $(document).ready(function() { /* Every time the window ...

Load jQuery in PHP script and return it

After searching around, I have not been able to find a suitable example for what I am trying to accomplish. Here is the scenario that I am facing: On a page (constructed in PHP and HTML), there is an included PHP script (currentMonth.php) that runs when th ...