Generate HTML using jQuery - javascript

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

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.

Silly mistake I made, code works fine, I simply misspelt the ID for the target element, this works now.

Related

Get ID of div created by jquery

I have two functions, where the first creates a div in the dom and the second gets the ID via getElementById(). Unfortunately, my second function is just returning null.
I looked in using $.Deffered() in either of my functions, but alas nothing I do seems to work
function one() {
var dynamicDiv = $("<div>").attr("id", 'test');
dynamicDiv.iziModal({
//modal content here
})
}
function two() {
var container = document.getElementById('test');
console.log(container.innerHTML); //not returning any data
}
enter code here
I had hoped to use this with a library that replaces images with a canvas object, but it requires that the "parent element to be a valid DOM Element". I have been searching for a while now, but I can not seem to find anything on the subject that is applicable.
** Edit**
Thank you for pointing out the error in my id (I had tried something else before I pasted). The iziModal function (http://izimodal.marcelodolza.com/) is currently pulling the content in via ajax (which I assume is the problem here):
The iziModal Function:
dynamicDiv.iziModal({
title: '',
autoOpen: 1,
width: 500,
onOpening: function (offer) {
offer.startLoading();
$.get(demoUrl, function (data) {
$('#' + id + " .iziModal-content").html(data);
offer.stopLoading();
});
}
});
Content of the other file:
<div id="test">
<img src="./bundle/images/coupon.jpg" />
</div>
function one() {
var dynamicDiv = $("<div>").attr("id", 'test');
dynamicDiv.iziModal({
//modal content here
});
$("body").append(dynamicDiv);
}

How to wrap a container div around a Ckeditor table onOk

When a user enters a table on the Ckeditor, I want to wrap a div around it with a class but I can't find a way to get this table HTML element. What is the best way to go about it?
I've tried creating a plugin to extend the table dialog onOk function (see code). This gives me all the properties from the table dialog but I don't want to have to create the whole table element again with all the properties as I don't want to re-write the existing table plugin.
I just need to get the code this plugin adds and wrap it in a div.
I thought about doing it in my projects javascript, when page loads, get all tables and wrap it in a div. However, this doesn't seem like the best way to do it at all. I thought there must be a way via ckeditor?
CKEDITOR.plugins.add( 'responsivetables', {
// The plugin initialization logic
init: function(editor) {
vsAddResponsiveTables(editor);
}
});
function vsAddResponsiveTables(editor){
CKEDITOR.on( 'dialogDefinition', function( ev ) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if ( dialogName == 'table') {
addTableHandler(dialogDefinition, editor);
}
});
}
function addTableHandler(dialogDefinition, editor){
dialogDefinition.onOk = function (a) {
// get table element and wrap in div?
}
}
I found the answer so for anyone else that needs it, this is what I did:
I used the insertElement event instead of when dialog was closed, only doing what I need if its a table that's being added.
// Register the plugin within the editor.
CKEDITOR.plugins.add( 'responsivetables', {
// The plugin initialization logic goes inside this method.
init: function(editor) {
vsAddResponsiveTables(editor);
}
});
function vsAddResponsiveTables(editor){
// React to the insertElement event.
editor.on('insertElement', function(event) {
if (event.data.getName() != 'table') {
return;
}
// Create a new div element to use as a wrapper.
var div = new CKEDITOR.dom.element('div').addClass('table-scroll');
// Append the original element to the new wrapper.
event.data.appendTo(div);
// Replace the original element with the wrapper.
event.data = div;
}, null, null, 1);
}
To the previous answer by 'gemmalouise' need to add one more line of code
CKEDITOR.editorConfig = function( config ) {
config.extraPlugins = 'responsivetables';
}
Otherwise it will not work (I cannot indicate this in the comment, because lack of 50 reputation).
And more compact code of this fuctional:
CKEDITOR.plugins.add('responsivetables', {
init: function (editor) {
editor.on('insertElement', function (event) {
if (event.data.getName() === 'table') {
var div = new CKEDITOR.dom.element('div').addClass('table-scroll'); // Create a new div element to use as a wrapper.
div.append(event.data); // Append the original element to the new wrapper.
event.data = div; // Replace the original element with the wrapper.
}
}, null, null, 1);
}
});

intercept or override javascript function of a class

I am new in javascript and jquery.
I have created a class having some functions in javascript.
My javascript class is written in a .js file.
common.js
var myGeneralClass = {
_show : function() {
console.log("showing some divs here");
},
_hide : function() {
console.log("hiding some divs here");
}
}
_show() and _hide() functions are bind to some events.
Now I have jsp file, from where final html is rendered.
myGeneralClass methods are called from various jsp files.
Some jsp script want to add some code in _show() and _hide() methods according to there need.
for eg :
employee.jsp
<script>
//want to add some lines of js code to _show() method plus its default code.
// intercept _show() method
_interceptShow : function() {
console.log("this line is custom for employee");
},
// override _show() method
_overrideShow : function() {
console.log("this line is custom for employee");
console.log("showing some divs here");
}
</script>
Can I override OR intercept methods in javascript?
Can it be possible ?
If yes then how?
For adding more code in method:
use this:
var temp = myGeneralClass._show;
myGeneralClass._show = function(){
temp();
// more code
}
for overriding:
myGeneralClass._show = function(){
// new code
}

How do I insert an html layout file into a div?

So right now I have a popup div (this is for a chrome extension) and right now the div pops up just fine.
What I would like to do is to inject this layout file that I created (lots of itty bitty design parts) into the div. How would I go about doing this. I tried to set the innerHTML property to index.html (the layout file)
jQuery(function($) {
// Mouse listener for any move event on the current document.
console.log("started"); //debug for starting
var popupStatus = 0; // set value
document.addEventListener('mousemove', function (e) {
var srcElement = e.srcElement;
// Lets check if our underlying element is a DIV.
if (srcElement.nodeName == 'A' || srcElement.nodeName == 'STRONG') {
loadPopup();
}
else{
disablePopup();
}
}, true);
function loadPopup() {
var x = document.getElementById("index");
if(popupStatus == 0) { // if value is 0, show popup
$('<div/>', {
id: 'cover',
innerHTML: index.html //line in question (making it "index.html" doesn't work)
}).appendTo(document.documentElement);
$('#cover').fadeTo("slow",1);
popupStatus = 1; // and set value to 1
}
}
function disablePopup() {
if(popupStatus == 1) { // if value is 1, close popup
$('#cover').fadeTo("slow",0);
$('#cover').remove();
popupStatus = 0;
}
}
});
Maybe you could use ajax to get the content of the file 'index.html'.
A snippet like this:
$.get("index.html", function( data ) {
$.('body').append('<div id="cover">' + data + '</div>');
});
could be placed at the line in question. Replace 'body' with whatever suits to your needs. The snippet can be certainly improved, but for now it should give you an idea.
I'm not aware of other possibilities to read files with JavaScript on the client side.
Or now I see, better make it:
$.get("index.html", function( data ) {
$('<div/>', {
id: 'cover',
innerHTML: data
}).appendTo(document.documentElement);
});
within the if-condition.
I'm not completely sure what you want to make, but it seems that you want to append it to the element with ID 'index'. Than you should change that appropriately in the last line.
EDIT:
Here are some slight changes:
$.get("index.html", function( data ) {
$('<div/>', {
id: 'cover',
html: data // this was making the problem
}).appendTo(x); // append to the element saved in the variable x
}, "html"); // state explicitly that the payload of data is HTML
that make the snippet working for me.

pass value/variable from fancybox iframe to parent

I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE

Categories

Resources