Note that there are some explanatory texts on larger screens.

plurals
  1. POIs there a better way to structure jQuery when using .on()?
    primarykey
    data
    text
    <p>I've recently completed something in jQuery after having to change it and I kind of feel dirty. But let me explain.</p> <p>My first attempt was simple, on page load I looped through and created all the bindings such as below I have attached below. This allows the bindings to happen at one time.</p> <pre><code>var flyouts = $('.comment[data-flyout]'); $.each(flyouts,function(){ var textarea = $(this).find('textarea'); var flyout = $(this).find('.write-comment__flyouts'); var addFile= $(this).find('[data-flyout=btn-file]'); textarea.click(function(){ flyout.addClass('open'); }); addFile.click(function(){ flyout.addClass('open').removeClass('open-link').toggleClass('open-files'); }); }); </code></pre> <p>Because of the project I've had to switch over to using jQuery's .on() function because content is dynamic. The problem there is that I can't create all the bindings at one time and instead, whenever there is a 'click' or a 'focus' have to navigate the DOM from that point up to a parent object and back down. Since I can't figure out a way to create the bindings at one point. Below is the same functionality as above.</p> <pre><code> var wrapper = $('.flyout-holder'); var textarea = 'textarea'; var flyout = '.write-comment__flyouts'; var addFile = '[data-flyout=btn-file]'; var parent = '.write-comment[data-flyout]'; wrapper.on('click',textarea,(function(){ $(this).closest(parent).find(flyout).addClass('open'); }); wrapper.on('click',addFile,function(){ $(this).closest(parent).find(flyout).addClass('open').removeClass('open-link').toggleClass('open-files'); }); </code></pre> <p>So I now have to go find the related object that I want to do something to every single time there's an event. Versus hooking it all up in the beginning. Is there a better way to do this when working with jQuery's .on() function?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload