I have a problem with alert messages. It is displayed normally, and I can close it when the user presses x
(close), but when the user tries to display it again (for example, click on the button event) then it is not shown. (Moreover, if I print this alert message to console, it is equal to []
.) My code is here:
<div class="alert" style="display: none">
<a class="close" data-dismiss="alert">×</a>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
And event:
$(".alert").show();
P.S! I need to show alert message only after some event happened (for example, button clicked). Or what I am doing wrong?
Data-dismiss completely removes the element. Use jQuery's .hide() method instead.
The fix-it-quick method:
Using inline javascript to hide the element onclick like this:
<div class="alert" style="display: none">
<a class="close" onclick="$('.alert').hide()">×</a>
<strong>Warning!</strong> Best check yo self, you're not looking too good.
</div>
<a href="#" onclick="$('alert').show()">show</a>
This should however only be used if you are lazy (which is no good thing if you want an maintainable app).
The do-it-right method:
Create a new data attribute for hiding an element.
Javascript:
$(function(){
$("[data-hide]").on("click", function(){
$("." + $(this).attr("data-hide")).hide()
// -or-, see below
// $(this).closest("." + $(this).attr("data-hide")).hide()
})
})
and then change data-dismiss to data-hide in the markup. Example at jsfiddle.
$("." + $(this).attr("data-hide")).hide()
This will hide all elements with the class specified in data-hide, i.e: data-hide="alert"
will hide all elements with the alert class.
Xeon06 provided an alternative solution:
$(this).closest("." + $(this).attr("data-hide")).hide()
This will only hide the closest parent element. This is very useful if you don't want to give each alert a unique class. Please note that, however, you need to place the close button within the alert.
Definition of .closest from jquery doc:
For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.
Hey! Regarding your do it right answer. This will hide EVERY element that has the same class (ie,
alert
) on the page. A solution for this would be to replace the contents of the callback with this line$(this).closest("." + $(this).attr("data-hide")).hide();
, which will only affect the closest parent element, seeing as the dismiss button is typically placed within the alert it affects.That is true, I didn't think of making it work that way. That will, however, remove the simplicity of this solution to a small extent. I'll add it as an comment to the existing code. Thanks!
New to this.. where would you define the '$(function(){..'
Anywhere in a JavaScript file or in a <script>code here</script> tag.
If you would use $(document).on('click', '[data-hide]', function() { /* */ }) Your answer would be perfect ;)