Moving the input box down to the lower portion of the screen

My goal is to create an interactive input box that glides smoothly to the bottom of the screen when clicked by the user. However, the current implementation causes the input box to move too far down, requiring the user to scroll down in order to see it.

Here is the code for the page:

'use client';
import { useState, useRef, useEffect } from 'react';
import Header from '@/components/Header';
import SendChatButton from '@/components/buttons/SendChatButton';

export default function Home() {
  const [isInputFocused, setInputFocused] = useState(false);
  const formRef = useRef(null);
  const [formHeight, setFormHeight] = useState(0);

  useEffect(() => {
    if (formRef.current) {
      setFormHeight(formRef.current.offsetHeight);
    }
  }, []);

  const formStyle = isInputFocused
    ? { transform: `translateY(calc(100vh - ${formHeight}px))` }
    : {};

  return (
    <main>
      <section className='p-4 pt-32'>
        <div>
          <h1 className='text-6xl font-bold'>
            Your very own<br /> personal designer
          </h1>
          <h2 className='text-xl mt-6'>Makes finding outfits so much easier</h2>
        </div>
        <form 
          ref={formRef}
          style={formStyle}
          className="mt-6 flex shadow-md transition-transform duration-1000 ease-in-out"
        >
          <input
            type="text"
            placeholder='Message your personal designer...'
            className="p-2 border border-gray-300 rounded-md block w-full text-sm outline-none"
            onFocus={() => setInputFocused(true)}
            onBlur={() => setInputFocused(false)}
          />
          <SendChatButton />
        </form>
      </section>
    </main>
  );
}


Answer №1

One issue arises when trying to calculate the new form height using `100vh` as it doesn't account for other elements on the page. If your page only consists of the form, this approach would work fine. However, since there are other elements present, the calculation `100vh - ${formHeight}px` is done from the current position of the form instead of the top of the entire page. I hope this explanation clarifies things.

A clever workaround involves setting the initial `section` height to occupy the full `100vh`. Then, adjust the form's height to fill the remaining space within the `section`. When the form is focused, change its height to a specific value (using `auto` won't provide the desired animation effect).

Here's a solution I've devised:

'use client';
import { useState, useRef, useEffect } from 'react';
import Header from '@/components/Header';
import SendChatButton from '@/components/buttons/SendChatButton';

export default function Home() {
  const [isInputFocused, setInputFocused] = useState(false);
  const formRef = useRef(null);
  const [formHeight, setFormHeight] = useState(0);

  useEffect(() => {
    if (formRef.current) {
      setFormHeight(formRef.current.offsetHeight);
    }
  }, []);

  //   added this to make the form grow when focused
  const formStyle = isInputFocused ? { height: '3rem' } : {};

  return (
    <main>
      {/* added flex and justify-between to make the form stick to the bottom */}
      <section className="p-4 pt-32 bg-red-300 h-screen flex flex-col justify-between">
        <div>
          <h1 className="text-6xl font-bold">
            Your very own
            <br /> personal designer
          </h1>
          <h2 className="text-xl mt-6">Makes finding outfits so much easier</h2>
        </div>
        <form
          ref={formRef}
          style={formStyle}
          // and added transition to make it smooth, with h-full, which will be overridden by the formStyle
          className="mt-6 flex shadow-md duration-1000 ease-in-out bg-green-300 transition-all h-full"
        >
          <input
            type="text"
            placeholder="Message your personal designer..."
            className="p-2 border border-gray-300 rounded-md block w-full text-sm outline-none h-min"
            onFocus={() => setInputFocused(true)}
            onBlur={() => setInputFocused(false)}
          />
          <SendChatButton />
        </form>
      </section>
    </main>
  );
}

I trust this solution proves helpful.

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

Autocomplete like Google with arrow key functionality

I have developed a basic search engine that retrieves data from a MySQL database using the PHP "LIKE" function (code provided below). Everything is functioning correctly, but I would like to enhance it so that users can navigate search results with arrow k ...

Issues arise when attempting to alter the background image using jQuery without browserSync being activated

I am facing an issue with my slider that uses background-images and BrowserSync. The slider works fine when BrowserSync is running, but without it, the animations work properly but the .slide background image does not appear at all. Can someone help me ide ...

The method Object.keys.map does not return the initial keys as they were in the original object

I'm retrieving an object from my database and it looks like this: {availability: null bio: null category: "" createdAt: "2020-10-13T13:47:29.495Z" email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfem ...

