One-time event in jQuery
When we looked at unbinding events using the off
method, we used the following construct:
$('li').on('click', function() {
$(this).append('!');
$(this).off('click', func);
});
First we attached the handler function using on
, then unattached it using off
.
jQuery has a handy method one
that allows you to bind a one-time event - it will only be executed once, and then automatically unbind. This method takes the event type as its first parameter, and the bound function as its second.
We will look at the following example based on the HTML code below:
<ul>
<li>text</li>
<li>text</li>
<li>text</li>
</ul>
CSS the code looks like this:
li {
width: 100px;
cursor: pointer;
}
Now we bind a one-time event to each li
:
$('li').one('click', function() {
$(this).append('!');
});
Click on the list items. As you can see, we got the same effect thanks to the one
method.
Bind an event to all links - when you hover over a link, its href
is added to the end of its text in parentheses. After the first hover over a link, you should unbind the event from it, which adds href
to the end of the text.
For all inputs, make them output their value
alert when you click on any of them, but only on the first click. Clicking on the input again should not cause a reaction.
Given paragraphs with numbers. When you click on a paragraph, the square of the number it contains should appear in it, but only on the first click. When you double-click on a paragraph, the number in the paragraph should double, but also only the first time.
Given paragraphs. Make it so that on the first click on a paragraph, '!'
is added to the end, but only on the first click.