Having difficulty in animating the upward movement of textbox2

I've got a form that contains 2 buttons and 2 textareas. When the form loads, I want to display only section1 (button, textarea) and the section2 button. Upon clicking the section2 button, my aim is to hide the section1 textarea, reveal the section2 textarea, and smoothly move it upwards to the top of the screen in place of where the section1 textarea was located. When the section1 button is clicked, I want to hide the section2 textarea and show a transition where the section1 textarea grows downwards.

Although I have written some code that can show/hide the two sections, I am struggling to implement the animation aspect.

function showSection1HideOthers(event) {
  var target = event.target;
  console.log("will show question", target);
  var elToShow = $("#section1");
  var elToHide = $("#section2");
  elToShow.addClass("uncollapsed");
  elToShow.removeClass("collapsed");
  elToHide.addClass("collapsed");
  elToHide.removeClass("uncollapsed");
}

function showSection2HideOthers(event) {
  var target = event.target;
  console.log("will show question", target);
  var elToShow = $("#section2");
  var elToHide = $("#section1");
  elToShow.addClass("uncollapsed");
  elToShow.removeClass("collapsed");
  elToHide.addClass("collapsed");
  elToHide.removeClass("uncollapsed");
}
.collapsed {
  display: none;
  animation-name: contract;
  animation-duration: 4s;
}

.uncollapsed {
  display: block;
  animation-name: expand;
  animation-duration: 4s;
}

@keyframes expand {
  0% {
    display: none;
    height: 0%;
    opacity: 1;
  }

  100% {
    display: block;
    height: 100%;
    opacity: 0;
  }
}


