1

I got a button which, when it is being clicked, loades with ajax some content from another "randomstuff.php" file. The button should be able to take this "randomstuff.php" file away again without refreshing the page. My thought was to use .toggle some where in this equation but I do not know where and how :/

$(document).ready(function() {
  $("#savedButtonBox").click(function () {
    $("#content").load('moduleSavedStyles/moduleSavedStyles.php');
  });
});

With this method it loads the content into the original (index.php) website but now I want to toggle it so it gets taken away again. I need some help! :) Thanks in advance!

1 Answer 1

2

If I've understood what you're asking, you want to load() some content then clear the loaded HTML on alternate clicks of the same button.

If so, you don't want toggle(). Instead you can use is(':empty') to check if any content exists in the containing element and then either fill it or empty it. Try this:

$("#savedButtonBox").click(function () {
  var $container = $('#content');
  if ($container.is(':empty')) {
    $container.load('moduleSavedStyles/moduleSavedStyles.php');
  } else {
    $container.empty();
  }
});

Working example

Sign up to request clarification or add additional context in comments.

4 Comments

Yes, that's what I want to do but the code you provided doesn't achive that effect, it doesn't load any content anymore.
Sorry, I mixed up the variable names. Try now. If that doesn't work, try if ($container.children().length == 0). If that does work, you need to remove whitespace between the container's tags, eg. <div id="content"> </div> should be <div id="content"></div>
I added a working example in a jsFiddle for you. Note that I had to change the AJAX request for it to work with jsFiddle's rules, but the logic is identical. Hopefully it's of some help. If you're still having issues try checking the console for errors after you first click the button.
Now it works :) Thanks!! I suspect that the browser was cashing something old or similar.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.