I'm using the WPForms plugin on my WordPress site. One of my forms has a hidden field which appears when you click a radio button elsewhere on the form, and disappears again when you click another radio button.
The hidden field has a class of .wpforms-conditional-hide
when it's hidden, which is set to display:none
. And the class magically changes to .wpforms-conditional-show
, which is set to display:block
, when the field is revealed.
I would like to animate the hiding and showing of this field, for example by having it slide in and out of view. I can't use CSS, because CSS isn't able to do animations/transitions with the "display" attribute, and the hidden field doesn't have a set height. I already have jQuery on my site, so I'd like to find a way to achieve this with jQuery, eg. using something like slideToggle or similar.
The thing is, I don't want to have the animation bound to the click action on the radio button. Particularly because I'd like this to be able to work on any hidden field on any form. So, if it's possible, I'd simply like a way to use slideToggle (or something similar) whenver the hidden field's class changes from .wpforms-conditional-hide
to .wpforms-conditional-show
and back, or alternatively whenever its CSS attribute changes from display:none
to display:block
and back.
Is that possible?
[UPDATE]
For the record, here is the entire function I'm now using, which incorporates the code and suggestions that @blex has provided his answer and his comments. The function below will work "as is" with WPForms on WordPress.
function slide_hidden_wpforms_fields() {
if ( wp_script_is( 'jquery', 'done' ) ) {
?>
<script type="text/javascript">
jQuery( document ).ready(function( $ ) {
$( document ).one( "wpformsProcessConditionals", function() {
var classname = 'wpforms-conditional-show';
$( '.wpforms-field' ).each( function( i, el ) {
var wasVisible = $( el ).hasClass( classname );
var obs = new MutationObserver( function( mutations ) {
mutations.forEach( function( mutation ) {
if ( mutation.attributeName === 'class' ) {
isVisible = $( el ).hasClass( classname );
if ( isVisible !== wasVisible ) {
wasVisible = isVisible;
$( el )[isVisible ? 'hide' : 'show']().slideToggle( 200 );
}
}
});
});
obs.observe( el, {
'attributes': true
});
});
});
});
</script>
<?php
}
}
add_action( 'wpforms_wp_footer_end', 'slide_hidden_wpforms_fields' );