How can I create a unique CSS or JS transition for a button that dynamically changes size based on text

My Angular app features a button labeled with "+".

When the user hovers over it, I use

element.append(' Add a New Number');
to add the text "Add a New Number" next to the + sign in the label.

Upon clicking the button, a new number is added and the label reverts back to "+".

I want to animate either the change in button size or the text label change. However, applying a CSS transition to width has shown no effect so far.

Any ideas?

UPDATE: Just to clarify, this is a bootstrap input group button. I'm trying to avoid setting specific widths or using CSS transforms to prevent any issues with the button display at different screen sizes.

Here are the two states:

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

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

I was hoping that by injecting more words, the existing button would naturally stretch.

Answer №1

It seems like you may not have a predefined width, but you can still achieve the desired effect by utilizing transform-origin and scale.

Check out the FIDDLE HERE

Here is an example of the HTML:

<button id="btn">Click</button>

And here is the CSS code:

#btn {
    outline: none;
    border:none;
    background: orange;
    padding: 1em 1.5em;
    -webkit-transition: .3s;
    -o-transition: .3s;
    transition: .3s;
}
#btn:hover {
    -webkit-transform: scaleX(1.2);
    -ms-transform: scaleX(1.2);
    -o-transform: scaleX(1.2);
    transform: scaleX(1.2);
    -webkit-transform-origin:0 0;
    -moz-transform-origin:0 0;
    -ms-transform-origin:0 0;
    -o-transform-origin:0 0;
    transform-origin:0 0;
}

Instead of using properties like width, it's recommended to utilize CSS transforms for smoother animations. If there are any slight jerks in the animation, further refining may be needed.

Answer №2

If you have jQuery tagged, this is how I would approach it.

Utilizing all transitions - fading and animating

function updateButtonText(button, text){
    // Using jQuery
    $button = $(button);
    
    // Store original CSS properties
    oldTextAlign = $button.css('text-align');
    overflowValue = $button.css('overflow');
    whiteSpaceValue = $button.css('white-space');
    $button.css('text-align', 'left').css('overflow', 'hidden').css('white-space', 'nowrap');
    
    // Determine the new width first
    $tmpBtn = $button.clone().append(text).css('opacity', '0.0').appendTo('body');
    newWidth = $tmpBtn.outerWidth();
    $tmpBtn.remove();
    
    // Expand the button to fit the new width
    $button.animate({width: newWidth+"px"});
    
    // Fade the new text into the button
    $button.append('<span style="display:none">'+text+'</span>');
    $btnText = $button.find('span').fadeIn('slow');
    
    return {
        'text-align': oldTextAlign,
        'overflow': overflowValue,
        'white-space': whiteSpaceValue
    };
}

Fiddle

Answer №3

Utilizing bootstrap CSS and Angular together may seem complex, but here is a programmatic approach to tackle it. A directive can be built to smoothly integrate with Angular and handle the model and data differently:


HTML

<div class="thing">+ <span id="message">
    <span id='target'></span>
</span></div>


JavaScript

$('.thing').hover( function() {
  var originalWidth = $(this).outerWidth();
  $messageHolder = $(this).find('#message');
  $target = $(this).find('#target');
  $target.text('Some helpful text');
  var targetWidth = $target.outerWidth();
  $messageHolder.animate({
    width: targetWidth
  }, {
    duration: 200,
    complete: function() {
      $messageHolder.animate({
        opacity: 1
      }, 500);
    }
  });
});

$('.thing').on('click', function() {
  $target = $(this).find('#target');
  $target.empty();
  $messageHolder = $(this).find('#message');
  $messageHolder.animate({
    opacity: 0
  }, {
    duration: 200,
    complete: function() {
      $messageHolder.animate({
        width: 0
      }, 200);
    }
  });

});

Angular's ng-animate library likely observes the dom and offers a smooth way of animating changes in the model/controller. This could be a glimpse of what happens behind the scenes.

Best of luck!

jsFiddle

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

Verify FileReader.onload function using Jasmine and AngularJS

I have a unique directive specifically designed for uploading and importing binary files. This directive listens for a change event on an <input type="file"../> element. Currently, I am facing an issue with the code coverage of my test. Although the ...

The React component is experiencing a delay in its updates

I've been experiencing delayed updates when using React.useEffect(). Can anyone shed some light on why this might be happening? function Process(props) { const [results, setResults] = React.useState({ number: "", f: {} }); let ...

Ways to access a DOM element in Next.js when the class name is dynamically generated

I am currently developing a Next.js app (version 12.1.0) and facing an issue in my Nav component. I am attempting to select a DOM element using const nav = document.querySelector('.nav'); However, this is triggering an error message: TypeError: ...

