简体   繁体   中英

How to use jQuery fadeIn with element created using .after?

I am new to jQuery and am trying to gracefully submit a form using AJAX rather than the traditional post method. So far I do the following to hide the form and prevent it from submitting:

$(document).ready( function() {
    $("#contact_me").submit( function(event) {
        event.preventDefault();
    });

    $('input#submit').click( function() {
        $('#contact_me').fadeOut( 1000, function() {
            $('#contact_me').hide();
            $('#contact_me').after( '<p class="submission_text">Thank you for contacting me. I will contact you shortly.</p>' );
        } );
    });
});

However, ideally, I would like the p.submission_text to fade in after the form has been hidden. However, if I append the following after the call to .after , the text does not fade in, it just appears:

$('.submission_text').fadeIn( 600 );

How can I get the behaviour I want?

.submission_text needs to be hidden in the first place in order to fade in. Try this:

$(document).ready( function() {
    $("#contact_me").submit( function(event) {
        event.preventDefault();
    });

    $('input#submit').click( function() {
        $('#contact_me').fadeOut( 1000, function() {
            var $p = $('<p class="submission_text" style="display:none">Thank you for contacting me. I will contact you shortly.</p>');

            $('#contact_me').hide();
            $('#contact_me').after( $p );

            $p.fadeIn( 600 );
        } );
    });
});

Because you are appending p tag with class 'submission_text' dynamically using jquery so,use event delegation as shown :

$(document).on('click','input#submit',function(){
  $('.submission_text').fadeIn( 600 );
});

Add the p.submission element as a hidden element initially with .hide() as follows:

$('input#submit').click( function() {
    $('#contact_me').fadeOut( 1000, function() {
        $('#contact_me').after( '<p class="submission_text">TEXT</p>')
        .hide()
        .fadeIn(600);
    } );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM