Adjust the button's width as the text changes to create a dynamic animation

I'm trying to create an animation effect where the width of a button changes whenever the text inside it is updated. I've attempted using useRef on the button itself to grab its clientWidth and then applying that value to a CSS variable in order to adjust the width dynamically.

However, I'm encountering an issue where although the width is being set correctly, the animation isn't working as expected. Strangely, if I manually adjust the width in Chrome Developer Tools, the animation works fine. But when I revert back to using the CSS variable and update the inner text, the animation fails to trigger.

.button {
width: var(--buttonwidth);
transition: width 2s ease-in-out;
}
// Update css variable when button text changes
  useEffect(() => {
    const buttonInnerWidth = buttonRef.current.clientWidth;
    document.documentElement.style.setProperty(
      '--buttonWidth',
      `${buttonInnerWidth}px`
    );
    console.log(buttonInnerWidth);
  }, [children]);

Does anyone have a more effective solution to achieve this animation effect?

Answer №1

Here is a demonstration showcasing how the button width changes when clicked. You have the freedom to modify this event listener to suit your preferences.

Check out the sample code below:

$(document).ready(function(){
$("button").css({"width":$("button").text().length*10});
  $("button").click(function(){
    var str = " activated ";
    var strWidth = str.length*10;
    $(this).css({"width":strWidth}).text(str);
  });
});
button{
height: 40px;
transition: 0.4s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>press</button>

Answer №2

Here is an alternative method. It's very similar to what Hooman Namazi proposed, but with a slightly different approach. Take a look:

jQuery(function ($) {
$("button").css({"width":$("button").text().length*10});
    var text = ['first text', 'this is second text', 'and this one is third', 'Hi, I am forth'];
    //used to determine which is the next text to be displayed
    var counter = 0;
    var $button = $('button');
    //repeat the passed function at the specified interval - it is in milliseconds
    setInterval(function () {
        //display the text and increment the counter to point to next text item
        $changeText = $button.text(text[counter++]);
        $button.css({"width":$("button").text().length*10});
        //if it is the last text item in the array point back to the first item
        if (counter >= text.length) {
            counter = 0;
        }
    }, 2000);
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}
button {
  background: #0084ff;
  border: none;
  border-radius: 5px;
  padding: 8px 14px;
  font-size: 15px;
  color: #fff;
  transition: 0.5s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>first text</button>

Answer №3

Avoiding the use of JS was important for me in this situation due to performance concerns. Constantly checking the width of text inside a button can be inefficient. Instead, I opted to set the width to auto and adjust the max-width when the text changes within the button.

While this solution is not ideal for lengthy text, it functions well for my particular needs! :)

Check out the CSS code below:

.button {
   width: auto;
   white-space: nowrap;
   max-width: 15rem;
   transition: max-width 0.3s cubic-bezier(0.445, 0.05, 0.55, 0.95);

   &.loading {
     max-width: 30rem;
    }
}

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 detected in d3.js Stacked chart transformation

I have developed an application for creating stacked chart animations and updates. However, I am encountering some NaN values being passed into the y and height variables. I am unsure about what is causing this issue. When toggling the data, the charts eve ...

Execute a function when the selected option changes

Now I have implemented a code that dynamically changes the foreign key based on user input and retrieves data accordingly. Here is how it all comes together: Starting with the HTML page: <div class="large-6 columns"> {% csrf_token %} <in ...

Validating multiple input fields using Javascript

Initially, I must ensure that the ID and password textboxes are not empty (which is functioning correctly). Following that step, I need to verify on the same form that the ID entered in the textbox is a numeric value within the range of 3000 to 3999 (tha ...

Using HTML5, the <section> element can inherit styling from the

This is my first time building a website using HTML5 and I've come across a small problem. Here is the code snippet: <header></header> <section> <header></header> <article></article> <footer></foot ...

Getting the Input Label properly aligned in Material UI

Here is my code for input with an input label: <FormControl> <InputLabel htmlFor="my-input"> Photo </InputLabel> <input type="file" /> </FormControl> The current output is as follows: The ...

Can anyone help me create a multilingual web application using ReactJS, Flux, NodeJS, and Postgres?

Ideally, I envision it functioning in the following way: When a client's browser sends a request to the server, The server will detect the language based on the request headers and send the corresponding language file along with the JavaScript bundl ...

Sending data from an AngularJS frontend to a Laravel backend using an HTTP

I've been researching, but I can't seem to make sense of anything. I'm new to Laravel and I want to use it as a backend for my AngularJS project. Since I have experience with Angular, here is the controller function where I make an HTTP call ...

Explore a React application that employs Firebase Authentication within a JavaScript environment

When testing my Login component, I encountered the following error: ● Test suite failed to run FIREBASE FATAL ERROR: Can't determine Firebase Database URL. Be sure to include a Project ID when calling firebase.initializeApp(). This is what I ...

What could be causing the Bootstrap navbar to not toggle when the button is clicked?

Attempting to create a website featuring a collapsible navbar, but encountering some issues. The button is properly identified with the correct ID assigned. Jquery and bootstrap have been included in the necessary order at the bottom of the body. However, ...

development session not persisting on local server (localhost:4200)

Currently, I am utilizing angular for the frontend and node.js along with express for the backend of my application. The interesting observation is that when I run the app on localhost:3000 (the designated port for the express app), everything operates cor ...

Combine activities from a dynamic array of Observables

I'm currently utilizing the rxjs library. In my application, I have a Browser object overseeing multiple instances of Page objects. Each page emits a stream of events through an Observable<Event>. Pages can be opened and closed dynamically, le ...

Aligning text and lists using Bootstrap on both desktop and mobile devices

I want to format a text with a list similar to the images provided https://i.stack.imgur.com/6giDH.png for desktop and tablet view, but for mobile display I would like it to look like this https://i.stack.imgur.com/7zSXi.png This is my current approach ...

React Hook is failing to trigger an update

Learning React and JavaScript has been quite a challenge for me, especially when it comes to understanding React Hooks and the issue of them not updating sometimes. I have tried searching online but either end up with solutions for class-based components o ...

What is the method to set an element's height equivalent to the height of the entire screen?

I attempted using height: auto;, however, it did not produce the desired outcome. Do you have any suggestions or alternative solutions? ...

Adding the ability to export CSV files from Bootstrap Table to an Angular 15 project

Struggling to incorporate the Bootstrap-table export extension into my Angular project without success so far. Visit this link for more information Any assistance or examples would be greatly appreciated. Thank you in advance! This is what I have tried ...

Preventing the page from auto-refreshing upon button click

Recently, I have encountered an issue with a button on my webpage. Every time the button is clicked, the onclick code executes and then the page refreshes. This was not a problem before, but now it seems to be automatically refreshing the page. The curren ...

Can you identify the type of component being passed in a Higher Order Component?

I am currently in the process of converting a protectedRoute HOC from Javascript to TypeScript while using AWS-Amplify. This higher-order component will serve as a way to secure routes that require authentication. If the user is not logged in, they will b ...

What is the best way to position my content next to my sticky sidebar for optimal visibility?

Just starting out with coding and tackling my initial project using reactJs and bootstrap 5. My aim is to create a sticky side navbar that remains fixed on the side while my content displays next to it, even when navigating through different routes. Unfort ...

What is the best way to trigger an ajax request when a user selects a tab?

How can I trigger an ajax call when a tab is clicked by the user? What is the best way to handle the HTML response and display it within the tab? How do I bind JavaScript events to the dynamically loaded HTML content? I am familiar with using jQueryUI tab ...

Both FireFox and Chrome are currently experiencing issues with video chat functionality through WEBRTC

Hello, I'm relatively new to this and have been dedicating about four consecutive days to figuring it out. Despite my efforts, I still can't seem to make it work. Please forgive any oversights as I am quite exhausted at the moment but I'll d ...