JunM
JunM

Reputation: 7160

Click event on dynamic elements not working

In framework7, how to add click event on dynamic elements?

If I add my element first on my view, the click event works fine like below:

<div class="test">Click Me</div>

$$('.test').on('click', function () {
    myApp.alert("Gotcha!");
}); 

But if I have dynamic elements, especially elements dynamically added to virtual-list, I cannot make the click event to work. What is the right way to do this?

I even tried inline function, ex: <div class="test" onclick="myFunction();">Click Me</div>, still this won't work.

Upvotes: 0

Views: 1313

Answers (4)

Viplock
Viplock

Reputation: 3319

All answers are good to go with. But if you are using this class 'test' for other elements of the page, you will end up firing some extra click event(when you click on any other element of same class). So if you wanna prevent that, you should add listener to that particular element.

if you're adding an element of class test to an existing element of id testId, then use

 $('#testId').on('click', '.test', function(this){

   }

Upvotes: 1

Ionut Necula
Ionut Necula

Reputation: 11480

Use this for dinamically added elements:

$$(document).on('click', '.test', function () {
    myApp.alert("Gotcha!");
}); 

Upvotes: 1

n4gys4nyi
n4gys4nyi

Reputation: 933

In the function where you dynamically add the new elements you have to assign an event handler for them.

Lets say you have a function something like this

function addNewLines(){
  //add the new lines here
  // you have to run this again
  $$('.test').on('click', function () {
     myApp.alert("Gotcha!");
  }); 
}

Upvotes: 0

Farkhat Mikhalko
Farkhat Mikhalko

Reputation: 3655

You can use:

// Live/delegated event handler
$$(document).on('click', 'a', function (e) { 
  console.log('link clicked'); 
});

For your case:

$$(document).on('click', '.test', function(e){
  console.log('Some code...');
});

Here is docs. Scroll until events section.

Upvotes: 3

Related Questions