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

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.

Related

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);
}
});

Resize one textarea with another?

I have a website with a few pages, each containing two textareas. All I'm trying to do is get it so that when the user resizes one of the textboxes, the other one sizes with it.
Here's what I've tried so far:
Attempt #1
$(document).ready(function(){
var taheight;
$('textarea').resize(function(){
taheight = $(this).height();
$('textarea').not(this).css('height',taheight);
});
});
I also tried .on('resize', function()... and some other variations before realising it couldn't be done that way on account of the fact the resize functionality on textareas is a browser control, rather than part of the DOM.
Then I found this jsFiddle: jsfiddle.net/gbouthenot/D2bZd/
I tried modifying it and came up with this:
$(document).ready(function(){
var textareaResize = function(source, dest) {
var resizeInt = null;
var thisTextArea;
var resizeEvent = function() {
dest.outerHeight(source.outerHeight());
};
source.on("mousedown", function(e) {
resizeInt = setInterval(resizeEvent, 1000/30);
thisTextArea = $(this).attr('id');
});
$(window).on("mouseup", function(e) {
if (resizeInt !== null) {
clearInterval(resizeInt);
}
resizeEvent();
});
};
textareaResize($("#" + thisTextArea), $("textarea"));
});
But that wouldn't get the id of the target textarea. I also tried thisTextArea = e.target.id, but that wouldn't work either.
Help! Where are am I going wrong?
You can do that by using jQuery UI resizable() and call the resize event from it.
$("textarea").resizable({
resize: function() {
//To get the id of the textarea being resized
var id = $(this).find('textarea').attr('id');
//You could also just put the resize function code here
}
});
jQuery UI Resizable

Jquery .change() event fires only once

So I'm fairly novice with jquery and js, so I apologise if this is a stupid error but after researching I can't figure it out.
So I have a list of data loaded initially in a template, one part of which is a dropdown box that lets you filter the data. My issue is that the filtering only works once? As in, the .change function inside $(document).ready() only fires the once.
There are two ways to reload the data, either click the logo and reload it all, or use the search bar. Doing either of these at any time also means the .change function never fires again. Not until you refresh the page.
var list_template, article_template, modal_template;
var current_article = list.heroes[0];
function showTemplate(template, data)
{
var html = template(data);
$("#content").html(html);
}
$(document).ready(function()
{
var source = $("#list-template").html();
list_template = Handlebars.compile(source);
source = $("#article-template").html();
article_template = Handlebars.compile(source);
source = $("#modal-template").html();
modal_template = Handlebars.compile(source);
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
$("#classFilter").change(function()
{
console.log("WOW!");
var classToFilter = this.value;
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.heroClass.search(classToFilter) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
$("#searchbox").keypress(function (e)
{
if(e.which == 13)
{
var rawSearchText = $('#searchbox').val();
var search_text = rawSearchText.toLowerCase();
var filteredData =
{
heroes: list.heroes.filter(function(d)
{
if (d.name.search(search_text) > -1)
{
return true;
}
return false;
})
};
console.log(filteredData);
showTemplate(list_template,filteredData);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = filteredData.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
}
});
$("#logo").click(function()
{
showTemplate(list_template,list);
$(".articleButton").click(function()
{
var index = $(this).data("id");
current_article = list.heroes[index];
showTemplate(article_template,current_article);
$('.poseThumb').click(displayModal);
});
});
//$("#logo").click();
});
function displayModal(event)
{
var imageNumber = $(this).data("id");
console.log(imageNumber);
var html = modal_template(current_article.article[0].vicPose[imageNumber]);
$('#modal-container').html(html);
$("#imageModal").modal('show');
}
I should note two things: first, that the search bar works perfectly, and the anonymous function inside both of them is nearly identical, and like I said, the filtering works perfectly if you try it after the initial load. The second is that the same problem occurs replacing .change(anonymous function) with .on("change",anonymous function)
Any help or advice would be greatly appreciated. Thanks.
I agree with Fernando Urban's answer, but it doesn't actually explain what's going on.
You've created a handler attached to an HTML element (id="classFilter") which causes part of the HTML to be rewritten. I suspect that the handler overwrites the HTML which contains the element with the handler on it. So after this the user is clicking on a new HTML element, which looks like the old one but doesn't have a handler.
There are two ways round this. You could add code inside the handler which adds the handler to the new element which has just been created. In this case, that would mean making the handler a named function which refers to itself. Or (the easier way) you could do what Fernando did. If you do this, the event handler is attached to the body, but it only responds to clicks on the #classFilter element inside the body. In other words, when the user clicks anywhere on the body, jQuery checks whether the click happened on a body #classFilter element. This way, it doesn't matter whether the #classFilter existed when the handler was set. See "Direct and delegated events" in jQuery docs for .on method.
Try to use some reference like 'body' in the event listeners inside your DOM like:
$('body').on('click','.articleButton', function() {
//Do your stuff...
})
$('body').on('click','#classFilter', function() {
//Do your stuff...
})
$('body').on('keypress','#searchbox', function() {
//Do your stuff...
})
$('body').on('click','#logo', function() {
//Do your stuff...
})
This will work that you can fire it more than once.

javascript - Append element to list dynamically, but browser doesn't refresh UI

I have a JavaScript code segment for loading server's data items, and insert them into UL element with generated LI elements like this:
function loadNewFileTemplates() {
var list = _fileTemplateContainer.find("ul");
$.submitToServer("[server URL]", null, function (data) {
list.empty();
if (data == "") {
list.append("Templates not available."); // in sample code, removed HTML tags
}
else {
$.each(data, function (index, item) {
var itemElement = $("[HTML template string]");
itemElement.find("div[data-field='image']").css("background-image", "url(" + item.icon + ")");
itemElement.find("div[data-field='caption']").text(item.caption);
itemElement.find("div[data-field='description']").text(item.description);
itemElement.find("div[data-field='type']").text(item.type);
itemElement.bind("click", function (e) {
$(e.target).parents("ul").find("li").removeClass("projectSelected");
$(e.target).parents("li").addClass("projectSelected");
});
itemElement.appendTo(list);
});
}
console.log(list);
});
}
This code works on first loading, but in second loading, the UI cannot refresh after elements inserted into UL element.
I confirmed the data is inserted successfully (use console.log() to output result), so I can't find the reason about this issue.
Please view the screen shot for this issue.
How to resolve this problem?
Thanks.
My browser: Chrome 19.0.1084.56, IE 9.0.8112.16421
jQuery version 1.5.1
I resolved this issue myself.
I use my jQuery plug-in to initialize this form by using the following code:
designFrameManager.updateFrameBody(data); // data is a HTML string.
projectDesigner = $(data).projectDesigner({
height: designFrameManager.getBodyHeight(),
width: designFrameManager.getBodyWidth(),
projectName: name
});
updateFrameBody() method's code:
this.updateFrameBody = function (ui, initFunction) {
_designFrameBody.html(ui);
if (initFunction != null && $.isFunction(initFunction))
initFunction();
};
I think the plug-in's initialization can't be binded to DOM because the init action is after UI binding to DOM, so DOM can't auto-refresh the changes after my script's call.
So, I update the code to this:
projectDesigner = $(data).projectDesigner({
height: designFrameManager.getBodyHeight(),
width: designFrameManager.getBodyWidth(),
projectName: name
});
designFrameManager.updateFrameBodyByObject(
projectDesigner // initialized object
);
updateFrameBodyByObject() method's code:
this.updateFrameBodyByObject = function (ui, initFunction) {
_designFrameBody.html("");
_designFrameBody.append(ui);
if (initFunction != null && $.isFunction(initFunction))
initFunction();
};
This issue is fixed successfully.
Thanks for all replies.
Try to run this: $('ul').listview('refresh');

jstree - node selection based on current navigated url

Today I'm using the built-in cookies of the jsTree in order to preserve user navigations in the tree.
on node click in the tree the user is redirected to the corresponding page in my site and the clicked node is selected/highlighted thanks to the jsTree cookies integration.
Now, I would like to to select/highlight nodes in the tree also based on a navigation among the web site, i.e., a link in the site might also be a node in the tree, for example, a grid of rows that also appears in the tree.
The question is how can I do this 'manually' node selection/highlighting and I also think that I should know from where the user arrived to the page, from the tree or from some other link in the site.
Thanks,
I already built a complete approach for this using jsTree, hashchange event and actual real SEO-able URLs so this would fit into your idea quite simply and you could toss your cookies but not in a bad way. This also works with bookmarking and arriving from a URL as it looks through the nodes then matches the links to select the node. This is best with AJAX though as it should be when possible.
I'm commenting this for you so you can understand it. The working example is here www.kitgui.com/docs that shows all the content.
$(function () {
// used to remove double reload since hash and click are intertwined
var cancelHashChange = false,
// method sets the selector based off of URL input
setSelector = function (path) {
var startIndex = path.indexOf('/docs');
if (startIndex > -1) {
path = path.substr(startIndex);
}
path = path.replace('/docs', '').replace('/', '');
if ($.trim(path) === '') { path = 'overview'; }
return '.' + path;
};
// sets theme without the folders, plain jane
$('.doc-nav').jstree({
"themes": {
"theme": "classic",
"dots": true,
"icons": false
}
}).bind("loaded.jstree", function (event, data) {
// when loaded sets initial state based off of priority hash first OR url
if (window.location.hash) { // if hash defined then set tree state
$.jstree._focused().select_node(selector);
$(setSelector(window.location.hash.substr(1)) + ' a:first').trigger('click');
} else { // otherwise base state off of URL
$.jstree._focused().select_node(setSelector(window.location.pathname));
}
});
// all links within the content area if referring to tree will affect tree
// and jump to content instead of refreshing page
$('.doc-nav a').live('click', function (ev) {
var $ph = $('<div />'), href = $(this).attr('href');
ev.preventDefault();
cancelHashChange = true;
// sets state of hash
window.location = '#' + $(this).attr('href');
$('.doc-content').fadeOut('fast');
// jQuery magic load method gets remote content (John Resig is the man!!!)
$ph.load($(this).attr('href') + ' .doc-content', function () {
cancelHashChange = false;
$('.doc-content').fadeOut('fast', function () {
$('.doc-content').html($ph.find('.doc-content').html()).fadeIn('fast');
});
});
});
// if doc content is clicked and has referring tree content,
// affect state of tree and change tree content instead of doing link
$('.doc-content a').live('click', function (ev) {
ev.preventDefault();
if ($(this).attr('href').indexOf('docs/') > -1) {
$.jstree._focused().select_node(setSelector($(this).attr('href')));
$(setSelector($(this).attr('href')) + ' a:first').trigger('click', false);
}
});
// if back/forward are used, maintain state of tree as if it was being clicked
// refers to previously defined click event to avoid double-duty
// but requires ensuring no double loading
window.onhashchange = function () {
if (cancelHashChange) { cancelHashChange = false; return; }
$.jstree._focused().select_node(setSelector(window.location.hash.substr(1)));
$(setSelector(window.location.hash.substr(1)) + ' a:first').trigger('click', false);
};
$('#top-doc-link').closest('li').addClass('active');
});
Feel free to ask me if you have more questions.

Categories

Resources