Clicking the button causes the div to shift from its original position

Issue

Whenever the buttons for playoff season or regular are clicked, the divs containing the content players-list and players-regular seem to move out of place as they fade in and out. How can this movement be prevented?

I attempted using position fixed on certain elements, but it caused severe misalignment. You can view a JSFiddle example here: http://jsfiddle.net/onlyandrewn/gcthaffs/

Click Event

 // Click event to toggle between sheets
    $('button').click(function() {
        $('button').removeClass("active");
        $(this).toggleClass("active");

        if ($('button.regular').hasClass('active')) {
            $('#players-list').fadeOut(500);
            $('.note').fadeOut(500);
            $('#players-regular').fadeIn(2000);
        } else {
            $('#players-regular').fadeOut(500);
            $('#players-list').fadeIn(2000);
            $('.note').fadeIn(2000);
        }
    });

index.html

<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
    <meta charset="UTF-8">
    <title>Wheat Kings' leading point scorers</title>
    <meta name="description" content="Wheat Kings' leading point scorers">
    <meta name="author" content="Andrew Nguyen">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="assets/css/style.css">
    <link href='http://fonts.googleapis.com/css?family=Lato:300,400,700,900' rel='stylesheet' type='text/css'>
</head>
<body>
    <h1>Wheat Kings leading goal scorers</h1>
    <p class="year"></p>
    <button class="playoffs active">Playoffs</button>
    <button class="regular">Regular Season</button>

    <div class="top">
        <div id="players-list"></div>
        <div id="players-regular"></div>

        <p class="note">Note: Since there was a five-way tie for 6th place, players who scored two goals were then ranked by their total points in the playoffs. The other two players not listed here are Nolan Patrick and Macoy Erkamps.</p>
    </div><!-- /.top -->

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tabletop.js/1.3.5/tabletop.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.0/handlebars.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.js"></script>

    <!-- Template for data goes here -->
    <script id="players" type="text/x-handlebars-template">
        <div class="container">
            <div class="group">
                <div class="{{row}}">
                    <p class="goals">{{goals}}</p>
                    <img src="{{image}}" alt="" class="head">
                    <p class="name">{{name}}</p>
                    <p class="position">{{position}}</p>
                </div><!-- /.group -->
            </div><!-- /.row -->
        </div><!-- /.container -->
    </script>

    <script type="text/javascript">
    // Click event listener
    $('button').click(function() {
        $('button').removeClass("active");
        $(this).toggleClass("active");

        if ($('button.regular').hasClass('active')) {
            $('#players-list').fadeOut(500);
            $('.note').fadeOut(500);
            $('#players-regular').fadeIn(2000);
        } else {
            $('#players-regular').fadeOut(500);
            $('#players-list').fadeIn(2000);
            $('.note').fadeIn(2000);
        }
    });

      // Original
      var public_spreadsheet_url = "https://docs.google.com/spreadsheets/d/1RMN49oyRlTxW5kv8MnYJwQRttis2csgVFH46kyORCaQ/pubhtml";

      $(document).ready( function() {
        Tabletop.init( { key: public_spreadsheet_url,
            callback: showInfo,
            parseNumbers: true } );
      });
      function showInfo(data, tabletop) {
        var source   = $("#players").html();
        var template = Handlebars.compile(source);

        $.each(tabletop.sheets("Playoffs").all(), function(i, fact) {
            var html = template(fact);
            
          $("#players-list").append(html);
          $('.container').eq(i).addClass(data.Playoffs.elements[i]);
      })

        $.each(tabletop.sheets("Regular").all(), function(i, fact) {
            var html = template(fact);
            
          $("#players-regular").append(html);
          $('.container').eq(i).addClass(data.Regular.elements[i]);
      });
    }
</script>
</body>
</html>

base.scss

/*----------------------------------
MAIN STYLES
----------------------------------*/

html {
  font-size: 62.5%; /* 10px browser default */
}

body {
    max-width: 600px;
    padding: 10px;
}

.top {
    max-width: 600px;
}

#players-list,
#players-regular {
}

h1 {
    font-family: 'Lato', sans-serif;
    font-weight: 900;
    border-bottom: 1px solid #ccc;
    padding-bottom: 8px;
}

.note {
    position: relative;
    width: 95%;
    left: 3%;
}

Answer №1

The reason for this issue is that the fadeOut effect is not finished by the time the fadeIn effect begins. This results in both divs being visible briefly, creating a noticeable jump when the first div disappears.

One possible solution could be:

$('#players-list').fadeOut(500, function() {
     $('#players-regular').fadeIn(500);
 }); 

By implementing this change, the second div will only appear once the first one has completely faded out. It's also recommended to reduce the animation duration slightly for a smoother user experience ;).

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

How to Execute a Java Method Using a JavaScript Function?

I've been doing some research, but haven't come across a straightforward answer to my question. Imagine I have an HTML page with embedded Javascript code, as well as a java.class file located in a package named somePackage.someSubPackage.*; Is t ...

