How to insert HTML ASCII art from document? - javascript

At the moment i'm trying to read .txt files which could contain ASCII arts and display them in my HTML document with JQuery. Simple text is displayed right but i have formatting problems with the arts.
How can i fix this ?
$(document).ready(function(e) {
$.get('/test/posts/header.txt', function(data) {
var lines = data.split('\n');
for (var i = 0, len = lines.length; i < len; i++) {
$(".stream").append('<div class="line"><p class="header">' + lines[i] + '</p></div>');
}
});
});

This is because the excess spaces are getting stripped. Either you replace all the spaces with &nbsp in every line with simple ... + lines[i].replace(/ /g,'&nbsp') + ..., or you wrap everything in <pre>...</pre>:
'<div class="line"><p class="header"><pre>' + lines[i] + '</pre></p></div>'

HTML
<pre id="asciiart"></pre>
I see you are using jquery:
$("#asciiart" ).load( "/test/posts/header.txt" );
You can also use css
.line{
white-space: nowrap;
}
or in your case
<div class="line"><p class="header"></div></div>
.line>.header
I think that's right.
Good Luck

Related

try to show html tags as text with innerHTML

I have a string that contains HTML tags.
I want to render as an HTML element only the span tags aka <span></span>.
every other tag that is not a span tag should be treated as regular text.
The result I'm trying to achieve is to color any text that I want even if it contains HTML tags.
I fail.
is there any other technique that I can try or a workaround?
var problem = ["<h1>","</h1>"];
var red_text = "<span style='color:red'>i am red </span>";
var green_text = "<span style='color:green'>" +
problem[0] +
"i am green" +
problem[1] +
"</span>";
//the real result should have <h1> </h1>
var expected_text = red_text + "<span style='color:green'>|h1|i am green|/h1|</span>";
document.getElementById("demo").innerHTML = red_text + green_text;
document.getElementById("expected").innerHTML = expected_text;
HTML and JavaScript code at :
https://jsfiddle.net/ytLftxww/1/
You need to use HTML entities to escape the < and > in those tags.
For example: "<span style='color:green'><h1>i am green</h1></span>"
See the fiddle: https://jsfiddle.net/ytLftxww/1/
var problem = ["<h1>","<h1>"];
does unescaping the < > work for you?
updated fiddle
You can use &lt for < and & &gt for >.

Random quotation mark being inserted into generated onclick html parameter

I'm trying to add parameters to an onclick function when generating HTML via javascript. When I inspect the code it is putting a quotation mark in the onclick function's parameter.
var lengthOfCats = ArrayOfCategories.length;
for (var a = 0; a < lengthOfCats; a++) {
$("#CatTable").append("<div class='better-table-cell'>" + ArrayOfCategories[a].Name + "</div>\
<div class='better-table-cell'>" + ArrayOfCategories[a].DepartmentName + "</div>\
<div class='better-table-cell'>" + ArrayOfCategories[a].Active + "</div>\
<div class='better-table-cell'>\
<button onclick=OpenUpdateCat(" + ArrayOfCategories[a].CategoryID + "," + ArrayOfCategories[a].Name + ");" + ">Edit</button>\
</div>");
Here is an image of the HTML that is getting generated for the edit button.
The browser is normalising the HTML and putting quote marks around the attribute value.
The problem is that because the attribute value includes spaces, and you didn't put the quote marks in the right spots yourself, the attribute value finishes in the middle of the JavaScript.
The next bit of JS is then treated as a new attribute.
Mashing together strings to generate HTML is fundamentally a bad idea. Ensuring all the right things are quoted and escaped is hard.
Use DOM to generate your HTML instead.
It is a little longer, but clearer and easier to maintain in the long run.
var $cat_table = $("#CatTable");
var lengthOfCats = ArrayOfCategories.length;
for (var a = 0; a < lengthOfCats; a++) {
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].Name)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].DepartmentName)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").text(ArrayOfCategories[a].Active)
);
$cat_table.append(
$("<div />").addClass("better-table-cell").append(
$("<button />").text("Edit").on("click", generate_edit_handler(ArrayOfCategories[a].CategoryID, ArrayOfCategories[a].Name))
)
);
}
function generate_edit_handler(cat_id, name) {
return function () {
OpenUpdateCat(cat_id, name);
};
}