What could be causing this function to work in Google Chrome, but not in Firefox?

For some reason, in Firefox, this section of the code never returns true. However, it works perfectly fine in Google Chrome. if(restrictCharacters(this, event, digitsOnly)==true) The expected behavior is that if a user inputs a number from 1 to 5 in the ...

Using Angular JS, send out a notification and pause execution until it is finished

I recently encountered an interesting situation involving an Angular event: $rootScope.$broadcast("postData"); doSomething(); However, I realized that doSomething() needs to wait for the completion of postData before executing. This led me to contemplate ...

rearranging the positioning of links in the HTML navbar

Is there a way to prevent other links in the navbar from moving up slightly when hovering over one link and creating a line (border bottom)? ` .n24{ margin-top: 2px; padding: 14px 14px; } .n25{ margin-top: 2px; padding: 14px 14px; } . ...

Adjustable Greybox Overlay Resizes Window Dimensions

Utilizing greybox on my business website allows users to easily log in and access their accounts. View an example of my site However, when the login or sign up window is activated at the top of the page, the page or window size changes, causing scroll bar ...

What could be causing the overlap between the button and the div element?

My main wrapper div contains a content div and a button. However, I'm facing an issue where the button is overlapping with the content div instead of appearing below it. The content div is styled with the following CSS: #groupMembers { position: ...

Set the value of a hidden field and proceed to submit it in CodeIgniter

I seem to be struggling with a simple task of setting a hidden input value. Here is how my form is structured: <?php echo validation_errors(); ?> <?php echo form_open('purchasing'); ?> <h1>Purchasing Re ...

Steps to exit browser in WebDriver Sampler in JMeter and halt execution

I have been attempting to close the browser in my Selenium Jmeter last sampler thread, but I keep encountering the following error: INFO c.g.j.p.w.s.WebDriverSampler: WebDriver has been quit. 2024-02-01 22:53:24,989 ERROR c.g.j.p.w.s.WebDriverSampler: Sess ...

Enhance the performance of React code by refactoring it

Having recently started coding in React for a new organization, I find that the code in my component has grown lengthy and the submithandler method is causing multiple array iterations. Is there a way to refactor the code for better performance? The data t ...

Display the list in a grid format with 4 columns and x number of rows by utilizing Angular and Bootstrap

I need to display a list of values [1,2,3,4,5,6,7,8,9,10] as a bootstrap grid (class="col-x") using AngularJS. My goal is to create a grid with 4 columns and 3 rows from this list. Can you suggest the most efficient method to achieve this? ...

When attempting to send data from Ajax to PHP as JSON, an error occurs and the data transmission fails

When attempting to send data as JSON, an error response is received stating: SyntaxError: Unexpected token < in JSON at position 0. If the data is sent as text, it successfully reaches PHP, but PHP does not respond accordingly. AJAX/JavaScript using J ...

What is the method for retrieving a variable from a Q Node promise?

I am currently developing a learning game utilizing Angular, Express, MongoDB, and Node. As part of my learning process, I have been exploring the use of promises to manage asynchronous operations effectively. One particular challenge I am facing involves ...

Utilizing Material UI's React framework for maintaining uniform grid column heights

Take a look at the image provided for context. I am facing an issue with two div elements, where one should occupy 20% of the total browser height and the other should take up 80%. Currently, I am utilizing Material UI Grid for positioning, which looks lik ...

Preventing Click Events from Firing During Drag in JavaScript

I have implemented a code for dragging containers left or right, which is functioning properly. Users can also click on the "thumb". However, I am facing an issue where a click event occurs even after dragging. I want to ensure that only either drag or cli ...

Unable to retrieve AJAX response

I've been working on a page where I'm using AJAX to fetch data based on the selection of radio buttons. The three options available are 'Unapproved', 'Approved' and 'All'. My goal is to display the corresponding user ...

What is the specific table element compatible with Polymer3?

I stumbled upon iron-data-table (), but it relies on bower which is used in Polymer2. However, I am working with npm in Polymer3. Is there a suitable table element or an alternative solution compatible with Polymer3? ...

Displaying recorded information from PHP/MySQL dropdown menu

My never-ending problem requires a simple solution. Despite searching online and in books, I can't seem to crack it. My goal is to display results from a drop-down menu that is currently connected to a database/table and showing the l_state as require ...

Tips for increasing the font size using html and css?

I am encountering an issue with my HTML code: <div class="a"><font size="40"><font color="black">A</font></font></div> No matter what I try, I cannot seem to increase the font-size. Even adjusting the value in the co ...