Reputation: 893
I am just starting to learn jQuery and have gotten some of the basic layout and UI plugins to work. However, I would like to create a custom widget that, using syntax that looks something like this:
var objs = [
{name: 'obj1', prop1: 'val1', prop2: 'val2'},
{name: 'obj2', prop1: 'val3', prop2: 'val4'},
{name: 'obj3', prop1: 'val5', prop2: 'val6'},
];
$(document).ready(function(){
myList = $('#divlist').mywidget(objs);
});
Where this code creates a list of draggable objects within the div named "divlist". The issue is here that the html/formatting that comprises the list items would need to be generated by the widget and dynamically added to the parent container, because they would not exist in the html beforehand.
All the jQuery tutorials I've seen operate on pre-existing html and just reformat/move/style it. Anyone have ideas about how I could do this?
Upvotes: 0
Views: 731
Reputation: 3526
I take it you want to know how to create new elements (like div or spans or tables) on the fly in JavaScript/jQuery? If so, there are a few ways.
Create it with the document object.
var my_new_element = document.createElement("div");
// Then feed it to jQuery so you can work with it.
$(my_new_element);
Or create it with jQuery.
var my_new_element = $('<div>');
For your solution, you'll need to loop over the array of JSON objects and create each div, adding them to your parent container as you go. Example:
var parent_div = '#divlist';
for (var i = 0; i < objs.length; i++) {
// Feed it straight to jQuery so it's easier to work with.
var widget_member = $(document.createElement('div'));
// Make it draggable.
widget_member.draggable();
// Append to the parent div.
$(parent_div).append(widget_member);
}
Upvotes: 1