Tell jQuery to execute specific code only once

Is there a way to tell jQuery to do something only once? For instance. right now, i need jQuery to click the div, add some HTML. Then every time someone clicks on this div, it switches to hide / show. Is there any way to do this? I try not to get too confusing.

EDIT: Solved!

+3
source share
4 answers

Use the method one.

For instance:

$('#myDiv').one('click', function() {
    $(this).append('...').click(function() { ... });
});
+18
source

There are several ways to do this.

Firstly, you can use a marker and then delete it:

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

from:

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

Secondly, you can change the event handlers:

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

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

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

, div, , .

+8

one. hide show toggle.

+4
source

Source: https://habr.com/ru/post/1726410/


All Articles