Struggling with using flexboxes and creating animated elements

Seeking assistance with animating the search bar on a website project. The animation is functioning, but the search input abruptly moves when the animation starts, as shown in this GIF:

https://i.sstatic.net/17sFl.gif

I am utilizing jQuery for the animation because I also want to implement additional actions when clicking on it, such as hiding the logo. Below is the code snippet:

$(".search-field").focus(function () {
    $(this).animate({ "width": "100%" }, "slow" );

    // $(".logo").fadeOut();
});
$(".search-field").focusout(function () {
    $(this).animate({ "width": "130px" }, "slow" );
    // $(".logo").fadeIn();
});

Could you offer a solution to prevent the abrupt movement or provide a technique to achieve a smoother transition?

Answer №1

To create a smooth animation for width, consider setting the initial width to 100% and then animating the max-width property instead.

Instead of directly using jQuery for animation, it's recommended to use the addClass / removeClass methods.

Below are the CSS modifications made along with the addition of the .expand class through JavaScript:

.search-field {
    width:100%;
    max-width:130px;
    border: 2px solid #ccc;
    border-radius: 4px;
    font-size: 16px;
    background-color: rgba(255, 255, 255, 0.3);
    background-image: url('https://cdn.rawgit.com/encharm/Font-Awesome-SVG-PNG/b7f74631/black/png/24/search.png');
    background-position: 3px 3px;
    background-repeat: no-repeat;
    padding: 6px 20px 6px 40px;
    transition: max-width 0.4s ease-in-out;
}

.search-field.expand{
    max-width:500px;
}

Here is a snippet showcasing how to add and remove the expand class on focus and focusout events:

$(".search-field").focus(function () {
    $(this).addClass('expand');
});
$(".search-field").focusout(function () {
    $(this).removeClass('expand');
    // $(".logo").fadeIn();
});
@import url('https://fonts.googleapis.com/css?family=Roboto+Slab');

/* Styles specific to the website */
body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
}

.top {
    position: fixed;
    height: 50px;
    width: 100vw;
    background-color: #24292e;
    color: rgba(255, 255, 255, 0.75);
    z-index: 10;
}
/* Other website-specific styles go here*/

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top" role="banner">
    <div class="container">
        <div class="nav-item1 header-item">
            <div class="logo">Logo</div>
            <div class="search">
                <input type="text" class="search-field" name="search" placeholder="Search...">
            </div>
        </div>
        <div class="nav-item2 header-item">
            <ul class="nav">
                <li class="nav-item">New</li>
                <li class="nav-item">Home</li>
                <li class="nav-item">Explore</li>
            </ul>
        </div>
        <div class="nav-item3 header-item">
            <div class="sign">
                <div class="sign-in">Sign In</div>
                <div class="sign-up">Sign Up</div>
            </div>
        </div>

    </div>
</div>

Answer №2

I have made an adjustment to the width of the container .search which contains the search field. By setting a width restriction, the input will now scale relative to .search.

.search {
  width:calc(100% - 40px);
}

$(".search-field").focus(function () {
    $(this).animate({ "width": "100%" }, "slow" );

    // $(".logo").fadeOut();
});
$(".search-field").focusout(function () {
    $(this).animate({ "width": "130px" }, "slow" );
    // $(".logo").fadeIn();
});
@import url('https://fonts.googleapis.com/css?family=Roboto+Slab');
/*! HTML5 Boilerplate v5.3.0 | MIT License | https://html5boilerplate.com/ */

/* 
 * Following extensive research on cross-browser styling,
 * credits go to Nicolas Gallagher, Jonathan Neal, Kroc Camen,
 * and the H5BP development community and team.
 */

/* ==========================================================================
   Base styles: opinionated defaults
   ========================================================================== */

html {
    color: #222;
    font-size: 1em;
    line-height: 1.4;
    z-index: 1;
}

/*
 * Eliminate text-shadow in selection highlight:
 * https://twitter.com/miketaylr/status/12228805301
 *
 * These selection rule sets must be separate.
 * Adjust background color to suit your design.
 */

::-moz-selection {
    background: #b3d4fc;
    text-shadow: none;
}

::selection {
    background: #b3d4fc;
    text-shadow: none;
}

