Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Salesforce
  3. Question
Salesforce

Adding onClick event dynamically via jquery not working in lightning

Asked by Nakamura Matsumoto Aug 8, 2021 1.7K views 2 answers
Share

About this question

<!--Required scripts.--> 
I have a filter button created dynamically, and there I am adding attributes using jquery .attr.
jQuery("document").ready(function(){ // Other code $(objFilterButton).attr('class', 'btn btn-default btn-lightning'); $(objFilterButton).attr('onClick', 'showFilter(event)'); });

The class gets added but, I cannot see the onClick event getting added on the dom. Is this a limitation in lightning?

enter image description here

Your answer

2 Answers

Webepej3 Latest answer

Answered on Mar 16, 2025

You're absolutely correct—jQuery's onclick event handlers don't work as expected with dynamically created word games elements in the Lightning framework due to its component encapsulation and shadow DOM structure.


The recommended solution is to use delegated event handling with $(elements).on(eventName, handlerRef) instead. This approach ensures that the event is properly handled even for dynamically added elements. Here's an example:


javascript

$[removed]('click', '.your-dynamic-element', function() {

    console.log('Dynamic element clicked!');

});

Was this helpful?

More Salesforce discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Salesforce Blogs

Guides, tips and career advice on Salesforce from JanBask experts.