Federico
Federico

Reputation: 1422

.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.

Upvotes: 0

Views: 903

Answers (2)

charlietfl
charlietfl

Reputation: 171669

Why not just load the data on page load and then toggle() the display when button is clicked?

$(function(){
    // add the content right when page loads
    $("#wait").load("about.html");
    $('#more').click(function(){
        // toggle display
        $("#wait").toggle();
        // toggle class
        $(this).toggleClass("less more");
    });
});

Upvotes: 1

mplungjan
mplungjan

Reputation: 178061

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");
  }
});

Upvotes: 2

Related Questions