What steps can I take to prevent the div from exiting the screen during animations?

Hello, I am a novice in the field of web development and I am attempting to create a website where, upon loading it, a text with a typing animation will appear centered in the middle. Eventually, the remaining words in the div will be 'Nice Paws'. Subsequently, there will be an animation that translates its Y position and moves it to the top of the screen.

My question is how can I translate the Y position so that it always ends up at the top of the screen without disappearing when the window is resized?

Any assistance on this matter would be greatly appreciated! Thank you!

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="81e3eeeef5f2f5f3e0f1c1b4afb3afb3">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
    <!-- <nav class="trans"></nav> -->
    <div class="slogan-container" id="slogan-container">
        <div id="slogan"></div><div class="brand-name" id="name-typed"></div>
    </div>
    <div style="height: 100%; background-color: aliceblue;"></div>   
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfaba6afbabbf1b5ac9fedf1eff1eeed">[email protected]</a>"></script>
    <script src="index.js"></script>
</body>
</html>

CSS

html, body {
    height: 100%;
    background-color: antiquewhite !important;
    overflow: auto;
}

.slogan-container {
    font-family: 'Lexend Deca', sans-serif;
    font-size: 30px;
    font-weight: 400;

    height: 100%;
    width: 100%;

    display: flex;
    align-items: center;
    justify-content: center;

    position: relative;
}

.brand-name {
    font-family: 'Lexend Deca', sans-serif;
    font-weight: 600; 
}

.slogan {
    
}

JS

var slogan = new Typed("#slogan", {
    strings: ["Damn, those are some&nbsp;", ""],
    typeSpeed: 25,
    backSpeed: 19,
    loop: false,
    showCursor: false,
    backDelay: 1500,
    onStringTyped: function(pos, slogan) {
        if(pos == 0) {
            var name = new Typed("#name-typed", {
                strings: ["Nice Paws"],
                typeSpeed: 25,
                loop: false,
                showCursor: false,
            })
        } else if(pos == 1) {
            // height = document.getElementById("slogan-container").offsetHeight;
            // console.log(height);
            const move = [
                { transform: 'translateY(-440px)' }
                // { transform: 'translateY(-20vh)' }
            ];
            const moveTiming = {
                duration: 1500,
                delay: 500,
                fill: 'forwards',
                easing: 'ease-in-out'
            }
            var elem = document.getElementById("name-typed");
            elem.animate(move, moveTiming);
            elem.style.position = 'fixed';
            console.log(elem.style.position)
        }
    }
}) 

Fiddle:

I attempted using 'vh' instead of 'px' but when resizing the screen it simply vanishes as well.

Answer №1

To determine the necessary Y translation, you can use a formula like this: translateY(calc(-50vh + 22.5px)), with 22.5px representing half of the height of your div.brand-name.

If you opt for this method, it might be beneficial to set the line-height of that div to 45px.

Here is the updated code snippet:

const move = [
    { transform: 'translateY(calc(-50vh + 22.5px))' }
];

View the functioning JSFiddle demo

Answer №2

Instead of using translateY, this method utilizes margin-top for animation.

Prior to the transition: margin-top: calc(50vh - 30px)

Following the transition: {marginTop: "20px"}

This approach ensures that the animation on brand-name adapts to varying screen sizes and maintains a fixed position post-animation.

For a live demonstration, visit: jsfiddle

We hope this proves helpful.

Example:

var slogan = new Typed("#slogan", {
    strings: ["Damn, those are some&nbsp;", ""],
    typeSpeed: 25,
    backSpeed: 19,
    loop: false,
    showCursor: false,
    backDelay: 1500,
    onStringTyped: function(pos, slogan) {
        if(pos == 0) {
            var name = new Typed("#name-typed", {
                strings: ["Nice Paws"],
                typeSpeed: 25,
                loop: false,
                showCursor: false,
            })
        } else if(pos == 1) {

            const move = [
            {marginTop: "20px"}
            ];
            const moveTiming = {
                duration: 1500,
                delay: 500,
                fill: 'forwards',
                easing: 'ease-in-out'
            }
            var elem = document.getElementById("name-typed");
            elem.animate(move, moveTiming);
            elem.style.position = 'fixed';
            console.log(elem.style.position)
        }
    }
}) 
html, body {
    height: 100%;
    background-color: antiquewhite !important;
    overflow: auto;
}

.slogan-container {
    font-family: 'Lexend Deca', sans-serif;
    font-size: 30px;
    font-weight: 400;

    height: 100%;
    width: 100%;

    display: flex;
    align-items: flex-start;
    justify-content: center;

    position: relative;
}

.brand-name {
    font-family: 'Lexend Deca', sans-serif;
    font-weight: 600;
}

#slogan, .brand-name {
    margin-top: calc(50vh - 30px);
}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
    <link href="https://fonts.googleapis.com/css2?family=Lexend+Deca:wght@200;300;400;600&display=swap" rel="stylesheet">
    <link href="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="91f3fefee5e2e5e3f0e1d1a4bfa3bfa3">[email protected]</a>/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi" crossorigin="anonymous">
</head>
<body>
    <!-- <nav class="trans"></nav> -->
    <div class="slogan-container" id="slogan-container">
        <div id="slogan"></div><div class="brand-name" id="name-typed"></div>
    </div>
    <div style="height: 100%; background-color: aliceblue;"></div>   
    <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="73070a0316175d190033415d435d4241">[email protected]</a>"></script>
    <script src="index.js"></script>
