I dynamically add a CSS class to a div containing a flash message with this line of code:
$("div#flash_notice").toggleClass('success');
The javascript file is in my micropost
view so that it is executed when I add a post. All is well except for when I add two posts without refreshing the page, because then the flash message loses it's style when it toggles back to remove the class. How can I get around this?
You can add the class only to elements that do not already have the class:
$("div#flash_notice").not('.success').addClass('success');
dont use toggle class. use addClass and it will add the class only if it does not have it:
$("div#flash_notice").addClass('success');
You can use the .addClass
method instead like others have mentioned. In repsonse to your comment about animating, you could do something like this:
var flashNoticeTimeout;
var fadeOutDelay = 1000;
function onPostAdded() {
var $flashNotice = $("#flash_notice"); // Get flash_notice element
$flashNotice.show().addClass("success"); // Show the flash element and then add the 'success' class.
// Need to use .show because the .fadeOut later on will have hidden this element
clearTimeout(flashNoticeTimeout); // Clear any previous timeouts. If the user button adds a post, then adds another post before the element has faded out, this will clear the last timeout so the element isn't hidden before 'fadeOutDelay`
flashNoticeTimeout = setTimeout(function() { // Trigger this anon function after 'fadeOutDelay' milliseconds (1000 milliseconds = 1 second)
$flashNotice.fadeOut(); // Fade out the element
}, fadeOutDelay);
}
See fiddle for demo.
or, easier: http://jsfiddle.net/LekisS/L2kvP/1/
$('div#flash_notice').delay(1000).fadeOut();