Question

I have an issue where I have the following jQuery and mark up working although if I move the location of textarea the .click() event doesn't fire. I haven't seen this $('element', something) before. What does the $wrapper syntax mean please? Thanks,

 this.each(function () {
     var $field = $(this);
     var $wrapper = $field.parent();


      $('.myClass', $wrapper)
          .click(function () { 
              // do stuff
          });

<div>
  <textarea></textarea>
  <img src="x" class="myClass" />
</div>
Was it helpful?

Solution

This answer assumes that $(this) refers to the textarea, which isn't clear from your question.

The second parameter in $('.myClass', $wrapper) refers to the context of the first parameter. That is, the first parameter is a descendant of the second parameter.

If $field is your text area, the context of .myClass is the parent of the textarea (as that is how you've defined $wrapper).

If you move the textarea out of the DIV that also contains .myClass, your context changes. Since .myClass is no longer in that context, the event handler is not bound to it.

If you want the click event bound to .myClass irrespective of context, use:

$('.myClass').click(function () { 
     // do stuff
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top