Assigning dynamic ids to elements using jQuery

Hi I am using jQuery and creating tags in a loop.
Ex -
for(var i=0;i<length;i++){
jQuery("#dailydata").append("<table class='table'><tr>"+
"<th>Min Temp : </th><td>"+ data[i]</td>" +
"</tr></table>";
if(data[i] <=10){
//add color to th
}else{
//add different color to th
}
}
I am creating a Table Row in every loop and appending to a HTML element. and just after that I am checking the value and according to that value I want to change the background color of the tag.
Can somebody tell me how to achieve this?
There are several methods.
The method you're using to build the tags isn't the most elegant, but you could adapt it to achieve the result you're after as follows...
jQuery("#dailydata").append("<table class='table'><tr>"+
"<th id='"+ (data[i]<=10?'blue':'red') + "'>Min Temp : </th><td>"+ data[i]</td>" +
"</tr></table>";
I suggest you also read the jQuery docs on how to use 'attr' and 'prop' to add id's (and other attributes/properties) to jQuery elements without hacking the text together as in my example.
jQuery 'attr': https://api.jquery.com/attr/
jQuery 'prop': https://api.jquery.com/prop/
The simplest way basing on your code:
for (var i = 0; i < length; i++) {
var color;
if(data[i] <=10) {
color = "ff0000";
} else{
color = "0000ff";
}
jQuery("#dailydata").append(
"<table class='table'><tr>" +
"<th style="background-color:#" + color +
">Min Temp : </th><td>" + data[i]</td>" +
"</tr></table>");
}
Firstly:
You should not use numeric values (0,1,2,3,etc) for ids. The HTML specification say this:
ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").
Secondly:
Your code is weight... Did you create a variable called "length" in lines not shown in your example? I assume in your for loop you meant i<data.length
So with that in mind use an alphabetical prefix to your ids:
// Note jQuery("#dailydata") same as $("#dailydata") unless you override the use of the "$" symbol
for(var i=0; i<data.length; i++) {
var newElementId = "some_prefix_"+i;
var newElementToAppend = $("<div>").attr("id", newElementId);
$("#dailydata").append(newElementToAppend);
}
You can just add an extra if condition to check the value of i
Here in this example , assume length is value greater than i. Also in your example you are using data[i] but the loop will run on length variable.There is a typo here data[i]</td>" It need to be data[i]+"</td>". Also the append method be closed with )
var length = 15;
for (var i = 0; i < length; i++) {
if (i < 10) {
jQuery("#dailydata").append("<table class='table'><tr>" +
"<th class='less10'>Min Temp : </th><td>" + i + "</td>" +
"</tr></table>");
} else {
jQuery("#dailydata").append("<table class='table'><tr>" +
"<th class='more10'>Min Temp : </th><td>" + i + "</td>" +
"</tr></table>");
}
}
.less10 {
color: green
}
.more10 {
color: blue
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="dailydata">
</div>

Dynamically add array contents as new elements - JQuery

edit: Problem solved! I was modifying the page before it was loaded so the script didn't actually do anything. I fixed it now and it works. Thanks for the help, I'll have to chalk this one up to being new to jQuery and it's weirdness.
Long story short I'm trying to make a webpage that dynamically takes Article titles, thumbnail images, descriptions, and links to them, and creates a nicely formatted list on the page. I'm trying to accomplish this in jQuery and HTML5.
Here is the sample data that I'll be using to dynamically populate the page. For now formatting isn't important as I can do that later after it works at all.
<script>
var newsTitles = ["If It Ain't Broke, Fix It Anyways"];
var newsPics = ["images/thumbnail_small.png"];
var newsDescs = ["August 14th 2015<br/><b>If It Ain't Broke</b><br/>Author: Gill Yurick<br/><br/> Sometimes, a solution isn't the only one. So how do we justify changes to systems that don't need to be fixed or changed? I explore various systems from other successful card games and how their approaches to issues (be they successes or failures in the eyes of the deisgners) can help us create EC."];
var newsLinks = ["it_aint_broke-gill_popson.html"];
var newsIndex = 0;
var newsMax = 1;
The section of code where I'm trying to use the contents of the arrays above to dynamically fill elements.
<td style="height:500px;width:480px;background-color:#FFF7D7;padding:20px" colspan=2 id="article">
<h1>Articles</h1>
<!-- the column for each news peice add an element with the thumbnail, the title and teh desc -->
<script>
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href="" newsLinks[i] + "">" + newsTitles[i] + "</h3>", "<img src=""newsPics[i] + "">","<p>" + newsDesc[i] + "</p>", ); $("div").append("hello");
}
</script>
<div id="articleList">
HELLO
</div>
</td>
Here is what it ends up looking like, I can post more info if needed as I am aware this may not be clear enough to fully explain my problem but I am unable to determine that. Thank you in advance.
try this
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href=""+ newsLinks[i] + "">" + newsTitles[i] + "</h3>, <img src=""+newsPics[i] + "">, <p>" + newsDescs[i] + "</p>" ); $("div").append("hello");
}
Concatation issue + typo for newsDescs
The following string is invalid html and is missing a +
"<h3 href="" newsLinks[i] + "">"
You need to use proper quotes for html attributes, not &quote;
Try
"<h3 href='" + newsLinks[i] + "'>"
OR
"<h3 href=\"" + newsLinks[i] + "\">" // `\` used to escape same type quote
Personally I prefer opening/closing html strings with single quotes but either will work
Note tht you should be getting a syntax error thrown in dev tools console which would have helped you locate problems
for(i = 0; i < newsMax; i++) {
$("#articleList").append("<h3 href='" + newsLinks[i] + "'>" + newsTitles[i] + "</h3>");
$("#articleList").append("<img src='" + newsPics[i] + "'>","<p>" + newsDesc[i] + "</p>" );
}

Simple Javascript For Loop in Meteor

I'm assuming I putting this in the wrong area or making some other flaw due to my lack of understand as I'm still learning Meteor.
I have a Meteor application working with data, etc. and all is well on that front. I have a number of logos created for this application that I want to share with some others to get feedback on which they prefer.
All the logo files are named logo1.png, logo2.png, logo3.png, etc. It's the perfect time for a quick and easy for loop (because I know how many files I have) that just concatenates the loop variable onto the word logo and then the .png.
So on my local computer I throw up an HTML file with the following that works exactly how I need it to.
<script type="text/JavaScript">
for (i = 1; i < 7; i++) {
logoName = '';
logoName += "logo" + i + ".png"
document.write ("<img src=" + logoName + " height=200px>");
}
</script>
Then I put into my Meteor main.html file:
<body>
{{> header}}
<script type="text/JavaScript">
for (i = 1; i < 7; i++) {
logoName = '';
logoName += "logo" + i + ".png"
document.write ("<img src=" + logoName + " height=200px>");
}
</script>
<div class="text-center">
{{> invList}}
</div>
</body>
The problem is my Meteor application is catching that "<" in the "i < 7" statement and expects there to be a tag.
So I get the following error:
While building the application: client/main.html:10: Expected tag name
after < ..."> for (i = 1; i < 7; i++) {
...
I'm probably missing something here about where code needs to be placed or something but I've gone through Meteor docs, DiscoverMeteor, and done some Googling in addition to checking this site and I just haven't found how to make Meteor ignore this bit of javascript so it doesn't catch that less than sign and expect anything.
Should I just put this code in /public somehow? If so I'm not sure how I would call it from main.html so it places the images where I want them.
As you already know, you shouldn't write to HTML like that. Instead, put your loop in a helper.
HTML:
<body>
{{> images}}
</body>
<template name="images">
{{#each logos}}
<img src="{{url}}" class="logo"/>
{{/each}}
</template>
JS:
Template.images.logos = function() {
return _.map(_.range(1, 7), function(idx) {
return {url: 'logo' + idx + '.png'};
});
};
CSS:
.logo {
height: 200px;
}
I don't think that it's a good idea to embed a script in the html when you are using Meteor. If you still want to do so, remember to escape some symbols. To correct your script, use following instead:
<script type="text/JavaScript">
for (i = 1; i < 7; i++) {
logoName = '';
logoName += "logo" + i + ".png"
document.write ("<img src=" + logoName + " height=200px>");
}
</script>

Categories