Question : jquery click functions not getting attached to dynamic div elements (a href)

Hello,

I'm trying to dynamically create html using jquery and dynamically create the contents of a div element on my html page.  When I alert the dynamic html and cut/paste it in the <div id="container"> the jquery functions all work ($('.ui-icon-zoomin').click(function()) but they don't work when I dynamically populate <div id="container"> and remove the hard coded html.  For some reason my jquery functions are not getting attached to the dynamic html.  The dynamic div elements are links (a1 and a2 variable names) and im using their class name to assign the click function after they are created.  var image_div = $('#container'); is the dynamic div.

html:
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
244:
<!doctype html>
<html lang="en">
	<head>
		<title>Opus 1 - Album Manager</title>
		<link type="text/css" href="jqueryui/css/ui.all.css" rel="stylesheet" />
		<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
		<script type="text/javascript" src="jqueryui/ui/ui.core.js"></script>
		<script type="text/javascript" src="jqueryui/ui/ui.draggable.js"></script>
		<script type="text/javascript" src="jqueryui/ui/ui.droppable.js"></script>
		<script type="text/javascript" src="jqueryui/ui/ui.resizable.js"></script>
		<script type="text/javascript" src="jqueryui/ui/ui.dialog.js"></script>		
		<script type="text/javascript" src="jqueryui/ui/effects.core.js"></script>
		<script type="text/javascript" src="jqueryui/ui/effects.highlight.js"></script>
		<script type="text/javascript" src="jqueryui/ui/ui.sortable.js"></script>		
		<link type="text/css" href="jqueryui/css/demos.css" rel="stylesheet" />
		<link type="text/css" href="jqueryui/css/ui.theme.css" rel="stylesheet" />
		<style type="text/css">
			#gallery { float: left; width: 65%; min-height: 12em; } * html #gallery { height: 12em; } /* IE6 */
			.gallery.custom-state-active { background: #eee; }
			.gallery li { float: left; width: 96px; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; }
			.gallery li h5 { margin: 0 0 0.4em; cursor: move; }
			.gallery li a { float: right; }
			.gallery li a.ui-icon-zoomin { float: left; }
			.gallery li img { width: 100%; cursor: move; }
			#trash { float: right; width: 32%; min-height: 60em; padding: 1%;} * html #trash { height: 60em; } /* IE6 */
			#trash h4 { line-height: 16px; margin: 0 0 0.4em; }
			#trash h4 .ui-icon { float: left; }
			#trash .gallery h5 { display: none; }
			.ui-dialog .ui-state-highlight, .ui-dialog .ui-state-error { padding: .3em;  }		
		</style>
<script language="javascript" type="text/javascript">
			$(function() {
				var image_div = $('#container');
				var ul = $(document.createElement("ul"))
					.attr("class", "gallery ui-helper-reset ui-helper-clearfix")
					.attr("id", "gallery");
				$.get("images.php", function(theXML){
					$('image',theXML).each(function(i){					 
					 	var filename = $(this).find("fileName").text();			
						var h5Text = $(document.createTextNode(filename));
						var h5 = $(document.createElement("h5"))
							.attr("class", "ui-widget-header")
							.append(h5Text);
	
						var img = $(document.createElement("img"))
							.attr("src", "testimages/" + filename)
							.attr("width", "75")
							.attr("height", "75");
	
						var a1Text = $(document.createTextNode("View Larger"));
						var a1 = $(document.createElement("a"))
							.attr("class", "ui-icon ui-icon-zoomin")
							.attr("href", "testimages/" + filename)
							.append(a1Text);
	
						var a2Text = $(document.createTextNode("Delete Image"));
						var a2 = $(document.createElement("a"))
							.attr("class", "ui-icon ui-icon-trash")
							.attr("href", "")
							.append(a2Text);
	
						var li = $(document.createElement("li"))
							.attr("class", "ui-widget-content ui-corner-tr")
							.append(h5)
							.append(img)
							.append(a1)
							.append(a2)
							.append(li);
				   
				   	ul.append(li);
				  }
				);
				image_div.append(ul);
				var spanText = $(document.createTextNode("Trash"));
				var span = $(document.createElement("span"))
					.attr("class", "ui-icon ui-icon-trash")
					.append(spanText);
	
				var h4Text = $(document.createTextNode("Trash"));
				var h4 = $(document.createElement("h4"))
					.attr("class", "ui-widget-header")
					.append(h4Text)
					.append(span);
	
				var trash_div = $(document.createElement('div'))
					.attr("id", "trash")
					.attr("class", "ui-widget-content ui-state-default")
					.append(h4);
	
				image_div.append(trash_div);	
			    	
					
				});
				// there's the gallery and the trash
				var $gallery = $('#gallery'), $trash = $('#trash');
				// let the gallery items be draggable
				$('li',$gallery).draggable({
					cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
					revert: 'invalid', // when not dropped, the item will revert back to its initial position
					containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
					helper: 'clone',
					cursor: 'move'
				});
				// let the trash be droppable, accepting the gallery items
				$trash.droppable({
					accept: '#gallery > li',
					activeClass: 'ui-state-highlight',
					drop: function(ev, ui) {
						deleteImage(ui.draggable);
					}
				});
				// let the gallery be droppable as well, accepting items from the trash
				$gallery.droppable({
					accept: '#trash li',
					activeClass: 'custom-state-active',
					drop: function(ev, ui) {
						recycleImage(ui.draggable);
					}
				});
				// image deletion function
				var recycle_icon = '<a href="link/to/recycle/script/when/we/have/js/off" title="Recycle this image" class="ui-icon ui-icon-refresh">Recycle image</a>';
				function deleteImage($item) {
					$item.fadeOut(function() {
						var $list = $('ul',$trash).length ? $('ul',$trash) : $('<ul class="gallery ui-helper-reset"/>').appendTo($trash);
						$item.find('a.ui-icon-trash').remove();
						$item.append(recycle_icon).appendTo($list).fadeIn(function() {
							$item.animate({ width: '48px' }).find('img').animate({ height: '36px' });
						});
					});
				}
				// image recycle function
				var trash_icon = '<a href="link/to/trash/script/when/we/have/js/off" title="Delete this image" class="ui-icon ui-icon-trash">Delete image</a>';
				function recycleImage($item) {
					$item.fadeOut(function() {
						$item.find('a.ui-icon-refresh').remove();
						$item.css('width','96px').append(trash_icon).find('img').css('height','72px').end().appendTo($gallery).fadeIn();
					});
				}
				// image preview function, demonstrating the ui.dialog used as a modal window
				function viewLargerImage($link) {
					var src = $link.attr('href');
					var title = $link.siblings('img').attr('alt');
					var $modal = $('img[src$="'+src+'"]');
					if ($modal.length) {
						$modal.dialog('open')
					} else {
						var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />')
							.attr('src',src).appendTo('body');
						setTimeout(function() {
							img.dialog({
									title: title,
									width: 400,
									modal: true
								});
						}, 1);
					}
				}
				// resolve the icons behavior with event delegation
				$('ul.gallery > li').click(function(ev) {
					var $item = $(this);
					var $target = $(ev.target);
					if ($target.is('a.ui-icon-trash')) {
						deleteImage($item);
					} else if ($target.is('a.ui-icon-zoomin')) {
						viewLargerImage($target);
					} else if ($target.is('a.ui-icon-refresh')) {
						recycleImage($item);
					}
					return false;
				});
				var name = $("#name"),
			email = $("#email"),
			password = $("#password"),
			allFields = $([]).add(name).add(email).add(password),
			tips = $("#validateTips");
		function updateTips(t) {
			tips.text(t).effect("highlight",{},1500);
		}
		function checkLength(o,n,min,max) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass('ui-state-error');
				updateTips("Length of " + n + " must be between "+min+" and "+max+".");
				return false;
			} else {
				return true;
			}
		}
		function checkRegexp(o,regexp,n) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass('ui-state-error');
				updateTips(n);
				return false;
			} else {
				return true;
			}
		}
			$("#dialog").dialog({
			bgiframe: true,
			autoOpen: false,
			height: 530,
			width: 545,
			modal: true,
			buttons: {
				'Save': function() {
					$(this).dialog('close');
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			close: function() {
				allFields.val('').removeClass('ui-state-error');
			}
		});
		$('#emptyTrash').click(function(){
			$('ui-helper-reset').remove();
		});
	[b]	$('.ui-icon-zoomin').click(function() {
			$('#picLg').attr('src', $(this).attr('href'));
			$('#caption').attr('value', 'this will be the caption text from each photo');
			$('#dialog').dialog('open');
		})[/b]
			});
		</script>
			</head>
	<body>
		<div id="container" class="demo ui-widget ui-helper-clearfix">
		</div

