Reputation: 515
I created a jquery plugin, and now I want to bind it to DOM elements which are created by a php script.
Using the following markup as an example:
<div class="showcase_window">
<div id='mywhatever'></div>
<div id='mywhatever2'></div>
<div id='mywhatever3'></div>
</div>
This works:
$(document).ready(function(){
$('#mywhatever').showcase();
$('#mywhatever2').showcase();
$('#mywhatever3').showcase();
});
But since the markup is created by the php script, I am trying to get something like this to work:
$(document).ready(function(){
$('.showcase_window').children().on('showcase');
});
But I am a bit confused... I understand that 'on' is used to attach events, but I am not sure how to go about it...
Many thanks!
P.S.: Here is the plugin:
$.fn.showcase = function () {
return this.each(function() {
var $this = $(this);
$this.find(".sc_itm_display").hover(function() {
$this.find(".sc_img_front").stop(true,true).fadeOut("slow");
}, function() {
$this.find(".sc_img_front").stop(true,true).fadeIn("slow");
});
$this.find('.sc_color_select img').click(function() {
var color_path_1 = $(this).attr("src").replace("color","1");
var color_path_2 = $(this).attr("src").replace("color","2");
$this.find('.sc_itm_display .sc_img_back img').attr("src",color_path_1);
$this.find('.sc_itm_display .sc_img_front img').attr("src",color_path_2);
});
});
};
Upvotes: 0
Views: 1153
Reputation: 26380
If your PHP is generating the elements you want to act on, use it to output a script with an string of comma separated id values to target. Then use those targets for your plugin.
PHP outputs this:
var target_ids = "#this, #that, #the_other";
in your jQuery:
$(target_ids).showcase();
Alternately, use a unique class to label all the elements you want to target and you need not know their id.
$(".mywhatevers").showcase();
Upvotes: 1
Reputation: 2191
on
attaches handlers to events. Events can be user actions or processes completing/failing etc.
You are not attaching an event but a function, in which case jQuery does it for you.
$('.showcase_window').children()
or simply $('.showcase_window>div')
contains the three example divs created by your script.
$('.showcase_window').children().showcase();
(or more efficiently $('.showcase_window>div').showcase();
)
will execute showcase()
once for each of these divs. this
within showcase
will be the div ('mywhatever') itself.
Upvotes: 1