Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
128
rated 0 times [  131] [ 3]  / answers: 1 / hits: 130195  / 12 Years ago, sun, november 25, 2012, 12:00:00

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?


More From » jquery

 Answers
7

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>


http://jsfiddle.net/cQNFL/



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.



[#81813] Friday, November 23, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;