@keyframes contract {
  0% {
    display: block;
    height: 100%;
    opacity: 0;
  }

  100% {
    display: none;
    height: 0%;
    opacity: 1;
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="new-form" onSubmit="addPracticeQuestion()" novalidate>
  <div>
    <!-- label and small in same line. select in a new line, thus enclosed select in a div-->
    <button type="button" class="unselected-button" id="section1-collapsable-button" onclick="showSection1HideOthers(event)">Section1</button>
    <div id="section1">
      <div class="section1-div" id="description-div">
        <textarea id="section1-description" type="text" rows="4">Section 1</textarea>
      </div>
    </div>
    <!-- transition to this only after the question has been filled correctly-->
    <button type="button" class="unselected-button" id="section2-collapsable-button" onclick="showSection2HideOthers(event)">Section2</button>
    <div class="collapsed" id="section2">
      <div id="section2-div">
        <textarea id="section2-description" type="text" rows="4"> Section 2</textarea>
      </div>
    </div>
  </div>
</form>

Answer №1

If you are utilizing jQuery, consider using the slideDown() and slideUp() functions for smooth animations.

To learn more, visit -> slideUp. You can customize these methods with options like duration and easing.

I've tweaked your HTML/jQuery code slightly.

Assign a common class to buttons (unselected-button) and use jQuery to select them and attach a click event listener.

Add a shared class to the sections, such as .section.

Then, target the section that follows the clicked button (e.g., clicking Submit1 will reveal section1) and display it using slideUp().

Next, hide all other sections except the selected one using slideDown().

var button = $('.unselected-button'); // selecting both buttons
$(button).on('click', function() {
  var elToShow = $(this).next('.section');
  var elToHide = $('.section').not(elToShow);
  elToShow.slideDown()
  elToHide.slideUp()
})
#section2 {
  display:none
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="new-form" onSubmit="addPracticeQuestion()" novalidate>
  <div>
    <!-- label and small in same line. select in new line enclosed select in div-->
    <button type="button" class="unselected-button" id="section1-collapsable-button">Section1</button>
    <div id="section1" class="section">
      <div class="section1-div" id="description-div">
        <textarea id="section1-description" type="text" rows="4">Section 1</textarea>
      </div>
    </div>
    <!-- transition only after question is filled correctly-->
    <button type="button" class="unselected-button" id="section2-collapsable-button">Section2</button>
    <div class="section" id="section2" >
      <div id="section2-div">
        <textarea id="section2-description" type="text" rows="4"> Section 2</textarea>
      </div>
    </div>
  </div>
</form>

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

Angular UI and Node backend causing CORS issues

Just diving into the world of node and could use a little assistance. Encountering this error message: Access to XMLHttpRequest at 'http://localhost:3000/api/auth/signin' from origin 'http://localhost:4200' has been blocked by CORS pol ...

Deactivate and circumvent Angular routing outside of the specified route URL

I am looking for a way to disable and bypass Angular routing when I have static pages or PHP-rendered views in my hybrid PHP and AngularJS app. Instead of being redirected by Angular's routing, I want to perform a full page reload to the routed link o ...

A JavaScript program will only replace strings if a certain local variable has been defined

This is a breakdown of how the script operates: The script first reads the manifest.json file, which includes a list of file names Next, it reads the content of the functions.php file and stores it in a variable named result The script then iterates throu ...

Is there a way to verify if both the username and email have already been registered?

I've exhausted multiple methods attempting to solve this issue, but every attempt falls short. My most recent strategy involved creating two "findOne" functions, however, even that proved unsuccessful. const checkUser = registerLogin.findOne ...

Why does the Node.js REST API keep throwing errors after I try to create just one record?

I encountered a back end issue recently. I have developed a simple API with just a post endpoint. The intention is to post data using the req.body. Oddly enough, it works perfectly fine the first time but when I attempt it again, I receive an error message ...

What is the correct way to encode an HTML string in JavaScript?

I have identified a XSS Scripting vulnerability in my code and I want to prevent it. To do so, I am utilizing a Jquery Encoder for protection against XSS Scripting attacks. Below is the JavaScript code snippet: function test(response) { $('#test ...

How to adjust the Timezone of a JavaScript Date without affecting the designated time?

var schedule = { start_at = Date ( '2017-10-10' ), // Data is not editable - ORM will provide ... }; // Mon Oct 09 2017 20:00:00 GMT-0400 (Eastern Daylight Time) console.log ( schedule.start_at ); Seeking a way to adjust the time of an ...

JavaScript functioning exclusively for specific list items within an unordered list

After implementing JavaScript on my website, I noticed that it only works when clicking on certain list items (li's) and not on others. Specifically, the functionalities for Specialties, Contact Us, and Referral Schemes are not working correctly. ...

JavaScript decimal validation not functioning as intended

Hey everyone! I've created a script that restricts textboxes to allow only decimal numbers. Take a look at the code snippet below: function onlyDecimal(evt) { if (!(evt.keyCode == 46 || (evt.keyCode >= 48 && evt.keyCode <= 57))) ...

What steps can be taken to resolve the error ERROR TypeError: undefined is not an object when evaluating 'userData.username'?

.I need help fixing this error ERROR TypeError: undefined is not an object (evaluating 'userData.username') Currently, I am working on a small application where users are required to allow permission for their location in order to save their cit ...

The data from the Vue.js instance is not available when accessing the Vuex store

My current task involves utilizing an API call to a django-rest backend in order to populate my data-store. The API call is functioning properly. Upon loading index.html, I am able to inspect both store_.state.products and v.$store.state.products, which s ...

Issue encountered while determining the specificity of a CSS selector involving pseudo-classes

As I delved into a tutorial on MDN, an intriguing code snippet caught my attention: /* weight: 0015 */ div div li:nth-child(2) a:hover { border: 10px solid black; } An unanswered question lingers in my mind: Why does this rule's specificity displa ...

Looking to create a div in HTML with two columns and two rows for display

Query: I am facing issues adjusting these grids using HTML and CSS. I have attempted to place them in a single frame within a separate div, but it's not working as expected. I need help aligning the grids according to the provided image below. Can som ...

AngularJS: Blocking access to specific state for users

I am currently in the process of developing an application using sails.js for the backend and Angular for the frontend. My goal is to restrict access to the admin control page for unauthorized users. I have come across several solutions, but none of them s ...

Obtain the HTML of a Vue component and transmit it using an ajax POST request

I need to send an email with an HTML body using only ajax since I don't have access to the server code. Fortunately, the server has an API for sending emails. Currently, I have a dynamically rendered component called invoiceEmail. sendEmail () { ...

Implementing Jquery Datatables in C# Codebase

I'm struggling to populate my jQuery Datatable with a List. Currently, I am writing the list to a file and accessing it in my view-model. Is this the correct approach? This is the snippet of my code: List<string> list = new List<string> ...

Interacting div elements with jQuery's dynamic content

I am searching for a way to populate a div with content based on my click selection. To begin, I create a dynamic table like the one below: user name total hours worked button(unique id fetched from database) user name total ho ...

Can floated divs be prevented from collapsing without taking up any width?

Let's discuss an issue that is not related to block elements collapsing when their children are floated, and has nothing to do with clearing at all. Imagine having a set of floated divs like: <div class="column">Column 1</div> <div cl ...

Mistakes within the react-router-dom package

I have been trying to connect MongoDB Realm to React by following a tutorial. Unfortunately, the tutorial is outdated and I encountered errors while trying to run the code. Initially, I received a warning stating that the leaf route does not have an elemen ...

The outcome of data binding is the creation of a connected data object

I am attempting to link the rows' data to my view. Here is the backend code I am using: [Route("GetCarCount")] [HttpGet] public async Task<long> Count() { return await _context.Cars.CountAsync(); } ...