Animate text size using jQuery, then return to the previous state

I play with animated text on click.

I have buttons with various classes that define size:

<div class="button-1">Click Me!</div> <div class="button-2">Click Me!</div> <div class="button-3">Click Me!</div> .button-1 {font-size: 10px;} .button-2 {font-size: 20px;} .button-3 {font-size: 30px;} 

Then, when one is clicked, it animates to a larger size.

  $('.button-1,.button-2,.button-3').click(function(){ $(this).animate({fontSize: "40px" }, 1000 ); 

My question is: I only want to have one big one at a time, and all the brothers and sisters come back to their original size. I see that the animate function works by adding an inline style to the text, is there a way I can just remove all the inline styles added to the pressed siblings buttons?

+4
source share
2 answers

It works and looks much better ...

 $(document).ready(function() { $('.button-1,.button-2,.button-3').each(function() { $(this).data('original-size', $(this).css('fontSize')); $(this).click(function() { $(this).animate({ fontSize: "40px" }, 1000); $(this).siblings().each(function() { var originalSize = $(this).data('original-size'); if ($(this).css('fontSize') != originalSize) { $(this).animate({ fontSize: originalSize }, 500); } }); }); }); }); 

jsFiddle .

If you were lazy, you could also do ...

 $(this).siblings().removeAttr('style') 

jsFiddle .

This solution, however, is rough and can adapt to painful debugging if you or jQuery add additional styles using the style attribute. I recommend using the old code.

+7
source

Here's a shorter way to do it.

 $(document).ready(function() { $('.button-1,.button-2,.button-3').click(function() { $('div').removeClass('button-4', 50); $(this).addClass('button-4', 100); }); }); 

Check out the working example http://jsfiddle.net/nLnvY/2/

+4
source

Source: https://habr.com/ru/post/1344043/


All Articles