What is the best method for extracting data from a JSON object that is structured differently than a traditional array format?

What is the best way to parse a JSON object with the specified structure? { "cutoffTimes" : { "85c46c49-99b6-47a1-9726-960c8fe6c337" : { "id" : "85c46c49-99b6-47a1-9726-960c8fe6c337", "customer ...

Is it possible to install the lib ldap-client module in node.js?

I'm having trouble installing the lib ldap-client package in Node.js. To try and solve this issue, I consulted the following page: https://github.com/nodejs/node-gyp. In an attempt to fix the problem, I have installed python, node-gyp, and Visual St ...

Having difficulty accessing any of the links on the webpage

I'm currently utilizing the selenium webdriver to automate a specific webpage. However, I am encountering an issue where my selenium code is unable to identify a certain link, resulting in the following error message. Exception in thread "main" org ...

Elevate your tooltips with Bootstrap 5: enabling hoverable tooltips and clickable links

At times, you may want to include clickable links in tooltips. I recently encountered this issue while using Bootstrap 5 and had trouble finding a solution. After some trial and error, I finally figured it out and wanted to share my findings. The standard ...

Submitting forms with Ajax in IE(8)

Sample Google form Related spreadsheet I modified the original code to create two custom forms: First created form Second created form Both forms are functional on most browsers except for IE(8). Any idea why? First form: <!DOCTYPE html> <h ...

In what circumstances should one utilize either the "this" keyword or an event argument?

$("span").on("click",function(event){ event.stopImmediatePropagation(); }) $("span").on("click",function(event){ $(this).stopImmediatePropagation(); }) Can you explain the distinction between these two code snippets and why only one of them is ...

Error message encountered: "myData undefined while executing server in Node.js"

const express = require('express'); const app = express(); app.post('/', (req, res) => { let newData = new contact(req.body); newData.save() .then(() => { res.send("Data has been successfully saved to ...

Dynamic jQuery URL truncater

Is there an on-the-fly URL shortener similar to Tweetdeck available? I have come across several jQuery and JavaScript plugins that can shorten a URL through services like bit.ly when a button is clicked. However, I am looking for one that shortens URLs aut ...

Utilize Server Side Includes in your JavaScript code

When the query string is parsed, a specific section of code SSI is included in the footer page. Here are some examples of query strings: ?headId=520&genderType=2 ?headId=600&genderType=1 function GetQueryStringParams(sParam){ var sPageURL ...

The challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

My email submission function is malfunctioning

my contact form in my website is not working properly. I have tried troubleshooting the issue by checking the contact.php file but it doesn't seem to be the problem. The script that I am using for the form submission is shown below: <!--Contact U ...

Angularjs - Navigating the Depths of OrderBy: Effective Strategies for Handling Complex Sorting Structures

I have a collection of Incidents (displayed as an array below) that I need to sort meticulously by State, Priority, and Start_date. Specifically, I want them ordered in the sequence of Initial > Ongoing > InReview > Resolved for State, then Priori ...

The functionality of removing a class on the body element is ineffective when using pagepiling.js

After creating a website using pagepiling.js, I implemented a script that adds the 'active' class to the section currently in view. My goal was to add a specific class to the body when my section1 is considered active. Here's the initial app ...

sophisticated method for sorting through data within an array of arrays

How can data be filtered from an array of arrays? Below is an example to help explain the process. To filter the data, use startnumber and endnumber in the query. const data = [ { "name": "x", "points": [ [100, 50, 1], //[number, value ...

Typography splits into a second line within the grid on the toolbar

I need help with my Appbar design. I want to align the title (Lorem ipsum text) on the left and the buttons on the right. However, when I tried implementing the code below, I noticed that there seems to be a maximum width causing the text to break into t ...

I encountered an issue where the data I passed to a component ended up being undefined

So here's the scenario: I'm working on a Next.js project where I have a context for modals. In this context, I store modal details in an array called modalBase. Additionally, I fetch data from another context (toolsContext) to pass it to componen ...

Trouble with Bootstrap Modal not closing properly in Chrome and Safari

ISSUE: I'm facing a problem where clicking on the X (font awesome icon) doesn't close the modal popup as expected. LIMITED FUNCTIONALITY ON CERTAIN BROWSERS: Currently, the X button for closing the modal works only in IE and Firefox. However, i ...