<div class="demo">
<div id="dialog" title="Edit Picture">
	<form>
		<fieldset>
			<img id="picLg"/><br/>
			<label for="name">Caption:</label>
			<input id="caption" type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" size="60"/><br/>
			<label for="email">Album Cover:</label>
			<input type="checkbox" name="team" value="team">	
		</fieldset>	
	</form>
</div>
	</body>
</html>




Answer : jquery click functions not getting attached to dynamic div elements (a href)

No, i was saying this
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
198:
199:
200:
201:
202:
203:
204:
205:
206:
207:
208:
209:
210:
211:
212:
213:
214:
215:
216:
217:
218:
219:
220:
221:
222:
223:
224:
225:
226:
227:
228:
229:
230:
231:
232:
233:
234:
235:
236:
237:
238:
239:
240:
241:
242:
243:
<!doctype html>
<html lang="en">
      <head>
            <title>Opus 1 - Album Manager</title>
            <link type="text/css" href="jqueryui/css/ui.all.css" rel="stylesheet" />
            <script type="text/javascript" src="js/jquery-1.3.2.js"></script>
            <script type="text/javascript" src="jqueryui/ui/ui.core.js"></script>
            <script type="text/javascript" src="jqueryui/ui/ui.draggable.js"></script>
            <script type="text/javascript" src="jqueryui/ui/ui.droppable.js"></script>
            <script type="text/javascript" src="jqueryui/ui/ui.resizable.js"></script>
            <script type="text/javascript" src="jqueryui/ui/ui.dialog.js"></script>            
            <script type="text/javascript" src="jqueryui/ui/effects.core.js"></script>
            <script type="text/javascript" src="jqueryui/ui/effects.highlight.js"></script>
            <script type="text/javascript" src="jqueryui/ui/ui.sortable.js"></script>            
            <link type="text/css" href="jqueryui/css/demos.css" rel="stylesheet" />
            <link type="text/css" href="jqueryui/css/ui.theme.css" rel="stylesheet" />
            <style type="text/css">
                  #gallery { float: left; width: 65%; min-height: 12em; } * html #gallery { height: 12em; } /* IE6 */
                  .gallery.custom-state-active { background: #eee; }
                  .gallery li { float: left; width: 96px; padding: 0.4em; margin: 0 0.4em 0.4em 0; text-align: center; }
                  .gallery li h5 { margin: 0 0 0.4em; cursor: move; }
                  .gallery li a { float: right; }
                  .gallery li a.ui-icon-zoomin { float: left; }
                  .gallery li img { width: 100%; cursor: move; }
                  #trash { float: right; width: 32%; min-height: 60em; padding: 1%;} * html #trash { height: 60em; } /* IE6 */
                  #trash h4 { line-height: 16px; margin: 0 0 0.4em; }
                  #trash h4 .ui-icon { float: left; }
                  #trash .gallery h5 { display: none; }
                  .ui-dialog .ui-state-highlight, .ui-dialog .ui-state-error { padding: .3em;  }            
            </style>
<script language="javascript" type="text/javascript">
            
             $(document).ready(function() {
                        var image_div = $('#container');
                        var ul = $(document.createElement("ul"))
                              .attr("class", "gallery ui-helper-reset ui-helper-clearfix")
                              .attr("id", "gallery");
                        $.get("images.php", function(theXML){
                              $('image',theXML).each(function(i){                               
                                     var filename = $(this).find("fileName").text();                  
                                    var h5Text = $(document.createTextNode(filename));
                                    var h5 = $(document.createElement("h5"))
                                          .attr("class", "ui-widget-header")
                                          .append(h5Text);
      
                                    var img = $(document.createElement("img"))
                                          .attr("src", "testimages/" + filename)
                                          .attr("width", "75")
                                          .attr("height", "75");
      
                                    var a1Text = $(document.createTextNode("View Larger"));
                                    var a1 = $(document.createElement("a"))
                                          .attr("class", "ui-icon ui-icon-zoomin")
                                          .attr("href", "testimages/" + filename)
                                          .append(a1Text);
      
                                    var a2Text = $(document.createTextNode("Delete Image"));
                                    var a2 = $(document.createElement("a"))
                                          .attr("class", "ui-icon ui-icon-trash")
                                          .attr("href", "")
                                          .append(a2Text);
      
                                    var li = $(document.createElement("li"))
                                          .attr("class", "ui-widget-content ui-corner-tr")
                                          .append(h5)
                                          .append(img)
                                          .append(a1)
                                          .append(a2)
                                          .append(li);
                           
                                 ul.append(li);
                          }
                        );
                        image_div.append(ul);
                        var spanText = $(document.createTextNode("Trash"));
                        var span = $(document.createElement("span"))
                              .attr("class", "ui-icon ui-icon-trash")
                              .append(spanText);
      
                        var h4Text = $(document.createTextNode("Trash"));
                        var h4 = $(document.createElement("h4"))
                              .attr("class", "ui-widget-header")
                              .append(h4Text)
                              .append(span);
      
                        var trash_div = $(document.createElement('div'))
                              .attr("id", "trash")
                              .attr("class", "ui-widget-content ui-state-default")
                              .append(h4);
      
                        image_div.append(trash_div);  
                        // there's the gallery and the trash
                        var $gallery = $('#gallery'), $trash = $('#trash');
                        // let the gallery items be draggable
                        $('li',$gallery).draggable({
                              cancel: 'a.ui-icon',// clicking an icon won't initiate dragging
                              revert: 'invalid', // when not dropped, the item will revert back to its initial position
                              containment: $('#demo-frame').length ? '#demo-frame' : 'document', // stick to demo-frame if present
                              helper: 'clone',
                              cursor: 'move'
                        });
                        // let the trash be droppable, accepting the gallery items
                        $trash.droppable({
                              accept: '#gallery > li',
                              activeClass: 'ui-state-highlight',
                              drop: function(ev, ui) {
                                    deleteImage(ui.draggable);
                              }
                        });
                        // let the gallery be droppable as well, accepting items from the trash
                        $gallery.droppable({
                              accept: '#trash li',
                              activeClass: 'custom-state-active',
                              drop: function(ev, ui) {
                                    recycleImage(ui.draggable);
                              }
                        });
                        // image deletion function
                        var recycle_icon = '<a href="link/to/recycle/script/when/we/have/js/off" title="Recycle this image" class="ui-icon ui-icon-refresh">Recycle image</a>';
                        // image recycle function
                        var trash_icon = '<a href="link/to/trash/script/when/we/have/js/off" title="Delete this image" class="ui-icon ui-icon-trash">Delete image</a>';
                        // resolve the icons behavior with event delegation
                        $('ul.gallery > li').click(function(ev) {
                              var $item = $(this);
                              var $target = $(ev.target);
                              if ($target.is('a.ui-icon-trash')) {
                                    deleteImage($item);
                              } else if ($target.is('a.ui-icon-zoomin')) {
                                    viewLargerImage($target);
                              } else if ($target.is('a.ui-icon-refresh')) {
                                    recycleImage($item);
                              }
                              return false;
                        });
                        var name = $("#name"),
                  email = $("#email"),
                  password = $("#password"),
                  allFields = $([]).add(name).add(email).add(password),
                  tips = $("#validateTips");

                  $("#dialog").dialog({
                  bgiframe: true,
                  autoOpen: false,
                  height: 530,
                  width: 545,
                  modal: true,
                  buttons: {
                        'Save': function() {
                              $(this).dialog('close');
                        },
                        Cancel: function() {
                              $(this).dialog('close');
                        }
                  },
                  close: function() {
                        allFields.val('').removeClass('ui-state-error');
                  }
            });
            $('#emptyTrash').click(function(){
                  $('ui-helper-reset').remove();
            });
            $('.ui-icon-zoomin').click(function() {
                  $('#picLg').attr('src', $(this).attr('href'));
                  $('#caption').attr('value', 'this will be the caption text from each photo');
                  $('#dialog').dialog('open');
            })
      });
});
            function checkRegexp(o,regexp,n) {
                  if ( !( regexp.test( o.val() ) ) ) {
                        o.addClass('ui-state-error');
                        updateTips(n);
                        return false;
                  } else {
                        return true;
                  }
            }
            function updateTips(t) {
                  tips.text(t).effect("highlight",{},1500);
            }
            function checkLength(o,n,min,max) {
                  if ( o.val().length > max || o.val().length < min ) {
                        o.addClass('ui-state-error');
                        updateTips("Length of " + n + " must be between "+min+" and "+max+".");
                        return false;
                  } else {
                        return true;
                  }
            }
                        function recycleImage($item) {
                              $item.fadeOut(function() {
                                    $item.find('a.ui-icon-refresh').remove();
                                    $item.css('width','96px').append(trash_icon).find('img').css('height','72px').end().appendTo($gallery).fadeIn();
                              });
                        }
                        // image preview function, demonstrating the ui.dialog used as a modal window
                        function viewLargerImage($link) {
                              var src = $link.attr('href');
                              var title = $link.siblings('img').attr('alt');
                              var $modal = $('img[src$="'+src+'"]');
                              if ($modal.length) {
                                    $modal.dialog('open')
                              } else {
                                    var img = $('<img alt="'+title+'" width="384" height="288" style="display:none;padding: 8px;" />')
                                          .attr('src',src).appendTo('body');
                                    setTimeout(function() {
                                          img.dialog({
                                                      title: title,
                                                      width: 400,
                                                      modal: true
                                                });
                                    }, 1);
                              }
                        }
                        function deleteImage($item) {
                              $item.fadeOut(function() {
                                    var $list = $('ul',$trash).length ? $('ul',$trash) : $('<ul class="gallery ui-helper-reset"/>').appendTo($trash);
                                    $item.find('a.ui-icon-trash').remove();
                                    $item.append(recycle_icon).appendTo($list).fadeIn(function() {
                                          $item.animate({ width: '48px' }).find('img').animate({ height: '36px' });
                                    });
                              });
                        }
            </script>
                  </head>
      <body>
            <div id="container" class="demo ui-widget ui-helper-clearfix">
            </div

<div class="demo">
<div id="dialog" title="Edit Picture">
      <form>
            <fieldset>
                  <img id="picLg"/><br/>
                  <label for="name">Caption:</label>
                  <input id="caption" type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" size="60"/><br/>
                  <label for="email">Album Cover:</label>
                  <input type="checkbox" name="team" value="team">      
            </fieldset>      
      </form>
</div>
      </body>
</html>
Random Solutions  
 
programming4us programming4us