i'm trying to generate some HTML using jQuery, I want to just create the elements with the required classes etc, and then append them to each other if that makes sense. I have written the below code, it doesn't produce any errors but also isn't adding the HTML to container at all.
What's wrong?
(function($) {
$.fn.twitter_plugin = function( options ) {
var container = this[0];
console.log('Started');
// Make aJax call
// Generate HTML
$con = $("<div>", { "class" : "tweet" });
$(container).append($con);
$col1 = $("<div>", { "class" : "twocol" });
$con.append($col1);
$col2 = $("<div>", { "class" : "tencol last" });
$con.append($col2);
// Profile Image
$tweet_profile_div = $("<div>", { "class" : "tweet-profile-photo" });
$col1.append($tweet_profile_div);
$profile_img = $("img", { "src" : '', "class" : "responsive-img" });
$tweet_profile_div.append($profile_img);
// END Profile Image
// Tweet
$tweet_head = $("div", { "class" : "tweet-head" });
// END Tweet
};
}(jQuery));
Executing this like so:
<script src="js-src/themev2/twitter_plugin.js"></script>
<script>
$( document ).ready(function() {
$("#map_canvas").twitter_plugin({ });
});
</script>
Edit 1
@Sean Reimer, my twitter_plugin function is being executed without that change you suggested, as the console.log is displayed, so this isn't the issue
-
Do you get your console log?Adjit– Adjit2016年07月28日 17:03:01 +00:00Commented Jul 28, 2016 at 17:03
-
Did you include jQuery?gaetanoM– gaetanoM2016年07月28日 17:05:47 +00:00Commented Jul 28, 2016 at 17:05
2 Answers 2
The problem is that you have an IIFE for jquery, but within you have your '$.fn.twitter_plugin function' defined but not called. At the end of your function definition you should add () to invoke it as well.
so
$tweet_head = $("div", { "class" : "tweet-head" });
// END Tweet
};
should be
$tweet_head = $("div", { "class" : "tweet-head" });
// END Tweet
}();
I also am not sure if this[0] is entirely reliable it might be better to just save the body as your container element. This is just a window object, so it doesn't have a 0 index element
var container = $('body')
would solve your problems.
1 Comment
this[0] gets the element defined from here $("#map_canvas").twitter_plugin({ }); as i need to put the new elements in there, not in the body. And thanks for the answer to my question :)Silly mistake I made, code works fine, I simply misspelt the ID for the target element, this works now.