2-D
2-D

Reputation: 109

How can I dynamically center a div in the screen with JQuery and Translate

I have the following problem: I want the tariffCard > div to be centered on the screen when clicked. I need the centering to be animated. Thereby, I decided to don't do it by changing the left/top position with JQuery, since it would make the animation rough.

Thus I choose to follow the following strategy:

    var leftPos = $(this).offset().left;
    var topPos = $(this).offset().top;
    var cardWidth = $(this).width();
    var cardHeight = $(this).height();
    var docWidth = $(document).width();  
    var docHeight = $(document).height();  
    var main = $(this);

    var moveRight = (docWidth - cardWidth)/2 - leftPos;
    var moveTop = (docHeight - cardHeight)/2 - topPos;
    $('.selected').css({"transform": "translateX(-" + moveRight + ") translateY(-" + moveTop + ") !important"});

The following issues are catching me:

This is the entire code:

$(document).ready(function(){
  $('.tariffCards > div').click(function(){
    var leftPos = $(this).offset().left;
    var topPos = $(this).offset().top;
    var cardWidth = $(this).width();
    var cardHeight = $(this).height();
    var docWidth = $(document).width();  
    var docHeight = $(document).height();  
    var main = $(this);
   
    var moveRight = (docWidth - cardWidth)/2 - leftPos;
    var moveTop = (docHeight - cardHeight)/2 - topPos;
    // console.log(cardWidth)
    // console.log(cardHeight)
    // console.log(leftPos)
    // console.log(moveRight)


    // Cria o Overlay
    $("body").append("<div id='overlay'></div>");

    $("#overlay")
      .height(docHeight)
      .css({
         'backdrop-filter': 'blur(3px)',
         'background-color': 'rgba(0,0,0,0.4)',
         'left': 0,
         'position': 'absolute',
         'top': 0,
         'width': '100%',
         'z-index': 1
      }).fadeIn('3000', function(){
          $('#overlay').show();
      });
    // transform: rotateY(-180deg) translateX(-90%) !important;
    // console.log("")
    // Some com o scroll
    $('body').css('overflow-y', 'hidden');
    // Some com os outros Cards
    $(main).siblings().css("opacity", 0);
    
    // Gira e centraliza o Card @Rever centralização
    setTimeout(function() {
      main.toggleClass('not-selected');
      main.find('h3').css("opacity", 0);
      main.find('span').css("opacity", 0);
      main.toggleClass('selected');
      // Ainda tenho que pensar como centralizar isso de um modo responsivo
      $('.selected').css({"transform": "rotateY(-180deg) translateX(-100%) !important"});
             
      $('.form-report').click(function(e) {
          e.stopPropagation();
      });
      
      $('#name-input').focus();
    }, 200);  

    setTimeout(function(){
     // Organiza o form dentro do Card
      $('.selected .form-report').css({
          "display":"inherit",
          "opacity": 1,
          "transform":"scaleX(-1)"
      });
    }, 600);
  });
});
	
	// Ao clicar no Overlay
	jQuery('body').on('click', '#overlay', function(){

    var main = $('.selected');

    $('.form-report').fadeOut('300', function(){
      $(this).hide();
    });

    $('#overlay').fadeOut('300',function(){
    $('#overlay').hide();
    });

    main.toggleClass('selected');
    // $('.tariffCards > div')
    // .css({"transform":'rotateX(45deg) rotateY(-15deg) rotate(45deg)', "height":"180px"
    // });

    setTimeout(function() {
      main.toggleClass('not-selected');
      $('.tariffCards > div').siblings().css("opacity", 1);
      $('.tariffCards > div h3').css("opacity", 1);
      $('.tariffCards > div span').css("opacity", 1);
    }, 900);    

    // Reaparece com o scroll
    $('body').css('overflow-y', 'scroll')
    
    
	});
.tariffCards {
  left: 25%;
  position: absolute;
  top: 100%;
  transform-style: preserve-3d;
  z-index: 2;
}

.tariffCards > div {
  border-radius: 12px;
  color: #fff;
  cursor: pointer;
  height: 180px;
  margin-top: -70px;
  overflow: hidden;
  position: relative;
  transform: rotateX(45deg) rotateY(-15deg) rotate(45deg);
  transition: all .9s ease-in-out;
  width: 330px;
}

