Changes in content result in modifications to the size of transition elements

Have you ever encountered a button with changing text upon being pressed? The transition in text leads to a shift in the button's width. Wouldn't it be amazing if one could smoothly transition the change in width of an element using a code snippet like the one below?

#el {
    transition: width 150ms ease-out;
}

However, this method only applies when the width property is explicitly modified.

Is there an inventive approach to achieving this effect? Check out this fiddle to experiment with it.

Answer №1

Check out this interactive demo which demonstrates the same concept using JavaScript library.

document.querySelector('button').addEventListener('click', function() {
    var width = this.style.width;
    var height = this.style.height;
    this.innerHTML = 'Hello, World!';
    var newWidth = this.style.width;
    this.style.width = width;
    this.style.height = height;
    this.animate([{width:width}, {width:newWidth}], {duration:1000, fill: 'forwards'});
});

Answer №2

After finding a solution in Maurice's response to prevent the button's text from overflowing onto a second line, it was discovered that setting the button's height to its original value was necessary. A better approach would be to

button {
    white-space: nowrap;
}

to ensure that the button's text remains on a single line as it transitions. By doing this, the code can be simplified as there is no longer a need to adjust the button's height:

$('button').click(function() {
    var width = $(this).css('width');
    $(this).text('Hello, World!');
    var newWidth = $(this).css('width');
    $(this).css({'width': width});
    $(this).animate({'width': newWidth}, 400);
});

http://jsfiddle.net/2rr54vp2/1/

Answer №3

It seems like a challenging task since the browser struggles to accurately determine the target width. Let's assume it captures the width before the transition, only to find out that the button has already expanded by then! It's quite possible that the transition is indeed occurring, but it's not visible to us. To address this issue, one must define an initial width and ascertain the target width using JavaScript.

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

Modifying the id attribute dynamically using jQuery during runtime

In my project, I have a submit button with the id of "submit" that is used to save new records. // Function to add a new customer record $("#submit").click(function() { var data = $.param($("#form").serializeArray()); ...

Unable to access this context in Firefox debugger after promise is returned

I'm curious as to why the 'this' object is not showing up in the debugger in Firefox, but it does appear in Chrome's debugger. When I try to access 'this.myProperty', it shows as undefined. This is the code from my TypeScript ...

How can I incorporate the "onClick()" function within an ajax call, while still utilizing the data returned in the success message?

After successfully making an Ajax call, I would like to implement an on-click function while still utilizing the original data retrieved. $.ajax({ URL: ......, type: 'GET', success: function (res) { var Ob ...

Using an ajax call to dynamically generate an array for jquery autocomplete feature

Struggling to implement a jQuery UI autocomplete feature using data from a database via an AJAX call. Having difficulty figuring out how to pass the table of values to the autocomplete function. $( document ).ready(function() { $.ajax({ url ...

Struggling with a persistent Jquery AJAX problem despite numerous attempts to resolve it

<table class="table table-striped"> <thead> <tr> <th>Choose</th> <th>>Location</th> <th>Topic</th> & ...

Bootstrap component malfunctioning and not performing as expected

Currently, I am learning how to use Bootstrap and attempting to replicate the example themes found on their official website. The specific theme I am focusing on is available at this link: https://getbootstrap.com/docs/4.3/examples/pricing/ Unfortunately, ...

Registering users in Laravel using asynchronous JavaScript and XML (AJ

I am having trouble implementing a user registration process using ajax in the Laravel framework. Routes Route::get('/register', 'Auth\AuthController@getRegister')>name('register'); Route::post('/register', ...

I'm struggling to understand the reasoning behind the 'undefined' error occurring in the Google Maps distance service

Currently facing a puzzling issue with an 'undefined' exception. Developing a tool to track distance traveled between two locations, leveraging Google Maps distance matrix. Upon selecting a vehicle, entering an origin and destination, and clickin ...

An approach to looping through arrays within an object in JavaScript

I have a JSON structure that consists of an array containing arrays, each holding dictionary elements. This data is retrieved from a function-based view. I am looking to iterate through all the elements and filter out arrays with empty dictionaries. data. ...

Learn how to extract JSON information from a URL and integrate it into either a table or dropdown in Vue.js

Looking to retrieve a JSON data array from a URL and utilize it to populate either a table or dropdown with Vue.js and Axios. Here is the link where I intend to fetch the data. Any advice on how to accomplish this? https://jsonplaceholder.typicode.com/us ...

The intersection of JavaScript, node.js, and cybersecurity

I recently set up a user registration form on my website where the data (username, password, email) is currently being sent to the server in plain text using socket.io. I am aware that this method is not secure at all. Can anyone recommend a better solut ...

Utilize npm to construct a Vue application and execute it on a Raspberry Pi device

My roommate and I are currently working on a Vue app project together, and we're aiming to deploy it on our Raspberry Pi. We're wondering if there's a way to npm build the final app on our PC and simply start the server on the Pi without hav ...

Display Image Automatically Upon Page Opening

Currently, I have an HTML file that includes the following code: <img src="(Image from file)" alt="Raised Image" class="img-raised rounded img-fluid"> I am attempting to retrieve the image from a file when the webpage loads using the server.js file ...

Tips for preventing the use of website URLs as variables in jQuery ajax() calls:

Having some trouble. For example: $(document).ready(function () { $("#btnSend").click(function () { var noti_p = { url: "Pusher_Controller.ashx", data: "&appname=" + $("#selt1").val() + "&title=" + $("#title"). ...

How do I resize an image to fit perfectly within the viewport dimensions?

As a beginner in Bootstrap and CSS, I am working on creating a home screen layout for my website. My goal is to ensure that the image with an intrinsic size of 1920x1080 fits perfectly within the viewport. Currently, part of the image extends off the scree ...

Application with menu design, similar to the layout of google.com on mobile devices

Have you seen the Android smartphone with Chrome from GOOGLE.COM? Did you notice the pop-up MENU that looks similar to an application? This menu has a "SPRING" effect, and I'm curious how Google achieved this result. I tried using the property "-web ...

Any modifications made to a copied object will result in changes to the original object

The original object is being affected when changes are made to the cloned object. const original = { "appList": [{ "appId": "app-1", "serviceList": [{ "service": "servic ...

Upon logging in to the first HTML page, the user will be automatically redirected to the second HTML page while passing values

Is there a way to automatically redirect users to Login2.html when selecting "TEAM" in the dropdown on Login1.html, using the values entered in Login1.html? Similarly, can we redirect them to the Premium page when they select "Premium"? I need a solution u ...

What is the reason for needing a page reload in Javascript or JQuery?

I'm curious why Javascript or jQuery require a page reload before applying certain effects. CSS updates in real-time, as demonstrated by the following example: This changes dynamically without needing to refresh the page @media all and (max-width:7 ...

Creating a Form with Table-like Alignment Using Div Tags

Take a look at my code: <div> <label>First Name</label><input type="text" id='first_name'/><br /> <label>Last Name</label><input type="text" id='last_name'/><br /> <l ...