The appearance of a CSS select box may vary across different computers and web browsers

The appearance of a select box in HTML can vary between different computers and browsers. For example, on one computer using Google Chrome, the select box may look like this: https://i.stack.imgur.com/g2Xnn.png However, on my computer with Google Chrome, ...

Guide to crafting a regular expression for constructing a path

Can anyone help me with writing a regular expression for the following path? /private/toolbox/* I'm stuck because of the * wildcard character. I've successfully added the two paths below without any issues: /private/healthcheck /private/da ...

Exploring Angular 11 Testing: Troubleshooting Async Issues in Jest with RxJS Timer

I encountered an issue while working on a test where I received the following error message: "Timeout - Async callback was not invoked within the 5000 ms timeout specified by jest.setTimeout.Error: Timeout - Async callback was not invoked within the 5 ...

positioning two out of three items in a navigation menu to the right and the remaining one to the left

I am looking to design a navigation bar that spans the full width of the screen, with the logo on the left side serving as a link back to the home page. Additionally, I want to include elements for register/login and cart. The background color should cove ...

`The header navigation is not responding to window resizing functionality`

I am currently developing a header navigation that consists of a logo on the left side, a profile icon on the right side, and some navigation links in the middle. A left slide menu has been implemented to trigger when the window width is less than 700px. ...

Angular JS Form's Pristine feature is malfunctioning when attempting to reset

I implemented a login form on my website. After submitting the form, I clear it and set it to Pristine mode. However, the error message still persists. Below is the code for my form: <form name="loginForm" ng-submit="loginForm.$valid && login( ...

Tips on returning the array

I've been struggling to figure out how to extract the 'sheetsArray' from the code snippet below so that I can use it for various tasks. Despite my efforts and hours of searching online, I haven't been able to find a solution. It seems l ...

JavaScript forEach: alter items

I am facing an issue with using the forEach method on an array. Despite it being a mutator, it is not mutating the values in the original array as expected. Can anyone help me figure out what could be causing this problem? let array = [1, 2, 3, 4]; //de ...

What are the reasons behind the issues encountered when enabling "Optimization" feature in Angular that affect the proper rendering of PrimeNg elements?

Angular Version : 9.x Primeng Version : 9.x We've encountered an issue with PrimeNg elements not rendering correctly in our dev/prod environments, although they work fine in the local environment. After some investigation, we found that the culprit ...

Tips on ensuring that the Google Maps marker remains in the center as you drag the map with the AGM component

I've implemented AGM (Angular Google Maps) in my Ionic Project to showcase Google Maps, and I'm looking to have the marker stay centered on the map even when it is dragged. Is there a way to achieve this with AGM? Please let me know if I have mad ...

Tips for Keeping Footer Aligned with Content:

When checking out this website, you may notice that the footer appears to be affixed to the left side. The CSS code responsible for this is as follows: #footer { width: 800px; clear:both; float:right; position:relative; left:-50%;} I would appreciate it ...

What is the best way to link a file to index.html using feathers.js?

I am currently learning feathers and encountering a problem. I am attempting to include files similar to PHP's switch function. For instance: /src/middleware/index.js 'use strict'; const handler = require('feathers-errors/handler&ap ...

What is the method to retrieve response text?

This is the content of my register.js file: var formdata = new FormData(); formdata.append("name", name.value); formdata.append("username", username.value); formdata.append("email", email.value); formdata.append("password", password.value) ...

Specify the return type based on specific parameter value

I'm facing a situation where I have two definitions that are identical, but I need them to behave differently based on the value of the limit parameter. Specifically, I want the first definition to return Promise<Cursor<T>> when limit is g ...

What is the method for specifying a string argument type from a string list and executing a mongo db query?

Is there a way to specify the argument type in a function as a string from a list of strings in order to run a MongoDB query? Here is what I am currently attempting: users.services.ts async findOne(key: "_id" | "email" | "username", value: string) { ...

What method does the framework use to determine the specific API being accessed?

How can the framework determine which API is being accessed? app.get('/user/:userId/name/export', function (req, res) { var userId = req.params.userId; } app.get('/user/:userId/name/:name', function (req, res) { var userId = req ...

Is it possible to set a read-only attribute using getElementByName method

To make a text field "readonly" by placing JavaScript code inside an external JS file, the HTML page cannot be directly modified because it is located on a remote server. However, interaction can be done by adding code in an external JS file hosted on a pe ...

No success with ajax following the execution of a php script

Utilizing a php-script, I am able to execute a database backup of my website with the simple click of a button on the admin-panel. To enhance user experience, I want to display real-time updates in the admin-panel during the backup process, indicating whe ...

No matter which file URL is provided, Ajax consistently returns error 500

I am encountering a server 500 error when trying to execute the following code. Even after testing it with a sample file, the error persists. The file permissions are set to 644. Below is the Ajax snippet: function paynlSubmitPayment(userid ,credits ,pro ...