Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery and Ajax: show/hide div

I have this example.

When I click, a dynamic content load via Ajax. In the loaded page there is a link, that could close the div. It works, but when the div is closed (with hide()), the click on link don't reopen loaded page.

Why? How can I create a button, that show/hide a div loaded with Ajax?

Calling page :

<script type="text/javascript">
function getAjax(divdett,pageload) {
$(function(){$(divdett).load(pageload);});}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>click</title>
</head>
<body>
<a href="javascript:getAjax('#siteloader','jquery_divajax.htm');">click</a>
<div id="siteloader"></div>
</body>

Included page :

<script type="text/javascript">
function delAjax(divdett) {
$(divdett).hide();
}
</script>
OK!
<a id="#chiudi" href="#" onclick="delAjax('#siteloader');">chiudi</a>
like image 394
Mario Avatar asked Sep 23 '12 18:09

Mario


People also ask

How do I toggle Show hide in jQuery?

jQuery toggle() MethodThe toggle() method toggles between hide() and show() for the selected elements. This method checks the selected elements for visibility. show() is run if an element is hidden. hide() is run if an element is visible - This creates a toggle effect.

How can I show and hide div on mouse click using jQuery?

To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides.

How do I hide a div and then show on click?

To display or hide a <div> by a <button> click, you can add the onclick event listener to the <button> element. The onclick listener for the button will have a function that will change the display attribute of the <div> from the default value (which is block ) to none .


2 Answers

In your "close" button, you call hide().

Change your getAjax function to this :

function getAjax(divdett,pageload) {
$(function(){$(divdett).load(pageload).show();});}

I just added .show() to ensure the div is visible even if it has been made hidden before.

Note that I respected the original construct but this is much too complex : no need to call $(function when you can simply do

function getAjax(divdett,pageload) {
$(divdett).load(pageload).show();}

If you want to have only one button, you may remove the one of the second file and change the getAjax function to

function getAjax(divdett,pageload) {
     var div = $(divdett);
     if (div.is(':visible')) div.hide();
     else div.load(pageload).show();
}
like image 147
Denys Séguret Avatar answered Oct 13 '22 23:10

Denys Séguret


I think it doesn't work because HTML DOM already loaded. For dynamic binding you need to use function .bind() or .live() (Documentation for bind()).

For example:

$( "#foo" ).bind( "click", function() {
  $( this ).hide(); // or show();
});
like image 39
Mr.OFF Avatar answered Oct 14 '22 00:10

Mr.OFF