Possible to know when x-show
/x-transition
have completed showing or hiding the element?
#3643
-
Is it possible to be notified or run a callback when I’m looking for a definitive way to know when something has been shown or hidden, regardless of whether transitions are used. Something that covers the cases of Does Alpine know when the transition is complete? And is it possible to hook into that somehow? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 10 replies
-
When a transition happens, You can use some code to tap into element internals, and, after x-show/x-transition is registered, wrap Is there a reason why you'd want to hook into the action in the dom and not onto the values themselves? There's a few different ways to do the general idea of knowing when the show evaluates, but which makes sense depends on why you want to do it in the first place. |
Beta Was this translation helpful? Give feedback.
-
I had the same problem. I needed to know when all content panels in an accordion had finished changing their visibility (changed by x-show) in order to scroll to the currently open one. // this is code is run inside the init-function of the component
const debounceScroll = window.Alpine.debounce(() => {
myScrollMethod()
}, 100)
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if( mutation.type === 'attributes' &&
mutation.attributeName === 'style' &&
mutation.target.hasAttribute('data-accordion-content')
) {
debounceScroll()
}
})
})
observer.observe(this.$root, {
attributeFilter: ['style'],
subtree: true,
}) |
Beta Was this translation helpful? Give feedback.
When a transition happens,
transitionend
event is dispatched, this is native behavior. It won't happen when there is no transition.You can use some code to tap into element internals, and, after x-show/x-transition is registered, wrap
el._x_doShow
in another function that also does whatever you want and put that in it's place.Is there a reason why you'd want to hook into the action in the dom and not onto the values themselves?
There's a few different ways to do the general idea of knowing when the show evaluates, but which makes sense depends on why you want to do it in the first place.