.tariffCards > div h3 {
  bottom: 30%;
  font-size: 18px;
  font-weight: 800;
  left: 20%;
  position: relative;
  transform: rotate(-90deg);
}

.tariffCards > div span {
  font-size: 12px;
  font-weight: 700;
  left: 35%;
  opacity: .8;
  position: absolute;
  top: -6%;
  transform: rotate(-90deg);
  width: 100%;
}
.tariffCards > .lren {
  background-color: #8063e1;
  background-image: linear-gradient(135deg, #bd7be8, #8063e1);
  box-shadow: 20px 20px 60px rgba(34,50,84,0.5), 1px 1px 0px 1px #8063e1;
}
.tariffCards > div.movi {
  background-color: #3f58e3;
  background-image: linear-gradient(135deg, #7f94fc, #3f58e3);
  box-shadow: 20px 20px 60px rgba(34,50,84,0.5), 1px 1px 0px 1px #3f58e3;
}
.tariffCards > div.flry {
  background-color: #2c6fd1;
  background-image: linear-gradient(135deg, #21bbfe, #2c6fd1);
  box-shadow: 20px 20px 60px rgba(34,50,84,0.5), 1px 1px 0px 1px #2c6fd1;
}
.tariffCards > div.pard {
  background-color: #352f64;
  background-image: linear-gradient(135deg, #415197, #352f64);
  box-shadow: 5px 5px 60px rgba(34,50,84,0.9), 1px 1px 0px 1px #352f64;
}

.not-selected{
  transition: all .4s ease !important;
  /*z-index: -1 !important;*/
}

.not-selected:hover {
  transform: rotateX(30deg) rotateY(-15deg) rotate(30deg) translate(-25px, 50px) !important;
}

.selected {
  height: 55vh !important;
  transform: rotateY(-180deg) translateX(-280px) !important;
  z-index: 3 !important;
}

/*Formulário de inscrição*/
.form-report{
    display: none;
    margin: 0 auto;
    opacity: 0;
    text-align: center;
    transition: all 2s;
    width: 80%;
}

.form-report form{
    margin-top: 10%;
    margin-bottom: 5%;
}
.form-report form input{
    color: black;
    width:100%;
}

.container-btn a{
    background-image: linear-gradient(56deg, #08AEEA 0%, #2AF598 100%);
    border:none;
    border-radius: 100px;
    box-shadow:0px 10px 10px rgba(0,0,0,0.2);;
    color: #fff;
    display: inline-block;
    font-size: 1.3em;
    padding: 4% 0;
    transition: all .2s;
    width: 70%;
}

.container-btn a:hover{
    transform: translateY(3px);
}
<!DOCTYPE html>
<html>
<head>
    <title>HomePage</title>
    <link rel="stylesheet" type="text/css" href="home.css">
</head>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <div class="tariffCards">
        <div class="lren not-selected">
            <h3>Lojas Renner<br><br>$LREN3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
        <div class="movi not-selected" id='movi3'>
            <h3>Movida<br><br>$MOVI3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
        <div class="flry not-selected" id='flry3'>
            <h3>Fleury S.A.<br><br>$FLRY3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
        <div class="pard not-selected" id='pard3'>
            <h3>Hermes Pardini<br><br>$PARD3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src='home.js'></script>
</body>

Upvotes: 2

Views: 1688

Answers (3)

Dupinder Singh
Dupinder Singh

Reputation: 7789

okay try this, made some changes in your code, and i was able to achive it

basic changes

added one more class

body
{
  margin-top: 200px;
  width: 100%;
  height: 100%;
  display: -webkit-flex; /* Safari */
  -webkit-justify-content: center; /* Safari 6.1+ */
  display: flex;
  justify-content: center;
}

and

.selected {
  height: 55vh !important;
  transform: rotateY(-180deg) translateX(0px) !important;
  z-index: 3 !important;
}

translateX(0px)

and remove some positions and left margins

here is running code snippet

<!DOCTYPE html>
<html>
<head>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

    <style>
        .tariffCards {
  left: 25%;
  top: 100%;
  transform-style: preserve-3d;
  z-index: 2;
}

.tariffCards > div {
  border-radius: 12px;
  color: #fff;
  cursor: pointer;
  height: 180px;
  margin-top: -70px;
  overflow: hidden;
  transform: rotateX(45deg) rotateY(-15deg) rotate(45deg);
  transition: all .9s ease-in-out;
  width: 330px;
}

.tariffCards > div h3 {
  bottom: 30%;
  font-size: 18px;
  font-weight: 800;
  left: 20%;
  transform: rotate(-90deg);
}

.tariffCards > div span {
  font-size: 12px;
  font-weight: 700;
  left: 35%;
  opacity: .8;
  top: -6%;
  transform: rotate(-90deg);
  width: 100%;
}
.tariffCards > .lren {
  background-color: #8063e1;
  background-image: linear-gradient(135deg, #bd7be8, #8063e1);
  box-shadow: 20px 20px 60px rgba(34,50,84,0.5), 1px 1px 0px 1px #8063e1;
}
.tariffCards > div.movi {
  background-color: #3f58e3;
  background-image: linear-gradient(135deg, #7f94fc, #3f58e3);
  box-shadow: 20px 20px 60px rgba(34,50,84,0.5), 1px 1px 0px 1px #3f58e3;
}
.tariffCards > div.flry {
  background-color: #2c6fd1;
  background-image: linear-gradient(135deg, #21bbfe, #2c6fd1);
  box-shadow: 20px 20px 60px rgba(34,50,84,0.5), 1px 1px 0px 1px #2c6fd1;
}
.tariffCards > div.pard {
  background-color: #352f64;
  background-image: linear-gradient(135deg, #415197, #352f64);
  box-shadow: 5px 5px 60px rgba(34,50,84,0.9), 1px 1px 0px 1px #352f64;
}

.not-selected{
  transition: all .4s ease !important;
  /*z-index: -1 !important;*/
}

.not-selected:hover {
  transform: rotateX(30deg) rotateY(-15deg) rotate(30deg) translate(-25px, 50px) !important;
}

.selected {
  height: 55vh !important;
  transform: rotateY(-180deg) translateX(0px) !important;
  z-index: 3 !important;
}

/*Formulário de inscrição*/
.form-report{
    display: none;
    margin: 0 auto;
    opacity: 0;
    text-align: center;
    transition: all 2s;
    width: 80%;
}

.form-report form{
    margin-top: 10%;
    margin-bottom: 5%;
}
.form-report form input{
    color: black;
    width:100%;
}

.container-btn a{
    background-image: linear-gradient(56deg, #08AEEA 0%, #2AF598 100%);
    border:none;
    border-radius: 100px;
    box-shadow:0px 10px 10px rgba(0,0,0,0.2);;
    color: #fff;
    display: inline-block;
    font-size: 1.3em;
    padding: 4% 0;
    transition: all .2s;
    width: 70%;
}

.container-btn a:hover{
    transform: translateY(3px);
}

body
{
  margin-top: 200px;
  width: 100%;
  height: 100%;
  display: -webkit-flex; /* Safari */
  -webkit-justify-content: center; /* Safari 6.1+ */
  display: flex;
  justify-content: center;
}
    </style>

<script>
    $(document).ready(function(){
  $('.tariffCards > div').click(function(){
    var leftPos = $(this).offset().left;
    var topPos = $(this).offset().top;
    var cardWidth = $(this).width();
    var cardHeight = $(this).height();
    var docWidth = $(document).width();  
    var docHeight = $(document).height();  
    var main = $(this);
   
    var moveRight = (docWidth - cardWidth)/2 - leftPos;
    var moveTop = (docHeight - cardHeight)/2 - topPos;
    // console.log(cardWidth)
    // console.log(cardHeight)
    // console.log(leftPos)
    // console.log(moveRight)


    // Cria o Overlay
    $("body").append("<div id='overlay'></div>");

    $("#overlay")
      .height(docHeight)
      .css({
         'backdrop-filter': 'blur(3px)',
         'background-color': 'rgba(0,0,0,0.4)',
         'left': 0,
         'position': 'absolute',
         'top': 0,
         'width': '100%',
         'z-index': 1
      }).fadeIn('3000', function(){
          $('#overlay').show();
      });
    // transform: rotateY(-180deg) translateX(-90%) !important;
    // console.log("")
    // Some com o scroll
    $('body').css('overflow-y', 'hidden');
    // Some com os outros Cards
    $(main).siblings().css("opacity", 0);
    
    // Gira e centraliza o Card @Rever centralização
    setTimeout(function() {
      main.toggleClass('not-selected');
      main.find('h3').css("opacity", 0);
      main.find('span').css("opacity", 0);
      main.toggleClass('selected');
      // Ainda tenho que pensar como centralizar isso de um modo responsivo
      $('.selected').css({"transform": "rotateY(-180deg) translateX(-100%) !important"});
             
      $('.form-report').click(function(e) {
          e.stopPropagation();
      });
      
      $('#name-input').focus();
    }, 200);  

    setTimeout(function(){
     // Organiza o form dentro do Card
      $('.selected .form-report').css({
          "display":"inherit",
          "opacity": 1,
          "transform":"scaleX(-1)"
      });
    }, 600);
  });
});
	
	// Ao clicar no Overlay
	jQuery('body').on('click', '#overlay', function(){

    var main = $('.selected');

    $('.form-report').fadeOut('300', function(){
      $(this).hide();
    });

    $('#overlay').fadeOut('300',function(){
    $('#overlay').hide();
    });

    main.toggleClass('selected');
    // $('.tariffCards > div')
    // .css({"transform":'rotateX(45deg) rotateY(-15deg) rotate(45deg)', "height":"180px"
    // });

    setTimeout(function() {
      main.toggleClass('not-selected');
      $('.tariffCards > div').siblings().css("opacity", 1);
      $('.tariffCards > div h3').css("opacity", 1);
      $('.tariffCards > div span').css("opacity", 1);
    }, 900);    

    // Reaparece com o scroll
    $('body').css('overflow-y', 'scroll')
    
    
	});
</script>

</head>


    <div class="tariffCards">
        <div class="lren not-selected">
            <h3>Lojas Renner<br><br>$LREN3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
        <div class="movi not-selected" id='movi3'>
            <h3>Movida<br><br>$MOVI3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
        <div class="flry not-selected" id='flry3'>
            <h3>Fleury S.A.<br><br>$FLRY3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
        <div class="pard not-selected" id='pard3'>
            <h3>Hermes Pardini<br><br>$PARD3</h3>
            <span>Atualizado em 2T19</span>
            <!--Form aberto ao clicar no relatório-->
            <div class='form-report'>
                <h2>Receba agora.</h2>
                <form>
                    <input type="text" id='name-input' placeholder="Nome">
                    <br/>
                    <input type="text" placeholder="Seu Email">
                    <br/>
                    <input type="text" placeholder="Celular (SMS de Confirmação)">
                </form>
                
                <br/>

                <div class='container-btn'>
                    <a href="#"><img src='http://edufinance.com.br/wp-content/uploads/2019/08/noun_down-arrow.png' width='12%'>
                    </a>
                </div>
            </div>
        </div>
    </div>
    <script type="text/javascript" src='home.js'></script>

</html>

Upvotes: 0

symlink
symlink

Reputation: 12208

You can do the animation part with CSS, and use a JavaScript click event that adds a class to the element:

var el = document.getElementById("centerme");

el.addEventListener("click", moveToCenter);

function moveToCenter()
{
    if(!el.classList.contains("centered")){
        el.classList += "centered";
    }
}
#centerme{
    width: 100px;
    height: 40px;
    background: dodgerblue;
     margin-left: 0%;
     transition: all 1s ease-in;
}

#centerme.centered{
    margin-left: 50%;
    transform: translateX(-50%);
}
<div id="centerme"></div>

Upvotes: 0

Dupinder Singh
Dupinder Singh

Reputation: 7789

if you have no issues with CSS, please use CSS to justify-content in the centre.

Why not JavaScript/Jquery: out custom javascript/jquery logic can lead to performance issues, because when we align some element in HTML DOM, then element removed and render at specified places.

So, I don't think this is not a good idea to justify a div after rendering in a page.

Why CSS: when the object is about to render at that time browser will decide where to place Element in Page, so using CSS we save the multiple time of rendering of an element in the page.

so this may help

div {
    display: flex;
    justify-content: center;
}

Upvotes: 1

Related Questions