Reputation: 31
I'm displaying an error message in the middle of the screen, then after a few seconds it will fade out.
This works, but what I don't want happening is the error message moving to the far left of the screen when fading out.
I'm not sure if this is being cause because of css or the actual jquery itself.
Here's an example of what's happening: http://jsfiddle.net/dLt51xwe/
$(document).ready(function () {
$("button").click(function () {
$('#error').html("<div class='error-message'>ERROR</div>").show();
setTimeout(function () {
$('#error').hide("slow");
}, 1000);
});
});
I was wondering if it was the margin on the css that was causing it, so I tried this instead:
left: 50%;
transform: translate(-50%, 0);
width: 40%;
position: relative;
But I still got the same problem where the element would move to the far left while fading out.
I've also tried using the fadeOut() option provided, but the fading doesn't work. The fadeOut() seems to only work in an event for me, and I'm using this in an else statement.
Example out of an event: http://jsfiddle.net/dLt51xwe/1/
Any help is greatly appreciated, Thanks!
Upvotes: 2
Views: 101
Reputation: 56
Simply use jQuery function fadeOut()
will solve the problem:
Change
$('#error').hide("slow");
to
$('#error').fadeOut("slow");
Upvotes: 0
Reputation: 3194
use .fadeOut("slow")
instead of .hide("slow")
the issue is to do with the default easing on hide(). I've always found it hard to find the available strings to use for the easing option - so its simpler to use fadeIn()
and fadeOut()
.
$(document).ready(function () {
$("button").click(function () {
$('#error').html("<div class='error-message'>ERROR</div>").show();
setTimeout(function () {
$('#error').fadeOut("slow");
}, 1000);
});
});
in response to ItsMatt's comment
See your fiddle updated: http://jsfiddle.net/dLt51xwe/2/
fadeOut()
and hide()
wasn't working on the <errormessage>
element you created, so instead I edited the javascript to call fadeOut()
on the internal div .error-message
rather than the <errormessage>
container element.
See here:
$(document).ready(function () {
$('errormessage').html("<div class='error-message'>Please enter a valid message!</div>").show();
setTimeout(function () {
$('.error-message').fadeOut("slow");
}, 1000);
});
Upvotes: 3