/*
 * Improved default horizontal rule appearance
 */

hr {
    display: block;
    height: 1px;
    border: 0;
    border-top: 1px solid #ccc;
    margin: 1em 0;
    padding: 0;
}

/*
 * Remove gap between audio, canvas, iframes, images, videos and bottom of their containers:
 * https://github.com/h5bp/html5-boilerplate/issues/440
 */

audio,
canvas,
iframe,
img,
svg,
video {
    vertical-align: middle;
}

/*
 * Disable default fieldset styles
 */

fieldset {
    border: 0;
    margin: 0;
    padding: 0;
}

/*
 * Allow only vertical resizing of textareas
 */

textarea {
    resize: vertical;
}

/* ==========================================================================
   Browser Upgrade Prompt
   ========================================================================== */

.browserupgrade {
    margin: 0.2em 0;
    background: #ccc;
    color: #000;
    padding: 0.2em 0;
}

/* ==========================================================================
   Author's custom styles
   ========================================================================== */


/* ==========================================================================
   Helper classes
   ========================================================================== */

.hidden {
    display: none !important;
}


.visuallyhidden {
    border: 0;
    clip: rect(0 0 0 0);
    height: 1px;
    margin: -1px;
    overflow: hidden;
    padding: 0;
    position: absolute;
    width: 1px;
}



.invisible {
    visibility: hidden;
}



.clearfix:before,
.clearfix:after {
    content: " ";
    display: table;
}

.clearfix:after {
    clear: both;
}



@media only screen and (min-width: 35em) {
    
}



@media print,
       (-webkit-min-device-pixel-ratio: 1.25),
       (min-resolution: 1.25dppx),
       (min-resolution: 120dpi) {
    
}




@media print {
   
}




body {
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
    font-size: 14px;
    line-height: 1.5;
}
.top {
    position: fixed;
    height: 50px;
    
    width: 100vw;
    background-color: #24292e;
    color: rgba(255, 255, 255, 0.75);
    z-index: 10;
}
.container {
    padding-top: 2px;
    width: 980px;
    margin-right: auto;
    margin-left: auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}
