tags:

views:

99

answers:

4

Is there any way to tell jQuery to do something only once? E.g. right now, I need jQuery to on click of div, append some HTML. Then, every time someone clicks that div again it toggles hide/show. Is there a way to do this? I'm trying not to be too confusing.

EDIT: Solved!

+8  A: 

Use the one method.

For example:

$('#myDiv').one('click', function() {
    $(this).append('...').click(function() { ... });
});
SLaks
Why was this downvoted?
SLaks
Instead of upvoting the comment, you could upvote the answer.
SLaks
Maybe someone approves of the principle of explaining a downvote rather than approving the answer?
cletus
I hadn't thought of that.
SLaks
Even though, this ultimately did solve my problem, it was what I was looking for in the first place. This is the accepted answer.
WillyG
+1  A: 

jQuery's toggle: http://docs.jquery.com/Effects/toggle

philfreo
+3  A: 

You're looking for the one method. Alternatively you could use hide or show instead of toggle.

thenduks
+6  A: 

There are multiple ways of doing this.

Firstly you could use a marker and then remove it:

<div id="mydiv" class="not-initialized">
  ...
</div>

with:

$("#mydiv").click(function() {
  if ($(this).hasClass("not-initialized")) {
    $(this).removeClass("not-initialized");
    // append content
  } else {
    $(this).toggle();
  }
});

Secondly, you could change event handlers:

$("#mydiv").click(append_content);

function append_content() {
  ...
  $("#mydiv").unbind("click", append_content).click(toggle_display);
}

function toggle_display() {
  $(this).toggle();
}

Or you could do things like testing the div to see if the content is there.

cletus
I tried testing whether the content existed, edited my post with the details...or should I start a new topic?
WillyG