Reputation: 1527
Is it possible to create a DOM element with a constructor using jquery?
I am trying to reverse-engineer a plug in called h5p, if you scroll down to the 'javascript' section you will see the following steps:
A declaration of a namespace for the object (I assume as to not pollute the global namespace
A consrtuctor function that creates the actual DOM element
Secondary helper functions that build the DOM element
I understand that this particular code is reliant on a framework, but is it possible for it to be replicated just in a single js file?
var H5P = H5P || {};
H5P.GreetingCard = (function ($) {
/**
* Constructor function.
*/
function C(options, id) {
// Extend defaults with provided options
this.options = $.extend(true, {}, {
greeting: 'Hello world!',
image: null
}, options);
// Keep provided id.
this.id = id;
};
/**
* Attach function called by H5P framework to insert H5P content into
* page
*
* @param {jQuery} $container
*/
C.prototype.attach = function ($container) {
// Set class on container to identify it as a greeting card
// container. Allows for styling later.
$container.addClass("h5p-greetingcard");
// Add image if provided.
if (this.options.image && this.options.image.path) {
$container.append('<img class="greeting-image" src="' + H5P.getPath(this.options.image.path, this.id) + '">');
}
// Add greeting text.
$container.append('<div class="greeting-text">' + this.options.greeting + '</div>');
};
return C;
})(H5P.jQuery);
This is what I imagine (warning: rough pseudocode ahead!):
// quick and dirty h5p prototyping
<!DOCTYPE html>
<html>
<head>
<script>import jquery here<script>
$(document).ready(function(){
// constructor for dom element
// secondary helpers for dom element
// initialize the element and append it to dom
});
</script>
</head>
<body>
<h2> h5p prototyping</h2>
</body>
Upvotes: 1
Views: 1688
Reputation: 43479
If I understand correctly than you can create DOM elements using jQuery in this way:
$(document).ready(function() {
var newDOM = $('<div/>', {
class: 'new-dom',
html: $('<span/>', {
text: 'NEW DOM!!'
}),
onClick: 'alert("Works EVEN JS");'
});
$('body').append(newDOM);
});
.new-dom {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Simply add required attributes of DOM element to second parameter of constructor object $('<nodeName/>', {settingsObject})
.
Upvotes: 3