.nav {
    list-style: none;
    padding-left: 0;
    margin-top: 0;
    margin-bottom: 0
}
.nav-item {
    padding: 12px;
    float: left;
    list-style: none;
}
.logo {
    flex: unset;
}
.header-item {
    display: flex;
    flex-direction: row;
}
.nav-item1 {
    width: 300px;
    justify-content: space-around;
}
.nav-item3 {
    width: 300px;
    justify-con...

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="top" role="banner">
            <div class="container">
                <div class="nav-item1 header-item">
                    <div class="logo">Logo</div>
                    <div class="search">
                        <input type="text" class="search-field" name="search" placeholder="Search...">
                    </div>
                </div>
                <div class="nav-item2 header-item">
                    <ul class="nav">
                        <li class="nav-item">New</li>
                        <li class="nav-item">Home</li>
                        <li class="nav-item">Explore</li>
                    </ul>
                </div>
                <div class="nav-item3 header-item">
                    <div class="sign">
                        <div class="sign-in">Sign In</div>
                        <div class="sign-up">Sign Up</div>
                    </div>
                </div>

            </div>
        </div>

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

Having difficulty replicating the same effect across all five canvas elements

After following the code provided by j08691 here for canvas, everything worked flawlessly. However, I encountered an error in JavaScript when trying to implement it on multiple canvas elements. As a beginner in JavaScript, I would greatly appreciate any as ...

Increasing the size of a card beyond the container using the CSS PRE tag

I am facing an issue with a card on my webpage. It contains a pre tag inside it, which is causing the size of the card to extend beyond its container, resulting in a horizontal scroll bar appearing. How can I make the content within the pre tag scroll hori ...

The jQuery slider does not abruptly halt when the mouse is clicked and released

Trying to create a smooth sliding effect on a jQuery slider, but facing issues with responsiveness. When I decrease the interval time in `setInterval` to 200, the slider doesn't immediately respond to `mouseup` events and the slides stop moving after ...

The custom validator in Material2 Datepicker successfully returns a date object instead of a string

Im currently working on developing a unique custom validator for the datepicker feature within a reactive form group. Within my code file, specifically the .ts file: form: FormGroup; constructor( private fb: FormBuilder, ...

Exploring VueJS: Sorting objects within an array

Currently, I am tackling a challenge in vue-js. In my codebase, there exists a data object known as items. I am iterating through these items and aiming to present a dropdown menu containing the list of products. My goal now is to showcase only those pro ...

The issue with property unicode malfunctioning in bootstrap was encountered

I have tried to find an answer for this question and looked into this source but unfortunately, when I copy the code into my project, it doesn't display Unicode characters. section { padding: 60px 0; } section .section-title { color: #0d2d3e ...

The utilization of ASP.NET C# for server-side controls

I am looking to empty a server-side control textbox that has the readonly attribute set to true. To achieve this, I have utilized the jQuery function $('#mycontrol').val(''); Although the code successfully empties the textbox, the val ...

It appears that Serverworker is causing significant delays in processing ajax requests

I'm encountering some performance issues with my PHP app that utilizes a lot of JavaScript for AJAX requests back to the PHP server. I'm currently implementing a service worker to cache content and enable push notifications, but I'm facing d ...

Uploading several files with Laravel and Vue JS in one go

Recently, I have been working on a project where I need to upload multiple image files using Vue JS in conjunction with Laravel on the server side. This is the snippet from my Vue template: <input type="file" id = "file" ref="f ...

Cannot instantiate Marker Clusterer as a constructor

I am facing an issue with implementing Marker Clusterer in my app. I have successfully installed '@google/markerclusterer' in my project and imported it as shown below. However, a puzzling error keeps popping up: core.js:4002 ERROR TypeError: _go ...

Transferring data from jQuery Ajax to PHP

I'm facing a challenge in retrieving a value back to PHP that I can manipulate and save to the database. It appears that using the GET method with jQuery AJAX is not yielding the desired results. Below is the PHP code snippet where I attempt to captur ...

When using jQuery, you can utilize the mouse over event to display elements with the same class within an each loop

I am struggling with a hover effect on my webpage. I have three visible elements and three hidden elements, and I want each visible element to display only one hidden element when hovered over. However, the issue is that currently, hovering over a visible ...

My JavaScript/Jquery functions are not running as expected

I need some help creating a simple image rotation feature. I have a folder named comics where the images are stored locally with names like comic_(number). However, when I click my buttons, nothing happens. The previous button doesn't even get disable ...

A pair of variables combined within a set of single quotation marks

After exploring numerous examples, I am still struggling to include a variable inside quotes. This situation seems unique and difficult to resolve. Take a look at the code snippet below: Var x='http://www.xyzftp/myservice/service1.svc' Var y=&a ...

Limit the radio button to being clickable

Ugh, I'm really struggling with this. I want to create a quiz where only the radio button is clickable, not the text itself. Can anyone help me figure out how to do this? I have two codes below that I don't quite understand. I'll include th ...

Organizing flex-items in a specific manner

My goal is to organize flex-items in a specific layout: To achieve this, I am referencing the following example: .Container { display: flex; overflow: hidden; height: 100vh; margin-top: -100px; padding-top: 100px; position: relative; widt ...

get selection choice from the server

I have been trying to update my option select menu when the button is clicked without clearing out the menu. Currently, I am using $(#id).click(function(){}); but it seems that this approach is causing the select menu to clear out. Upon further investigati ...

Changing the height using JQuery UI resizable() can also affect the width during resizing

Having an issue with resizing here. Using the JQuery .resizable() on a div with specific css: div#resizable { float: left; border: solid 1px white; box-shadow: 0px 0px 0px 1px #F2F2F2; box-sizing: border-box; padding: 15px; } This div cont ...

Display the importance of utilizing Bootstrap 4's range input feature

Is there a way to display the value of a range input in Bootstrap without using Javascript? I found this tutorial but it doesn't show how to do it: https://getbootstrap.com/docs/4.1/components/forms/#range-inputs <div class="container"> < ...

The utilization of useState can potentially trigger an endless loop

Currently, I am in the process of developing a web application using Next.js and Tailwind CSS. My goal is to pass a set of data between methods by utilizing useState. However, I have encountered an issue where the application loads indefinitely with excess ...