I have to integrate several html type tags (ex: <div id = "mysection"> <div class = "mycontainer"> <h1> mytitle </h1> </div> </div>) to format data (here "mytitle") output in javascript
So, I have in my HTML <span id="datahere"></span>
and the js i need to edit is :
function Bigdata(title, subtitle, type) {
const mydata = document.getElementById('datahere');
mydata.innerHTML += title + subtitle + (type ? ' <strong>(type is ' + type + ')</strong>' : '') +'<br/>';
}
// element in which the data is initialized, visible in another <span>
const sprit = document.getElementById('sprit');
// when a given message is received
sprit.addEventListener(SpritEvents.MessageSprit, ({ data }) => {
Bigdata('Sprit', data.text, data.type);
// if there are actions, we offer links
if (data.actions) {
var links = '';
for (var i = 0; i < data.actions.length; i++) {
if (i > 0) {
links += ', ';
}
let act = data.actions[i];
links += '<a data-val="' + act.value + '">' + act.title + '</a>';
}
Bigdata('Sprit', links);
}
});
I cannot integrate the tags which must "contain" data (title, subtitle, type) WHITH links if there are actions ...
if I add my tags like this: mydata.innerHTML += '<div id = "mysection"> <div class = "mycontainer"><h1>' + title + '</h1>' + subtitle + (type ? ' <strong>(type =' + type + ')</strong>' : '') +'<br/></div></div>';
that does not surround the whole, the div and the h1 are duplicated (surrounds on one side title, subtitle, type and on the other links).
I'm not used to using pure javascript ... I hope you can help me
I recommend rewriting it using Template literals:
mydata.innerHTML += `<h1>${title}</h1>`;
More on this topic:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
This makes things look much lighter.
Also, it looks like you are not closing the html tags. For example: <div>, needs to be closed with </div>
Related
I made a forEach case for text loop,
and this moment, I;m facing a problem that I cannot put span tag in return result of innerText.
data.forEach(item => {
const dataTitle = document.createElement('p');
dataTitle.innerText = data.title + '<span class="p-90">' + data.subTitle + '</span>'
viewContainer.appendChild(dataTitle);
});
this is my code, but the < span class =".... is exposed to the site in raw.
how can I fix it?
Try this. use innerHTML instead of innerText and replace data.title with item.title. same for data.subTitle.
data.forEach((item) => {
const dataTitle = document.createElement("p");
dataTitle.innerHTML =
item.title + '<span class="p-90">' + item.subTitle + "</span>";
viewContainer.appendChild(dataTitle);
});
I'm using jQuery to get values from ajax rest call, I'm trying to concatenate these values into an 'a' tag in order to create a pagination section for my results (picture attached).
I'm sending the HTML (divHTMLPages) but the result is not well-formed and not working, I've tried with double quotes and single but still not well-formed. So, I wonder if this is a good approach to accomplish what I need to create the pagination. The 'a' tag is going to trigger the onclick event with four parameters (query for rest call, department, row limit and the start row for display)
if (_startRow == 0) {
console.log("First page");
var currentPage = 1;
// Set Next Page
var nextPage = 2;
var startRowNextPage = _startRow + _rowLimit + 1;
var query = $('#queryU').val();
// page Link
divHTMLPages = "<strong>1</strong> ";
divHTMLPages += "<a href='#' onclick='getRESTResults(" + query + "', '" + _reg + "', " + _rowLimit + ", " + _startRow + ")>" + nextPage + "</a> ";
console.log("Next page: " + nextPage);
}
Thanks in advance for any help on this.
Pagination
Rather than trying to type out how the function should be called in an HTML string, it would be much more elegant to attach an event listener to the element in question. For example, assuming the parent element you're inserting elements into is called parent, you could do something like this:
const a = document.createElement('a');
a.href = '#';
a.textContent = nextPage;
a.onclick = () => getRESTResults(query, _reg, _rowLimit, _startRow);
parent.appendChild(a);
Once an event listener is attached, like with the onclick above, make sure not to change the innerHTML of the container (like with innerHTML += <something>), because that will corrupt any existing listeners inside the container - instead, append elements explicitly with methods like createElement and appendChild, as shown above, or use insertAdjacentHTML (which does not re-parse the whole container's contents).
$(function()
{
var query=10;
var _reg="12";
var _rowLimit="test";
var _startRow="aa";
var nextPage="testhref";
//before divHTMLPages+=,must be define divHTMLPages value
var divHTMLPages = "<a href='#' onclick=getRESTResults('"+query + "','" + _reg + "','" + _rowLimit + "','" + _startRow + "')>" + nextPage + "</a>";
///or use es6 `` Template literals
var divHTMLPages1 = `` + nextPage + ``;
$("#test").append("<div>"+divHTMLPages+"</div>");
$("#test").append("<div>"+divHTMLPages1+"</div>");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
I am creating a simple bootstrapped add-on for Firefox. I need to capture the current URL from the browser through sidebar with a button click.
My bootstrap.js:
const {classes: Cc, interfaces: Ci, utils: Cu} = Components;
Cu.import('resource://gre/modules/Services.jsm');
Cu.import("resource://gre/modules/NetUtil.jsm");
Cu.import("resource://gre/modules/FileUtils.jsm");
/*start - windowlistener*/
var windowListener = {
//DO NOT EDIT HERE
onOpenWindow: function (aXULWindow) {
// Wait for the window to finish loading
let aDOMWindow =aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal||Ci.nsIDOMWindow);
aDOMWindow.addEventListener("load", function () {
aDOMWindow.removeEventListener("load", arguments.callee, false);
windowListener.loadIntoWindow(aDOMWindow, aXULWindow);
}, false);
},
onCloseWindow: function (aXULWindow) {},
onWindowTitleChange: function (aXULWindow, aNewTitle) {},
register: function () {
// Load into any existing windows
let XULWindows = Services.wm.getXULWindowEnumerator(null);
while (XULWindows.hasMoreElements()) {
let aXULWindow = XULWindows.getNext();
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
windowListener.loadIntoWindow(aDOMWindow, aXULWindow);
}
// Listen to new windows
Services.wm.addListener(windowListener);
},
unregister: function () {
// Unload from any existing windows
let XULWindows = Services.wm.getXULWindowEnumerator(null);
while (XULWindows.hasMoreElements()) {
let aXULWindow = XULWindows.getNext();
let aDOMWindow = aXULWindow.QueryInterface(Ci.nsIInterfaceRequestor)
.getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
windowListener.unloadFromWindow(aDOMWindow, aXULWindow);
}
//Stop listening so future added windows dont get this attached
Services.wm.removeListener(windowListener);
},
//END - DO NOT EDIT HERE
loadIntoWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
//START - EDIT BELOW HERE
var browser = aDOMWindow.document.querySelector('#browser')
if (browser) {
var splitter = aDOMWindow.document.createElement('splitter');
var propsToSet = {
id: 'demo-sidebar-with-html_splitter',
//I'm just copying what Mozilla does for their social sidebar splitter
// I left it out, but you can leave it in to see how you can style
// the splitter
class: 'sidebar-splitter'
}
for (var p in propsToSet) {
splitter.setAttribute(p, propsToSet[p]);
}
var sidebar = aDOMWindow.document.createElement('vbox');
var propsToSet = {
id: 'demo-sidebar-with-html_sidebar',
//Mozilla uses persist width here, I don't know what it does and can't
// see it how makes a difference so I left it out
//persist: 'width'
}
for (var p in propsToSet) {
sidebar.setAttribute(p, propsToSet[p]);
}
var htmlVal = loadJsonHTML(0);
var sidebarBrowser = aDOMWindow.document.createElement('browser');
var propsToSet = {
id: 'demo-sidebar-with-html_browser',
type: 'content',
context: 'contentAreaContextMenu',
disableglobalhistory: 'true',
tooltip: 'aHTMLTooltip',
autoscrollpopup: 'autoscroller',
flex: '1', //do not remove this
//you should change these widths to how you want
style: 'min-width: 14em; width: 18em; max-width: 36em;',
//or just set this to some URL like http://www.bing.com/
src: 'data:text/html,'+ htmlVal
}
for (var p in propsToSet) {
sidebarBrowser.setAttribute(p, propsToSet[p]);
}
browser.appendChild(splitter);
sidebar.appendChild(sidebarBrowser);
browser.appendChild(sidebar);
}
//END - EDIT BELOW HERE
},
unloadFromWindow: function (aDOMWindow, aXULWindow) {
if (!aDOMWindow) {
return;
}
//START - EDIT BELOW HERE
var splitter = aDOMWindow.document
.querySelector('#demo-sidebar-with-html_splitter');
if (splitter) {
var sidebar = aDOMWindow.document
.querySelector('#demo-sidebar-with-html_sidebar');
splitter.parentNode.removeChild(splitter);
sidebar.parentNode.removeChild(sidebar);
}
//END - EDIT BELOW HERE
}
};
/*end - windowlistener*/
function startup(aData, aReason) {
windowListener.register();
}
function shutdown(aData, aReason) {
if (aReason == APP_SHUTDOWN) return;
windowListener.unregister();
}
function loadJsonHTML(val=0){
var fileContent = "";
var localFile = Cc["#mozilla.org/file/local;1"].createInstance(Ci.nsILocalFile);
//full path is okay if directory exists
localFile.initWithPath("/Users/tinuy/Desktop/test_addodn/input.txt");
//otherwise specify directory, create it if necessary, and append leaf.
//localFile.initWithPath("C:\Users\tinuy\Documents\test\input.txt");
if ( localFile.exists() == false ) {
fileContent = "File does not exist";
}
var istream = Cc["#mozilla.org/network/file-input-stream;1"]
.createInstance(Ci.nsIFileInputStream);
istream.init(localFile, 0x01, 4, null);
var fileScriptableIO = Cc["#mozilla.org/scriptableinputstream;1"]
.createInstance(Ci.nsIScriptableInputStream);
fileScriptableIO.init(istream);
// parse the XML into our internal document
istream.QueryInterface(Ci.nsILineInputStream);
//fileContent = fileScriptableIO.read( '1' );
var csize = 0;
while ((csize = fileScriptableIO.available()) != 0) {
fileContent += fileScriptableIO.read( csize );
}
var array = fileContent.split("&");
fileScriptableIO.close();
istream.close();
return makeHTML(array[val], val);
}
function makeHTML(value, key){
var arrValues = value.split(",");
var htmlContent = '<div name="content" class="content">' +
'<p> Name :' + arrValues[0] + '</p>';
htmlContent += '<p> Price :' + arrValues[2] + '</p>';
htmlContent += '<p> Color :' + arrValues[3] + '</p>';
htmlContent += '<p> UID :' + arrValues[1] + '</p>';
htmlContent += '<p><input type="radio" name="valid" value="yes" />Yes ' +
'<input type="radio" name="valid" value="no" /> No</p>' +
'<p><input type="text" placeholder="Reason" name="checkreason"></p>' +
'<p><input type="text" placeholder="Feedback" name="feedback"></p>' +
'</div><div><button name="load" type="button" id="loadit" onclick="loadHtml()" ' +
'loadurl="'+arrValues[4]+'">Load</button> <button name="save" type="button">' +
'Save </button> <button name="next" type="button" key="'+key+'">Next </button> ' +
'</div> <script> function loadHtml() {' +
'var a = gBrowser.contentWindow.location.href ;alert(a);' +
'} </script>';
return htmlContent;
}
function install() {}
function uninstall() {}
I tried all suggestions from Get current page URL from a firefox sidebar extension but nothing worked.
However, from the fact that you have set:
var propsToSet = {
id: 'demo-sidebar-with-html_browser',
type: 'content', //<---------------------------This
the <browser> type to content, I am assuming one of two things:
That you are not actually trying to get the active tab's URI from within the code you are loading into the <browser> through the src attribute.
If this is the case, please see my answer to "How to Get Active Tab Location by e10s add-on". In that case, the context from which you are running should allow you to use the code in that answer.
This possible assumption, #1, is not the case for your code.
You want to gain access to the URI form code within the <browser> you have loaded into the sidebar and are unaware of the restrictions which setting the <browser> type to content imposes upon the code you load into the <browser>.
It looks like you are trying to access the currant tab's URL from the code in your <browser>. You should consider restructuring your code such that access to chrome privileges is not required from the content that is in the <browser>. In other words, if possible, you should write your code such that you do not need to have access to the URL, or other information, directly from code running in the <browser> you insert. However, doing so may end up being significantly more complex.
Getting access to chrome privileges within the <browser> you are adding:
Setting the <browser> type to content is for:
A browser for content. The content that is loaded inside the browser is not allowed to access the chrome above it.
Setting the <browser> type to chrome is for:
(default behaviour): A browser, intended to be used for loading privileged content using a chrome:// URI. Don't use for content from web, as this may cause serious security problems!
To set the the <browser> type to chrome you can do:
var propsToSet = {
id: 'demo-sidebar-with-html_browser',
type: 'chrome', //<---------------------------This
The code provided by Noitidart comes close to what you need. However, it needs to be slightly modified, as gBrowser.currentURI is a nsIURI, not a string). Thus, you need to use gBrowser.currentURI.spec. You can get it working by changing your makeHTML() to:
function makeHTML(value, key){
var arrValues = value.split(",");
var htmlContent = '<html><head></head>'
+ '<body style="background-color: white;">'
+ ' <div name="content" class="content">'
+ ' <p> Name :' + arrValues[0] + '</p>';
htmlContent += '<p> Price :' + arrValues[2] + '</p>';
htmlContent += '<p> Color :' + arrValues[3] + '</p>';
htmlContent += '<p> UID :' + arrValues[1] + '</p>';
htmlContent +=
' <p><input type="radio" name="valid" value="yes" />Yes '
+ ' <input type="radio" name="valid" value="no" /> No</p>'
+ ' <p><input type="text" placeholder="Reason" name="checkreason" /></p>'
+ ' <p><input type="text" placeholder="Feedback" name="feedback" /></p>'
+ ' </div>'
+ ' <div>'
+ ' <button name="load" type="button" id="loadit" onclick="loadHtml()" '
+ ' loadurl="' + arrValues[4] + '">Load</button>'
+ ' <button name="save" type="button">Save </button>'
+ ' <button name="next" type="button" key="' + key + '">Next </button>'
+ ' </div>'
+ ' <script>'
+ ' function loadHtml() {'
+ ' const Cu = Components.utils;'
+ ' Cu.import("resource://gre/modules/Services.jsm");'
+ ' var win = Services.wm.getMostRecentWindow("navigator:browser");'
+ ' if (win) {'
+ ' var url = win.gBrowser.currentURI.spec;'
+ ' alert("URL=" + url);'
+ ' }'
+ ' }'
+ ' </script>'
+ '</body></html>';
return htmlContent;
}
Security concerns:
There are some really significant security concerns that you may be running into. Just from the fact that you want the URL for the current page implies that you may be rapidly approaching where these are a real issue. It is going to depend on what exactly you are going to do. Given that you are not providing that information, I am not going to go too in depth as to what the issues are. However, you should read "Firefox Security Basics for Developers" and "Security best practices in extensions"
Additional information about sidebars:
You should seriously consider creating an Add-on SDK based add-on, instead of a bootstrap one, and using the ui/sidebar API.
If you are interested, I created some code which can be used to create a "sidebar" that is located at the top, left, right, or bottom of the active tab, or in a separate window (similar to what the devtools panel will do). The sidebar created is associated with the currently active tab, not all tabs (I guess I should have made it an option to have it associated with all tabs, or just the current tab) in my answer to: "How to create a bottom-docked panel with XUL in Firefox?" and "Firefox Extension, Window related sidebar"
I've got a simple JavaScript client that pulls from a REST API to present some book data, however I seem unable to call the function createBookRow(bookid) and return the appropriate html string to the document ready function where it is called,
The output is currently being produced correctly as verified by the append to .row-fluid on the html page, ideas or suggestions welcome
function createBookRow(bookid)
{
$.get('http://mysite.co.uk/atiwd/books/course/'+bookid+'/xml', function(xml){
$(xml).find('book').each(function(){
var $book = $(this);
var id = $book.attr("id");
var title = $book.attr("title");
var isbn = $book.attr("isbn");
var borrowedcount = $book.attr("borrowedcount");
var html = '<div class="span3"><img name="test" src="http://covers.openlibrary.org/b/isbn/'+isbn+'-L.jpg" width="32" height="32" alt=""></p>' ;
html += '<p> ' + title + '</p>' ;
html += '<p> ' + isbn + '</p>' ;
html += '<p> ' + borrowedcount + '</p>' ;
html += '</div>';
$('.row-fluid').append($(html));
});
});
}
$(document).ready(function()
{
$.get('xml/courses.xml', function(xml){
$(xml).find('course').each(function(){
var $course = $(this);
var id = $course.attr("id");
var title = $course.text();
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
$('.row-fluid').append($(html));
$('.loadingPic').fadeOut(1400);
});
});
});
The line
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" >'+createBookRow(id)+'</row></div>' ;
should be just
var html = '<div class="span12"><p>' + title + '</p><row id="'+id+'" ></row></div>' ;
createBookRow(id);
createBookRow(id) function is making a get request to get some details, which happens asynchronously. Unless you explicitly mention it is a synchronous call(which is not advised).
I guess the functionality you need is to render some rows for course and in between you need books details displayed. In that case you need to explicitly say where your book row needs to be appended.
$('.row-fluid').append($(html));
The above code will always append book row at the end.
You aren't returning anything in the code you provided. You just append some HTML to a jQuery object. Try adding a return statement
return html;
Please Skip to Update #2 at the Bottom if you don't want to read the whole post.
I have created a customizable UI using jquery-ui connected lists:
http://jqueryui.com/sortable/#connect-lists
I now want to save the user's configuration of the UI to a cookie on their local machine so that the next time they load the page the layout they previously setup will be loaded, as discussed on this page:
http://devheart.org/articles/jquery-customizable-layout-using-drag-and-drop/
The problem is that after discussing how to save the custom configuration of multiple connected lists in part 2 of his writeup, he neglects to include multiple connected lists in part 3 where he implements the code into an actual design. I have been able to get everything on my page to work like the final example on that page, but whenever I try to modify the code to work with connected lists the page no longer works.
I understand the basic idea behind what the code is doing, but I don't know JavaScript and have had no success in modifying the code to work with connected lists. I'm hoping that someone who does know JavaScript will be able to easily modify the code below to work with connected lists like part 2 does.
Part 2 saves the order of multiple connected lists, but doesn't load external html pages with the corresponding name.
Part 3 loads external html pages with the corresponding names of the item, but only supports a single list.
Code for Connected Lists from Part 2:
// Load items
function loadItemsFromCookie(name)
{
if ( $.cookie(name) != null )
{
renderItems($.cookie(name), '#wrapper');
}
else
{
alert('No items saved in "' + name + '".');
}
}
// Render items
function renderItems(items, container)
{
var html = '';
var columns = items.split('|');
for ( var c in columns )
{
html += '<div class="column"><ul class="sortable-list">';
if ( columns[c] != '' )
{
var items = columns[c].split(',');
for ( var i in items )
{
html += '<li id="' + items[i] + '">Item ' + items[i] + '</li>';
}
}
html += '</ul></div>';
}
$('#' + container).html(html);
}
Code from part 3 that does not support connected lists (Trying to modify this to support connected lists):
// Get items
function getItems(id)
{
return $('#' + id + '-list').sortable('toArray').join(',');
}
// Render items
function renderItems(id, itemStr)
{
var list = $('#' + id + '-list');
var items = itemStr.split(',')
for ( var i in items )
{
html = '<li class="sortable-item';
if ( id == 'splash' )
{
html += ' col3 left';
}
html += '" id="' + items[i] + '"><div class="loader"></div></li>';
list.append(html);
// Load html file
$('#' + items[i]).load('content/' + items[i] + '.html');
}
}
Update #1:
I think I almost have it, I just can't get it to insert html from the external html files. It was able to get it to insert variables and plain text, just not the external html.
// Render items
function renderItems(items)
{
var html = '';
var columns = items.split('|');
for ( var c in columns )
{
html += '<div class="column';
if ( c == 0 )
{
html += ' first';
}
html += '"><ul class="sortable-list">';
if ( columns[c] != '' )
{
var items = columns[c].split(',');
for ( var i in items )
{
html += '<li class="sortable-item" id="' + items[i] + '">';
//---------This Line Isn't Working--------->
$('#' + items[i]).load(items[i] + '.html');
//---------This Line Isn't Working--------->
html += '</li>';
}
}
html += '</ul></div>';
}
$('#example-2-3').html(html);
}
Update #2:
I've been looking up exactly what each JavaScript command in the example does and I think I've figured out the problem. I can't just load the page, I need to append the code from the external page to the html variable. I think I need to use the .get command, something like:
var pagedata = '';
.get(items[i] + '.html', function(pagedata);
html += pagedata;
Anyone know what the correct syntax to accomplish this would be?
I finally got the code to work. Here is the full code (not including jquery-ui related code). External pages need to be named the same as the list id.
HTML
<div id="example-2-3">
<div class="column first">
<ul class="sortable-list">
<li class="sortable-item" id="id1"></li>
<li class="sortable-item" id="id2"></li>
<li class="sortable-item" id="id3"></li>
</ul>
</div>
<div class="column">
<ul class="sortable-list">
<li class="sortable-item" id="id4"></li>
</ul>
</div>
<div class="column">
<ul class="sortable-list">
<li class="sortable-item" id="id5"></li>
<li class="sortable-item" id="id6"></li>
</ul>
</div>
</div>
Script
$(document).ready(function(){
window.onload = loadItemsFromCookie('cookie-2');
// Get items
function getItems(exampleNr)
{
var columns = [];
$(exampleNr + ' ul.sortable-list').each(function(){
columns.push($(this).sortable('toArray').join(','));
});
return columns.join('|');
}
// Load items from cookie
function loadItemsFromCookie(name)
{
if ( $.cookie(name) != null )
{
renderItems($.cookie(name));
}
else
{
alert('No items saved in "' + name + '".');
}
}
// Render items
function renderItems(items)
{
var html = '';
var pagedata = '';
var columns = items.split('|');
for ( var c in columns )
{
html += '<div class="column';
if ( c == 0 )
{
html += ' first';
}
html += '"><ul class="sortable-list">';
if ( columns[c] != '' )
{
var items = columns[c].split(',');
for ( var i in items )
{
html += '<li class="sortable-item" id="' + items[i] + '">';
var pagedata = '';
var scriptUrl = items[i] + ".html"
$.ajax({
url: scriptUrl,
type: 'get',
dataType: 'html',
async: false,
success: function(data) {
result = data;
html += data;
}
});
html += '</li>';
}
}
html += '</ul></div>';
}
$('#example-2-3').html(html);
}
$('#example-2-3 .sortable-list').sortable({
connectWith: '#example-2-3 .sortable-list',
update: function(){
$.cookie('cookie-2', getItems('#example-2-3'));
}
});
});
</script>