Collapse input horizontally using the display property set to flex

At the top of a mobile page, I have implemented two search boxes:

https://i.sstatic.net/gCfOG.png

When a user clicks inside one of the boxes, the desired behavior is as follows:

  • The selected box expands
  • The other box collapses horizontally
  • A close icon expands on the right.

After the transition, this is what it looks like:

https://i.sstatic.net/odGJB.png

Below is the code snippet for this functionality:

<div class="navigation--mobile__search">
    <div class="header-searchfield" id="kurssuche">
        <input type="text" class="header-searchfield__input" placeholder="Search1">
            <a href="">
                <span class="icon icon--lupe">
                    <svg class="icon__svg">
                        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/svg-symbol.svg#lupe"></use>
                    </svg>
                </span>
            </a>
    </div>
    <div class="header-searchfield" id="volltextsuche">
        <input type="text" class="header-searchfield__input" placeholder="Search2">
            <a href="">
                <span class="icon icon--lupe">
                    <svg class="icon__svg">
                        <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/svg-symbol.svg#lupe"></use>
                    </svg>
                </span>
            </a>
    </div>                      
    <span class="icon icon--close-x header-searchfield__close-button" style="display: none;">
        <svg class="icon__svg">
            <use xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="/assets/svg/svg-symbol.svg#close-x"></use>
        </svg>
    </span>
</div>

Here are the corresponding LESS classes:

.navigation--mobile__search {
        background: @common-quarks-color--cd-anthracite;
        display: flex;
        padding: .625rem .75rem;
        position: relative;
        .header-searchfield {
            display: flex;
            flex: 1;
            &__input {
                flex-grow: 1;
                padding: .5625rem 2rem .5625rem .8125rem;
            }
            &__close-button {
                flex: 0 0 1.8rem;
                color: white;
                display: none;
                margin: .7rem 0 .7rem .5rem;
                svg {
                    fill: @searchfield--border-color;
                    height: .8125rem;
                    width: .8125rem;
                }
            }
        }
    }

And here's the JavaScript code for the implementation:

$(function () {
  $("#kurssuche")
    .focusin(function() {
      $("#volltextsuche").hide(500);
      $(".header-searchfield__close-button").show(500);
      $(".navigation--mobile__search-results").animate({height: "400px"}, 500);
    })
    // Other functions for focusout and clicking
            
});

Issue:

In order to achieve the desired collapsing behavior, I attempted different approaches with flex divs but was unable to make it work properly due to the display: flex property. Is there a workaround to animate flex divs to collapse horizontally?

Fiddle: https://jsfiddle.net/amear6x0/

Answer â„–1

If you want to achieve a particular effect, you can use CSS alone without the need for jQuery. Here's how:

  1. Utilize classes to indicate the visible/hidden states of components individually. You can still employ jQuery to toggle these classes, removing the need for the cumbersome jQuery .aninmation() function.
  2. Toggle between a width of 0 and 100% for input elements and close buttons based on their visibility. The transition will be smoothly animated by the browser using a duration of 500ms, as specified in your jQuery code, along with the ease-in-out timing function. Feel free to define custom bezier curves if needed.
  3. Instead of using focusin and focusout, opt for focus and blur functions—it's just a personal preference.

Here are some additional pointers:

  • Apply box-sizing: 0 to prevent extra padding from affecting the size of input elements
  • Use overflow: hidden to hide content that overflows when parent widths collapse to 0
  • To enhance extensibility, avoid duplicating functions for similar elements. By utilizing .closest() and .siblings(), you can combine hide/show toggles into a single function based on context.

Take a look at this proof-of-concept example on the updated fiddle here:

$(function() {
  $('.header-searchfield input')
    .on('focus', function() {
    
      // Reduce redundancy by filtering siblings of the parent wrapper
      $(this).closest('.header-searchfield').siblings('.header-searchfield').addClass('hide');
    
      // Display the close button
      $('.header-searchfield__close-button').addClass('show')
    })
    .on('blur', function() {
    
      // Reduce redundancy by filtering siblings of the parent wrapper
      $(this).closest('.header-searchfield').siblings('.header-searchfield').removeClass('hide');
    
      // Hide the close button
      $('.header-searchfield__close-button').removeClass('show');
    });

  $('.header-searchfield__close-button').on('click', function() {
    $('.header-searchfield__input').val('');
  });
});
* {
  box-sizing: border-box;
}
/* Add your CSS styles here */
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Your HTML content goes here -->

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 discovered in Webpack syntax

I'm a newcomer to webpack and feeling lost on how to properly configure the settings. Here is my project structure: / -- /public -- /js -- app.js -- /css -- app.scss -- /node_modules -- /autoprefixer -- /babel-loader ...

Alternative to using the disabled attribute in JavaScript to make a checkbox read-only option

