I’m using jQuery to show a success message after a form is submitted. The form is created using the wordpress plugin Contact Form 7. The class wpcf7-mail-sent-ok is added dynamically by the plugin ajax submission script. I’m trying to make it so that when the user clicks on the message, it fades out and then dissappears. For some reason though the removeClass method isn’t working.
Can anyone see any reason why it shouldn’t be working? The timeout function is definitely working as I tested it with an “alert()” call. Thanks for your help.
PS… i’m using LESS css so that explains the .opacity() syntax in the css posted here.
HTML:
<div class="wpcf7-response-output wpcf7-mail-sent-ok"><div class="image"></div></div>
Jquery + CSS
var $sent = $('.wpcf7-mail-sent-ok ');
function remove() {$sent.hide().removeClass('wpcf7-mail-sent-ok hide').removeAttr('style')}
$sent.live("click", function(){
$(this).addClass('hide');
setTimeout(remove,400)
});
.wpcf7-response-output {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
z-index: -1;
background: transparent;
opacity: 0;
-moz-opacity: 0;
.transition(opacity,.4s);
}
.wpcf7-response-output.wpcf7-mail-sent-ok .image {
width: 400px;
height: 138px;
display: block;
position: absolute;
z-index: 2000;
top: 50%;
left: 50%;
margin: 0;
background: url(assets/images/loading.png) no-repeat;
background-size: 0 0;
-webkit-transition: margin .4s ease-in-out;
-moz-transition: margin .4s ease-in-out;
-o-transition: margin .4s ease-in-out;
-ms-transition: margin .4s ease-in-out;
transition: margin .4s ease-in-out;
-webkit-animation: pulse 400ms ease-out infinite alternate;
-moz-animation: pulse 400ms ease-out infinite alternate;
-o-animation: pulse 400ms ease-out infinite alternate;
animation: pulse 400ms ease-out infinite alternate
}
.wpcf7-response-output.wpcf7-mail-sent-ok {z-index: 1000; background-color: rgba(255,255,255,.7); .opacity(1)}
.wpcf7-response-output.wpcf7-mail-sent-ok .image {
height: 132px;
position: absolute;
margin: -66px 0 0 -200px;
background-size: 100% 100%;
background: url(assets/images/img-sent.png) no-repeat center center;
}
.wpcf7-mail-sent-ok.hide {.opacity(0); z-index: -1}
It doesn’t work because at the point where you define the function
remove, the value of$senthas already be determined to be a jQuery object that matches no elements. This is because the matching happens as soon as you writeAt this time there is no “mail sent” element present yet.
The easiest way to fix this is to re-evaluate the selector within
remove:Another solution would be to just use
thisinside the click handler and pass it as a parameter toremove:Of course it’s even better to just use jQuery’s built-in
delayand get rid ofremovealtogether: