1

With a javascript click-event I am adding extra html-text (to be specific: an "X"-icon" within a span) to a button. I am doing this with switching the property on the span-icon-class from display: none to display: block.

The button therefore becomes bigger because of the added icon after the click event instantly.

What CSS/js do I need to add, to make this transition smooth, so that the button grows slowly bigger instead of instantly?

Thanks a lot and sorry for maybe complicated questioning.

3 Answers3

1

Maybe look at https://www.w3schools.com/css/css3_transitions.asp. If you have a fixed initial button width, it should be something like this :

JS :

$('.mybutton').on('click', function(){ $(this).addClass('clicked') };

CSS :

.mybutton{
    width : 90px;
    transition : width 0.5s ease;
}
.mybutton.clicked{
    width : 120px;
}
  • thanks! Problem is, I have various buttons which are being looped through and they have various widths, so I cannot use fixed withs. – mikephilipp Feb 20 '17 at 07:42
  • You can use this if you pass the new width with the javascript instead. $("#id").css("width", newWidth); – Simon Hyll Feb 20 '17 at 21:35
0

Yes, you can add CSS to do such a transition. However, you can't use from display: none -> block for a CSS transition. If I don't remember it incorrectly it's because it transitions over time, and display: none/block is a binary system, meaning it can only be shown or not shown, there is no in between. I believe visibility can be used instead because it supports this in-between state of both existing and not existing so to speak.

See this question: Transitions on the display: property

Also, google "css transition display none block" and you'll get a bunch of helpful links.

Community
  • 1
  • 1
Simon Hyll
  • 3,265
  • 3
  • 24
  • 44
  • thanks a lot. Ive done an endless googlesearch but didnt find the answer I was looking for. I also cannot use visibility, because then the x-icon-element is only hidden, which means there will be a placeholder blank space even on the small buttons. – mikephilipp Feb 20 '17 at 07:41
  • Ive had similar issues before, another solution is to use javascript and make the transition happen after you show it. So first its hidden, then shown with no visibility, then transitions to visible. – Simon Hyll Feb 20 '17 at 21:33
0

Okay, I resolved it with a scale-property. I transition the scale of the x-icon, which also slowly enlarges the button.