Does anyone know how to make a checkbox readonly so that its value can be submitted, while also disabling it? Using the disable attribute prevents the value from being submitted, and setting it as readonly doesn't seem to work for checkboxes. Your as ...

The JQuery pagination feature fails to function properly once an AJAX load is initiated

I am using jspages.js to implement pagination with jQuery. Everything works fine when the page is initially loaded. However, I encounter an error when the content for pagination is loaded after an ajax call. The plugin does not seem to work as expected. ...

Embedding PHP code within inline styles

Is it possible to incorporate a variable inside my progress bar? I want the progress to change based on the status of each project ($projek), but inserting the variable directly into the style attribute doesn't seem to be working. Here's the code ...

Disable Vue click event based on a condition

One issue I encountered was that even though I successfully disabled the document body scroll when my mobile nav was open, the overflow hidden feature was not being removed when a user clicked a link to another route or page. To address this, I implement ...

The looping mechanism results in only displaying the final number

Through my coding journey, I crafted a for loop to showcase multiple entries stored within an array. Unexpectedly, the for loop only displays the final entry in the array as opposed to all elements from the beginning to the end. for (var i = 0; i < r ...

adjusting array based on screen size fluctuations

Imagine having two arrays of images named landscape_images[] and portrait_images[]. One is for the landscape view and the other for the portrait view. When the screen width is in landscape mode, the wide resolution images will be displayed on the body. C ...

Guide on redirecting to an HTML page on a local computer

Recently, I created an HTML page named A.html on my local computer which consists of 2 text fields and a button. I made a host entry to access the file via localhost. Upon clicking the button on A.html, it redirects me to a corporate login page where I ne ...

When working with angular.js and angular-sanitize.js, the src attribute is removed from JSON HTML data

I'm new to Angular and I'm really enjoying learning how to work with it. Currently, I have a simple JSON file that contains text structured like this: "gettingstarted":{ "title":"Getting Started", "content":"<img ng-src='i ...

What is the best way to assign attributes to multiple HTML elements using an array?

Seeking assistance to hide various sections in my HTML file upon button click, with the exception of one specific section. Encountered an error message: Uncaught TypeError: arr[i].setAttribute is not a function Here's a snippet of my code: const hide ...

Add the directive prior to rendering the HTML

I attempted to comprehend the problem below: My html string is rendered using ng-bind-html I successfully replaced a specific placeholder in the html string with a directive (or multiple). For example, I changed [placeholder]test[/placeholder] to <my- ...

Troubleshooting server-side sorting issues with AJAX implementation, encountering problems with headers functionality

I'm encountering a problem: Some headers are not functioning properly to sort the table. For example, Brand and Model work as expected, but VehicleType only works once, and CarID and ReleaseDate never seem to work. Here is my index.php file: index. ...

What is the best way to avoid repeated guesses in a number guessing game?

I've implemented an array named 'tries' to keep track of the numbers guessed by the user. Once the user correctly guesses the number, the total number of tries and the guessed numbers are displayed. How can I prevent the user from guessing a ...

Expanding navigation bar onto a second line with the help of Bootstrap

Currently delving into Bootstrap for the first time, I am working on designing a webpage from scratch. The navbar component has been giving me some trouble. My vision for the navbar is as follows: On desktops and tablets, it should function like a traditi ...

When an SVG image is embedded, its color may not change even after being converted to an inline SVG

I've inserted an SVG using an img tag. When hovering over it, I want the fill color of the SVG to change. I attempted to convert the SVG to inline SVG following this method, but it doesn't seem to be working as expected. No console errors are b ...

The sluggish loading speed of the page is being caused by both jQuery and an external file containing Amazon

I am facing an issue with my website where it is loading over 1000 images per page from Amazon servers. To enhance the functionality, I have integrated jQuery plugins that are stored locally on the webserver, without using any remote JS or CSS. However, ...

Breaking on newline, excluding newline-space in JavaScript

I want to divide my string into an array based on new lines, excluding those that start with a space. ORGANIZER;<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3758455056595e4d524577524f565a475b521954585a">[email prot ...

Combining user input with React's useState function

I have a form with three Quantity inputs. (Although more can be added dynamically, let's keep it simple for now and stick to three.) | - | - | Quantity | |---|---|----------| | - | - | 3 | | - | - | 4 | | - | - | 5 | Now, I want ...

Displaying HTML content in UITableViewCell on iOS

Can anyone assist me with rendering HTML content containing images and text in different cells of a UITableView? My data source consists of HTML content that needs to be displayed on UITableViewCells. I have attempted using Attributed strings on UILabel a ...

What is the best way to retrieve the date and time using the Open Weather API for a specific city

Currently, I am in the process of developing a weather application using React and integrating the Open Weather API. Additionally, I have incorporated an external library for weather icons. The functionality allows users to input a city name and receive t ...