</body>
</html>

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

In the iOS app when the Ionic HTML5 select keypad is opened, a bug causes the view to scroll upwards and create empty space after tapping the tab

I am currently working with Ionic v1 and AngularJS, utilizing ion tabs: <ion-tabs class="tabs-icon-top tabs-color-active-positive"> <!-- Home Tab --> <ion-tab icon-off="ion-home" icon-on="ion-home" href="#/tab/home"> <ion-nav ...

Tips for aligning multiple identical images horizontally using Javascript

I am attempting to use the following code to display the same image 19 times and then center all of those images horizontally on the page as a whole. However, I have been unsuccessful in getting it to work. var totImg = "large.png"; function prettyHea ...

Applying CSS styles to a class dynamically using JavaScript

Is there a way to dynamically add a new CSS property to an existing class using JavaScript? Let's say I have a class called .test with some pre-defined styling. How can I append the property color: blue; to this class using JavaScript? const elm ...

Troubleshooting Full Screen Problems with Three.js

Despite my efforts to troubleshoot, I am still encountering a frustrating issue with the Three.js API. Even after thoroughly studying the API documentation, browsing through StackOverflow questions, and using debugging tools like firebug and chrome's ...

This function is functional with jquery version 1.4.2 but encounters issues with jquery version 1.9.1

I have encountered an issue with a script that submits data to my database. The script worked perfectly on version 1.4.2, but the template I am using now requires version 1.9.1, so I updated my site accordingly. However, after the update, I am facing an er ...

Steps to display the "col-md-6" div upon hovering over list items in a different div

I have been trying to make a hover action work in my HTML document. I've managed to get it to work only when the description is a child of the li tag, but I want the description to be displayed as a separate div. <div class="row"> ...

Issues with Jquery content sliders

I am really struggling with this piece of code and I just can't seem to figure out what's causing the issue. If anyone has any insight on how I can make it display a slide for 3 seconds, fade out, show a new slide, and then loop back to the first ...

What scenarios call for the use of Content-Type as application/json?

When my server sends data to the client, should I always include headers? header('Content-type: application/json'); echo json_encode($jsondata); I have noticed that including the header doesn't seem to have any visual impact on different b ...

Utilizing jQuery with live content to determine dimensions as required

Within my web application, I have a page that dynamically retrieves a view with both HTML and JavaScript. The JavaScript is responsible for rendering a chart into the retrieved view. The problem arises because the chart library I am utilizing (flot) necess ...

pm2 doesn't play well with node dotenv

In my current project, I'm faced with an interesting issue. When running the application locally without pm2, all the environment variables in the .env file are properly recognized using dotenv. However, when deploying the app on a server and using p ...

Setting the percentage height of parent and child divs in a precise manner

Trying to work through this without causing chaos. I have a container div containing three floated left child divs, with the container div set to 100% height like so: .Container { height: 100%; min-width: 600px; overflow-y: hidden; } One of the child divs ...

I am currently using jQuery autocomplete in an attempt to display the value in the textbox as a table. The data is not being retrieved from a JSON source using Ajax directly in the text

Attempting ajax with json for autocomplete using Jquery for the first time, aiming for auto-complete appearance but table-like structure. Below is the jquery code snippet: $("document").ready(function (){ $(function () { $.ajax({ url: "dum ...

Creating an HTML table that adjusts to the screen height with square-shaped cells

var grid = document.getElementById("grid"); var size = 50; for (var y = 0; y < size; y++) { var currentRow = grid.insertRow(0); for (var x = 0; x < size; x++) { var currentCell = currentRow.insertCell(-1); currentCell.style.height = currentCell.styl ...

Utilizing Asynchronous Functions within a Loop

I have a situation where I am working with an array and need to make API calls for each index of the array. Once the API call is resolved, I need to append the result in that specific element. My goal is to ultimately return the updated array once this pro ...

The lightbox is triggered by clicking on a different div to display its content

Great news - my lightbox is up and running! Each image on my website corresponds to a different organization, and clicking on the image opens a specific lightbox. My question is: how can I have a lightbox configured so that only the trigger image is displ ...

Trouble with Bootstrap popover functionality

Twitter bootstrap-2.3.2 popover is being utilized in my BackboneJs project. When I click, a function is triggered to open the popover: <li> <a class="candidPopover" href="#" id="loginUser" rel="popover"><%= candidateName %></a> & ...

The webpage encountered an issue while trying to load a resource: the server returned a 500 (Internal Server Error) status message, preventing the submission of the data

When I use AJAX jQuery to send data via POST, the input name does not get sent and the database shows NULL as the answer. Thank you for any assistance. Below is my JQuery code: $('#btn-save').click(function(){ $.ajax({ url: "<? ...

The 'innerText' property is not present in the 'Element' type. (2339)

Recently, I've been working with javaScript and I encountered some issues while writing a function. Strangely, I kept receiving error messages that I couldn't quite understand. Initially, there was a problem where every time I tried to create a j ...

Arrange two input fields side by side if the quantity of input fields is unspecified

I am currently in the process of developing a project using Angular. I have implemented an *ngFor loop to dynamically add input fields based on the data retrieved from the backend. Is there a way I can ensure that two input fields are displayed on the same ...

Are the orders of events maintained when emitted using an event emitter?

I have a simple query regarding the event emitter, which is crucial for my program's logic. Currently, I am utilizing an external library that triggers events that I'm listening to. These events consist of 'data' and 'error'. ...