Federico Federico - 21 days ago 13
Javascript Question

.load and .unload external page inside a div

I'm using this jQuery function to load an external page inside a div on click.



$(document).on("click", ".more", function() {
$("#wait").load("www.google.com")
}),
$(document).on("click",".more",function(){
$("#wait").empty()
})

#wait{
width:80vw;
height:80vh;
position:fixed;
top:30px;
left:30px;
background:red;
}

#more{cursor:pointer}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="more">CLICK</div>
<div id="wait"></div>





It works but if I click to show that div again it will be empty.

What the alternative to
.empty()
?

Thanks.

Answer

From your post it seems you want to load it once and then just toggle.

$(document).on("click", ".more", function() {
  var $wait = $("#wait");
  if ($wait.html().length==0) $wait.load("about.html");
  $wait.show();
  $(this).toggleClass("more less");
});
$(document).on("click",".less",function(){
  $("#wait").hide();
  $(this).toggleClass("less more");
});

To add and delete each time you click the SAME button try this which seems to be very much what you already tried

$(document).on("click", ".more", function() {
  $("#wait").load("about.html");
  $(this).toggleClass("more less");
});
$(document).on("click",".less",function(){
  $("#wait").empty();
  $(this).toggleClass("less more");
});

One event handler:

$(document).on("click", ".moreorless", function() {
  if ($(this)hasClass("more")) {
    $("#wait").load("about.html");
    $(this).toggleClass("more less");
  }
  else {
    $("#wait").empty();
    $(this).toggleClass("less more");
  }
});
Comments