Adding custom javascript to fields


Using jQuery to add extra functionality to your fields is simple. However, there is one key idea to remember; ACF can load in new HTML at different times on any specific page. This HTML may take the form of:

  • New field groups (when location rules are changed )
  • Repeater rows
  • Flexible content rows

To add custom functions / events to the HTML, you can use an action similar to native WP!

Using a jQuery action

Just like WP, ACF uses actions to allow you to hook in and add functionality to the new HTML. This action is a jQuery event called “acf/setup_fields”.

This event is triggered on the document element each time new HTML is added to the page. It is triggered on first load of the page (document.ready ) and each time 1 of the 3 items listed above are added.

You can use it like this:

$(document).live('acf/setup_fields', function(e, div){

	// div is the element with new html.
	// on first load, this is the $('#poststuff')
	// on adding a repeater row, this is the tr





How does it work?

Each time new HTML is added to the page, ACF triggers an event on the document object. This works across all browsers and is a very smart WP styled action / hook alternative.

The HTML is also passed through for you to use inside a custom listener function (as above in example).

By writing your code as above, the live event will only be fired when the event is triggered and code inside the each loop will only run if the selector found any matches.

Remember, you may have multiple instances of your element inside the new HTML, so it is important to use an each loop to make sure your code is applied to each element.