2

I have been searching this on internet, I have found some answers which were helpful like but they were not enough to solve my problem (e.g. Similar Problem but no solution provided for my problem)

I am using JRate plugin, I am adding a div inside a div using jQuery. The problem is that when I add it using jQuery and use the JRate Functions then they are not working. But they are working without appending a new div.

I know how to make it work. I will have to use $(document) but I dont know how to use it with this code.

Here is HTML

<div class="jRate"></div>

Here is my Jquery

$(".jRate").jRate({
    onSet: function(rating) {                             
        alert(rating);
    }
});

Here is my appending code

var divjRate = "<div class='jRate'></div>";
$(divjRate).appendTo('.fb-jRate');

Can any one tell me how can I use $(document) here or any other alternative solution you have.

Community
  • 1
  • 1

2 Answers2

1

You need to append the html element first so that it is registered in the DOM. Then, you can call jRate on it

var divjRate = "<div><div class='jRate'></div></div>";

// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');

// Use plugin on new element
$('.jRate').jRate({
    onSet: function(rating) {                            
        alert(rating);
    }
});
AmmarCSE
  • 30,079
  • 5
  • 45
  • 53
0

The solution you have linked applies to binding event listeners, which is not the case with a typical jQuery plugin that usually involves DOM replacement and other things.

You will need to apply the method to newly added DOM elements. The DOM mutation event specification is deprecated due to performance issues, and it is not realistic to expect the browser to keep track of all changes (and what kind of changes) happening in the DOM.

For example, if you're adding new content with an AJAX call, you can apply the method to newly added content within the jqXHR.done() function.


Update: OP provided with some code, so I have adding a way to initialize the plugin for newly added DOM element:

// Declare new element
var divjRate = "<div><div class='jRate'></div></div>";

// Use plugin on new element
$(divjRate).find('.jRate').jRate({
    onSet: function(rating) {                            
        alert(rating);
    }
});

// Append new element to container of choice
$(divjRate).appendTo('.fb-jRate');
Terry
  • 63,248
  • 15
  • 96
  • 118