I have 3 of the same widgets on my screen, widgets as in 3 div tags with content which the user chooses to have on his/her screen, which s/he can move and arrange on the screen. A bit like what iGoogle did. So basically, they can have 0 or more of the same widgets on the screen.
I got this working by using classes in the html instead of ids.
<div class="widget_1">
<div class="widget_header_1"></div>
<div class="widget_sub_header_1"></div>
<div class="widget_content_1"></div>
<div class="widget_footer_1"></div>
<div>
So if I have 2 of these widgets, the users screen will have 2 widgets with the class widget_1, i.e. the above html will be in the html source twice.
Anyway, I have a button in the sub_header of the widgets which adds data to the content section of the widget, i.e.
$('.my_button').live('click',function() {
get_data( $(this) );
});
That works fine, as in, if I click on the button in the first widget_1, only it’s content will change, if I click on the button in the second widget_1, only it’s content will change and it will not effect the other widget_1‘s.
To do that I am using:
$(this).closest('.widget_1').find('.widget_content_1').empty().append( some_data_here );
My question is, I want to prepend a loading image into the content when a button is clicked in the sub_header of a widget, so I tried:
$(this).closest('.widget_1').find('.widget_content_1').prepend( "<img class='imgLoading' src='/img/loading_white_32.gif'></img>" );
This works in that it only displays a loading image in the widget in which the button was clicked, but it displays 2 images in the clicked widget_1 if I have 2 widget_1‘s on the screen, and it will display 5 images in the clicked widget_1 if I have 5 widget_1‘s on the screen.
Why is that happening?
It should be displaying just 1 loading image in the clicked widget_1 no matter how many widget_1‘s are on the screen.
It looks like the code:
Runs once for each widget you create. This is unnecessary, and actually counter-productive, because a single call to
live()installs a delegated handler that will “see” theclickevents bubbling from all the elements that match.my_button, whichever widget they reside in.You have to find a way for that code to only run once (possibly in your widget’s common initialization routine if it has one).
In passing, note that live() is deprecated in favor of on() since jQuery 1.7. The code above would become: