Browser shows < and > instead of <> - javascript

I'm creating a very simple HTML page using the Typewriter JavaScript plugin.
The page essentially should type out the code of an elementary Java program in which each declared variable is one of my contact details.
The problem is that if I write <span class="standard-highlight">List<String> list = Arrays</span>, the browser doesn't display List<String> list = but instead displays List<String> list =.
How can I fix this?
Here is a snippet from the output in the browser (Chrome)
JavaScript below:
function setupTypewriter(t) {
var HTML = t.innerHTML;
t.innerHTML = "";
var cursorPosition = 0,
tag = "",
writingTag = false,
tagOpen = false,
typeSpeed = 10,
tempTypeSpeed = 0;
var type = function() {
if (writingTag === true) {
tag += HTML[cursorPosition];
}
if (HTML[cursorPosition] === "<") {
tempTypeSpeed = 0;
if (tagOpen) {
tagOpen = false;
writingTag = true;
} else {
tag = "";
tagOpen = true;
writingTag = true;
tag += HTML[cursorPosition];
}
}
if (!writingTag && tagOpen) {
tag.innerHTML += HTML[cursorPosition];
}
if (!writingTag && !tagOpen) {
if (HTML[cursorPosition] === " ") {
tempTypeSpeed = 0;
}
else {
tempTypeSpeed = (Math.random() * typeSpeed) + 30;
}
t.innerHTML += HTML[cursorPosition];
}
if (writingTag === true && HTML[cursorPosition] === ">") {
tempTypeSpeed = (Math.random() * typeSpeed) + 30;
writingTag = false;
if (tagOpen) {
var newSpan = document.createElement("span");
t.appendChild(newSpan);
newSpan.innerHTML = tag;
tag = newSpan.firstChild;
}
}
cursorPosition += 1;
if (cursorPosition < HTML.length - 1) {
setTimeout(type, tempTypeSpeed);
}
};
return {
type: type
};
}
var typer = document.getElementById('typewriter');
typewriter = setupTypewriter(typewriter);
typewriter.type();

The below code works fine for me.
<span class="standard-highight" id="app"></span>
<script>
var app = document.getElementById('app');
var typewriter = new Typewriter(app, {
loop: true
});
typewriter.typeString('<span>List<String> list = Arrays</span>').start();
</script>
Place the string passing to the typeString() function within any html tag and only then the HTML symbols will be rendered by the function.

Related

Print JS Variable in HTML

I would like to output a JS variable to HTML. Until now I have attached it to the URL and then truncated it. unfortunately other things like this don't work and I would like to pass the Label variable directly into 'Tablet_name'. Is this possible?
Here is the JS code with the var label.
function search_period(period, max_num, offset) {
var count = 0;
var link = ""
var div = document.createElement('div')
var h2 = document.createElement('h2')
var iiif = ""
h2.innerHTML = period
document.body.appendChild(h2)
const keys = Object.keys(urls);
for(const elem of keys) {
var label = urls[elem].label
for(const el of urls[elem].variants) {
if(el.label.includes('front')) {
iiif = el.url
}
}
if(!periods.hasOwnProperty(label)) {
continue;
}
if(periods[label] != period) {
continue;
}
if(count < offset) {
count+=1
continue
}
link = changeIIIFInformation(iiif, 10, "default")
var figure = document.createElement('figure')
var figcaption = document.createElement('figcaption')
var linkToImage = document.createElement('a')
//linkToImage.setAttribute('#image', label)
linkToImage.setAttribute('href', 'annotator#'+label)
linkToImage.innerHTML = label
figcaption.appendChild(linkToImage)
var image = document.createElement('img')
image.setAttribute('src', link)
figure.appendChild(image)
figure.appendChild(figcaption)
div.appendChild(figure)
count += 1;
if(count >= max_num+offset) {
break;
}
}
document.body.appendChild(div)
}
And here is the HTML Code:
var tablet_name = ""
var default_tablet_link = ""
if(document.URL.includes('#')) {
tablet_name = document.URL.split('#')[1]
} else {
tablet_name = 'HS_0044'
}
I want the for the tablename the variable label.

How to make a restriction on the addition of tags in the input?

there is a fully working code. its task is to add tags (text) separated by commas in the input field remembering the choice (the added tag changes color).
everything would be fine, but with this functionality, users can add an unlimited number of tags. how to prevent users from adding more than 4-5 tags? and if you exceed the limit tag will be replaced by another tag?
html code:
<ul id="aTags">
HTML;
for ($i=0;$d[$i];$i++) {
$html .= '<li class="atags-b" onClick="aTags.toggle(this);">'.$d[$i].'</li>';
}
$html .= <<<HTML
</ul>
javascript code:
aTags = {
inputObj : document.getElementById("tags"),
tagsColl : document.getElementById("aTags").getElementsByTagName("li"),
array_value : function (arr) {
var c = 0;
var tmpArr = new Array ();
for (key in arr) {
tmpArr[c] = arr[key];
++c;
}
return tmpArr;
},
toggle : function (e) {
var iArr = this.inputObj.value.split(',');
var in_arr = false;
for (var i in iArr) {
iArr[i] = iArr[i].replace(/^[\s\xa0]+|[\s\xa0]+$/g, "");
}
for (var i=0;i<iArr.length;i++) {
if (iArr[i] == e.innerHTML) {
in_arr = true;
delete iArr[i];
break;
}
else if (iArr[i] == '')
delete iArr[i];
}
if (in_arr === false) {
iArr.push(e.innerHTML);
}
iArr = this.array_value(iArr);
this.highlight(iArr);
this.inputObj.value = iArr.join(', ');
},
highlight : function (tags) {
for (var i=0;i < this.tagsColl.length;i++) {
this.tagsColl[i].className = 'atags-b';
for (var ii=0;ii<tags.length;ii++) {
//alert (this.tagsColl[i].innerHTML + ' <> ' + tags[ii]);
if (this.tagsColl[i].innerHTML == tags[ii]) {
this.tagsColl[i].className = 'atags-c';
break;
}
}
}
},
iHighlight : function () {
var iArr = this.inputObj.value.split(',');
var in_arr = false;
for (var i in iArr) {
iArr[i] = iArr[i].replace(/^[\s\xa0]+|[\s\xa0]+$/g, "");
}
this.highlight (iArr);
}
}
click count:
let num = 0, button = document.querySelector('[class=atags-b]');
button.onclick = function () {
num++, num > 4 ? this.disabled = true : '';
};
Thanks!!
-Aison
Just before iArr = this.array_value(iArr), I would limit the array to 4 elements:
iArr = iArr.slice(0, 4);

HtmlOptions.OnLoadScript doesnt works to create PDF with ABCPdf

I have a html page created with bootstrap, and i want to create a PDF with it and for this i'm using ABCPdf.
I'm trying to execute a javascript script to apply some styles to my html, but it doesn't works. Someone knows what happens?
Doc theDoc = new Doc();
theDoc.Rect.Inset(5, 20);
theDoc.HtmlOptions.Timeout = 3000000;
theDoc.HtmlOptions.UseScript = true;
theDoc.HtmlOptions.PageCacheEnabled = false;
theDoc.HtmlOptions.DoMarkup = true;
theDoc.HtmlOptions.HostWebBrowser = false;
theDoc.HtmlOptions.Media = MediaType.Screen;
theDoc.HtmlOptions.BrowserWidth = 1500;
theDoc.HtmlOptions.AddLinks = true;
string script = #"var elemento = document.getElementById('description');"
+"for (i = 0; i < elemento.childNodes.length; i++) {"
+ "if (elemento.childNodes[i].className == 'row') {"
+ " if (elemento.childNodes[i].offsetHeight > 200) {"
+ "elemento.childNodes[i].className += ' saltoPagina'; } } }";
theDoc.HtmlOptions.OnLoadScript = script;
int theID;
theID = theDoc.AddImageUrl(url, true, 0, true);
Thanks in advance. :)
Solve: If you are using ABCPdf, you cant execute javaScript (jQuery never works) without the next line:
theDoc.HtmlOptions.Engine = EngineType.Gecko;
And then executes your code:
theDoc.HtmlOptions.GeckoSubset.OnLoadScript =
#"(function() {
window.ABCpdf_go = false;
var elemento = document.getElementById('description');
var elementos = elemento.childNodes;
var contador = 0;
for (i = 0; i < elementos.length; i++) {
if(elementos[i].className == 'info'){
contador = contador + elementos[i].offsetHeight;
if(contador > 1600) {
contador = elementos[i].offsetHeight;
var childElements = elementos[i].childNodes;
for(j = 0; j < childElements.length; j++) {
if (childElements[j].className == 'infoDescrip' && i != 1){
childElements[j].className += ' saltoPagina';
}
}
}
}
}
window.ABCpdf_go = true;
})();";
But if you use EngineType.Gecko, bootstrap librarie doesn't works.

Google CSE Branding on IE Re-appearing on custom search Box

I have chose to CSE Result Only look and feel in order to implement my box.
I did the branding of Google CS by attaching functions to onblur and onfocus. I found the code on a Demo by Google.
Everything works fine, but here is an annoying scheme on IE:
A user types in the box and searches
A user clicks on link that open in the current window
If he clicks back, the box shows the query and the box's background.
On different browsers the query is removed.
My problem is how to either clear the box or remove the background.
IE is not running my codes (which works in my branding code) after the user clicks back.
Here is the Code I used to bind events.
(function() {
var f = document.getElementById('cse-search-box-form-id');
if (f && f['cse-search-input-box-id']) {
var q = f['cse-search-input-box-id'];
var n = navigator;
var l = location;
var du = function(n, v) {
var u = document.createElement('input');
u.name = n;
u.value = v;
u.type = 'hidden';
f.appendChild(u);
return u;
};
var su = function(n, t, v, l) {
if (!encodeURIComponent || !decodeURIComponent) {
return;
}
var regexp = new RegExp('(?:[?&]' + n + '=)([^&#]*)');
var existing = regexp.exec(t);
if (existing) {
v = decodeURIComponent(existing[1]);
}
var delimIndex = v.indexOf('://');
if (delimIndex >= 0) {
v = v.substring(delimIndex + '://'.length, v.length);
}
var v_sub = v.substring(0, l);
while (encodeURIComponent(v_sub).length > l) {
v_sub = v_sub.substring(0, v_sub.length - 1);
}
du(n, v_sub);
};
var pl = function(he) {
var ti = 0,
tsi = 0,
tk = 0,
pt;
return function() {
var ct = (new Date).getTime();
if (pt) {
var i = ct - pt;
ti += i;
tsi += i * i;
}
tk++;
pt = ct;
he.value = [ti, tsi, tk].join('j');
};
};
var append = false;
if (n.appName == 'Microsoft Internet Explorer') {
var s = f.parentNode.childNodes;
for (var i = 0; i < s.length; i++) {
if (s[i].nodeName == 'SCRIPT' &&
s[i].attributes['src'] &&
s[i].attributes['src'].nodeValue == unescape('http:\x2F\x2Fwww.google.com\x2Fcse\x2Fbrand?form=cse-search-box-form-id\x26inputbox=cse-search-input-box-id')) {
append = true;
break;
}
}
} else {
append = true;
}
if (append) {
var loc = document.location.toString();
var ref = document.referrer;
su('siteurl', loc, loc, 250);
su('ref', loc, ref, 750);
if (q.addEventListener) {
q.addEventListener('keyup', pl(du('ss', '')), false);
} else if (q.attachEvent) {
q.attachEvent('onkeyup', pl(du('ss', '')));
}
}
if (n.platform == 'Win32') {
q.style.cssText = 'border: 0px ';
}
if (window.history.navigationMode) {
window.history.navigationMode = 'compatible';
}
var b = function() {
if (q.value == '') {
q.style.background = '#fff url(http:\x2F\x2Fwww.google.com\x2Fcse\x2Fintl\x2Fen\x2Fimages\x2Fgoogle_custom_search_watermark.gif) 3.5% 80% no-repeat';
}
};
var f = function() {
q.style.background = '#fff';
};
q.onfocus = f;
q.onblur = b;
if (!/[&?]q=[^&]/.test(l.search)) {
b();
}
}
})();
<div class="search-bar-outer">
<form onsubmit="return executeQuery();" id="cse-search-box-form-id">
<div class="search-box-outer">
<input type="text" id="cse-search-input-box-id" size="25" autocomplete="off" style="border: 0px;" class="search-input">
</div>
<div class="search-button-outer">
<button type="submit" class="search-button"></button>
</div>
</form>
<script type="text/javascript" src="js/branding.js"></script>
</div>

changing element ID to data-code?

instead of using the ID element, data-code. Do I just change everything that is .getElementById to getElementByData-code ?
// form validation function //
function validate(form) {
var s_name = form.s_name.value;
var s_email = form.s_email.value;
var s_drop = form.s_drop.value;
// var s_promo = form.s_promo.value;
var nameRegex = /^[A-Za-z\d_]+$/;
var emailRegex = /^[\w-\.]+#([\w-]+\.)+[\w-]{2,4}$/;
var msgRegex = new RegExp(/<\/?\w+((\s+\w+(\s*=\s*(?:".*?"|'.*?'|[^'">\s]+))?)+\s*|\s*)\/?>/gim);
if(s_name == "") {
inlineMsg('s_name','You must enter your name.',2);
return false;
}
if(!s_name.match(nameRegex)) {
inlineMsg('s_txt','You have entered an invalid name.',2);
return false;
}
if(s_email == "") {
inlineMsg('s_email','<strong>Error</strong><br />You must enter your email.',2);
return false;
}
if(!s_email.match(emailRegex)) {
inlineMsg('s_email','<strong>Error</strong><br />You have entered an invalid email.',2);
return false;
}
if(s_drop == "") {
inlineMsg('s_drop','<strong>Error</strong><br />You must select your gender.',2);
return false;
}
/*
if(s_promo == "") {
inlineMsg('s_promo','You must enter a message.');
return false;
}
*/
if(s_promo.match(msgRegex)) {
inlineMsg('s_promo','You have entered an invalid message.',2);
return false;
}
return true;
}
// START OF MESSAGE SCRIPT //
var MSGTIMER = 20;
var MSGSPEED = 5;
var MSGOFFSET = 3;
var MSGHIDE = 3;
// build out the divs, set attributes and call the fade function //
function inlineMsg(target,string,autohide) {
var msg;
var msgcontent;
if(!document.getElementById('msg')) {
msg = document.createElement('div');
msg.id = 'msg';
msgcontent = document.createElement('div');
msgcontent.id = 'msgcontent';
document.body.appendChild(msg);
msg.appendChild(msgcontent);
msg.style.filter = 'alpha(opacity=0)';
msg.style.opacity = 0;
msg.alpha = 0;
} else {
msg = document.getElementById('msg');
msgcontent = document.getElementById('msgcontent');
}
msgcontent.innerHTML = string;
msg.style.display = 'block';
var msgheight = msg.offsetHeight;
var targetdiv = document.getElementById(target);
targetdiv.focus();
var targetheight = targetdiv.offsetHeight;
var targetwidth = targetdiv.offsetWidth;
var topposition = topPosition(targetdiv) - ((msgheight - targetheight) / 2);
var leftposition = leftPosition(targetdiv) + targetwidth + MSGOFFSET;
msg.style.top = topposition + 'px';
msg.style.left = leftposition + 'px';
clearInterval(msg.timer);
msg.timer = setInterval("fadeMsg(1)", MSGTIMER);
if(!autohide) {
autohide = MSGHIDE;
}
window.setTimeout("hideMsg()", (autohide * 1000));
}
// hide the form alert //
function hideMsg(msg) {
var msg = document.getElementById('msg');
if(!msg.timer) {
msg.timer = setInterval("fadeMsg(0)", MSGTIMER);
}
}
// face the message box //
function fadeMsg(flag) {
if(flag == null) {
flag = 1;
}
var msg = document.getElementById('msg');
var value;
if(flag == 1) {
value = msg.alpha + MSGSPEED;
} else {
value = msg.alpha - MSGSPEED;
}
msg.alpha = value;
msg.style.opacity = (value / 100);
msg.style.filter = 'alpha(opacity=' + value + ')';
if(value >= 99) {
clearInterval(msg.timer);
msg.timer = null;
} else if(value <= 1) {
msg.style.display = "none";
clearInterval(msg.timer);
}
}
Since you are using jQuery, you can use the Sizzle Selection Engine (packaged with jQuery) to select the elements you want by attribute:
//this will select all elements with the `data-code` attribute with a value of `whatever`
var data_codes = $('[data-code="whatever"]');
You can also just select all elements with a certain attribute regardless of the value of that attribute:
var data_codes = $('[data-code]');
Here's a list of selector types that jQuery has (at the top of the list are the attribute selectors): http://api.jquery.com/category/selectors/
Note that document.getElementById('SOME_ID') is the same as $('#some_id')[0]. I added the [0] to the end of the jQuery selection to return just the DOM node. You are using other functions that jQuery makes easier as well. .innerHTML = 'some string'; is the same as .html('some string');, .style.display = 'block' is the same as .show() or .css({display: 'block'}).

Categories

Resources