This is the code i got from codepen, it generates special characters and changes to the phrase i put, I'm wanting to compile this vanilla javascript code to react, because you can't use the DOM
there.
My real doubt is where do I put the useState so that it stops looping and shows character by character, this passing for example the state 'title' in a .
vanilla javascript code:
function setCharAt(str,index,chr) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!##$%^&*~`\|'.split('');
var progress404 = 0;
var total404 = $('.text__error').data('text').length;
var progressLink = 0;
var totalLink = $('.text__link a').data('text').length;
var scrambleInterval = setInterval(function() {
var string404 = $('.text__error').data('text');
var stringLink = $('.text__link a').data('text');
for(var i = 0; i < total404; i++) {
if(i >= progress404) {
string404 = setCharAt(string404, i, characters[Math.round(Math.random() * (characters.length - 1))]);
}
}
for(var i = 0; i < totalLink; i++) {
if(i >= progressLink) {
stringLink = setCharAt(stringLink, i, characters[Math.round(Math.random() * (characters.length - 1))]);
}
}
$('.text__error').text(string404);
$('.text__link a').text(stringLink);
}, 1000 / 60);
setTimeout(function() {
var revealInterval = setInterval(function() {
if(progress404 < total404) {
progress404++;
}else if(progressLink < totalLink) {
progressLink++;
}else{
clearInterval(revealInterval);
clearInterval(scrambleInterval);
}
}, 50);
}, 1000);
This is the code I developed to try to work:
const [ title, setTitle ] = useState('404 page not found')
const [ link, setLink ] = useState('click here to go home')
function setCharAt(str: string,index: number,chr: any) {
if(index > str.length-1) return str;
return str.substr(0,index) + chr + str.substr(index+1);
}
var characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890-=+<>,./?[{()}]!##$%^&*~`\|'.split('');
var progress404 = 0;
var total404 = title.length
var progressLink = 0;
var totalLink = link.length
var scrambleInterval = setInterval(function() {
for(var i = 0; i < total404; i++) {
if(i >= progress404) {
setTitle( setCharAt(title, i, characters[Math.round(Math.random() * (characters.length - 1))]));
}
}
for(var i = 0; i < totalLink; i++) {
if(i >= progressLink) {
setLink( setCharAt(link, i, characters[Math.round(Math.random() * (characters.length - 1))]));
}
}
}, 1000 / 60);
setTimeout(function() {
var revealInterval = setInterval(function() {
if(progress404 < total404) {
progress404++;
}else if(progressLink < totalLink) {
progressLink++;
}else{
clearInterval(revealInterval);
clearInterval(scrambleInterval);
}
}, 50);
}, 1000);
I have the following code that is using 3 columns to check for difference in input values.
The third column difference in my view is generated fine but while viewing it the table is not displaying it.
What is want to do is to compare base text with new text and thrid text input enteries and display the changes to user in inline or side by side format
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
<title>jsdifflib demo</title>
<link rel="stylesheet" type="text/css" href="diffview.css"/>
<script type="text/javascript" src="diffview.js"></script>
<script type="text/javascript" src="difflib.js"></script>
<style type="text/css">
body {
font-size: 12px;
font-family: Sans-Serif,serif;
}
h2 {
margin: 0.5em 0 0.1em;
text-align: center;
}
.top {
text-align: center;
}
.textInput {
display: block;
width: 49%;
float: left;
}
textarea {
width:100%;
height:300px;
}
label:hover {
text-decoration: underline;
cursor: pointer;
}
.spacer {
margin-left: 10px;
}
.viewType {
font-size: 16px;
clear: both;
text-align: center;
padding: 1em;
}
#diffoutput {
width: 100%;
}
</style>
<script type="text/javascript">
function diffUsingJS(viewType) {
"use strict";
var byId = function (id) { return document.getElementById(id); },
base = difflib.stringAsLines(byId("baseText").value),
newtxt = difflib.stringAsLines(byId("newText").value),
thirdText = difflib.stringAsLines(byId("3rdText").value),
sm = new difflib.SequenceMatcher(base, newtxt, thirdText),
opcodes = sm.get_opcodes(),
diffoutputdiv = byId("diffoutput"),
contextSize = byId("contextSize").value;
diffoutputdiv.innerHTML = "";
contextSize = contextSize || null;
diffoutputdiv.appendChild(diffview.buildView({
baseTextLines: base,
newTextLines: newtxt,
thirdTextLines: thirdText,
opcodes: opcodes,
baseTextName: "Base Text",
newTextName: "New Text",
thirdTextName: "Third Text",
contextSize: contextSize,
viewType: viewType
}));
}
</script>
</head>
<body>
<div class="top">
<strong>Context size (optional):</strong> <input type="text" id="contextSize" value="" />
</div>
<div class="textInput">
<h2>Base Text</h2>
<textarea id="baseText" >a</textarea>
</div>
<div class="textInput spacer">
<h2>New Text</h2>
<textarea id="newText">b</textarea>
</div>
<div class="textInput spacer">
<h2>3rd Text</h2>
<textarea id="3rdText">c</textarea>
</div>
<div class="viewType">
<input type="radio" name="_viewtype" id="sidebyside" onclick="diffUsingJS(0);" /> <label for="sidebyside">Side by Side Diff</label>
<input type="radio" name="_viewtype" id="inline" onclick="diffUsingJS(1);" /> <label for="inline">Inline Diff</label>
</div>
<div id="diffoutput"> </div>
</body>
</html>
diffview.js
var diffview = {
/**
* Builds and returns a visual diff view. The single parameter, `params', should contain
* the following values:
*
* - baseTextLines: the array of strings that was used as the base text input to SequenceMatcher
* - newTextLines: the array of strings that was used as the new text input to SequenceMatcher
* - opcodes: the array of arrays returned by SequenceMatcher.get_opcodes()
* - baseTextName: the title to be displayed above the base text listing in the diff view; defaults
* to "Base Text"
* - newTextName: the title to be displayed above the new text listing in the diff view; defaults
* to "New Text"
* - contextSize: the number of lines of context to show around differences; by default, all lines
* are shown
* - viewType: if 0, a side-by-side diff view is generated (default); if 1, an inline diff view is
* generated
*/
buildView: function (params) {
var baseTextLines = params.baseTextLines;
var newTextLines = params.newTextLines;
var thirdTextLines = params.thirdTextLines;
var opcodes = params.opcodes;
var baseTextName = params.baseTextName ? params.baseTextName : "Base Text";
var newTextName = params.newTextName ? params.newTextName : "New Text";
var thirdTextName = params.thirdTextName ? params.thirdTextName: "Third Text"
var contextSize = params.contextSize;
var inline = (params.viewType == 0 || params.viewType == 1) ? params.viewType : 0;
if (baseTextLines == null)
throw "Cannot build diff view; baseTextLines is not defined.";
if (newTextLines == null)
throw "Cannot build diff view; newTextLines is not defined.";
if (thirdTextLines == null)
throw "Cannot build diff view; thirdTextLines is not defined.";
if (!opcodes)
throw "Canno build diff view; opcodes is not defined.";
function celt (name, clazz) {
var e = document.createElement(name);
e.className = clazz;
return e;
}
function telt (name, text) {
var e = document.createElement(name);
e.appendChild(document.createTextNode(text));
return e;
}
function ctelt (name, clazz, text) {
var e = document.createElement(name);
e.className = clazz;
e.appendChild(document.createTextNode(text));
return e;
}
var tdata = document.createElement("thead");
var node = document.createElement("tr");
tdata.appendChild(node);
if (inline) {
node.appendChild(document.createElement("th"));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", baseTextName + " vs. " + newTextName + " vs. " + thirdTextName));
} else {
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", baseTextName));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", newTextName));
node.appendChild(document.createElement("th"));
node.appendChild(ctelt("th", "texttitle", thirdTextName));
}
tdata = [tdata];
var rows = [];
var node2;
/**
* Adds two cells to the given row; if the given row corresponds to a real
* line number (based on the line index tidx and the endpoint of the
* range in question tend), then the cells will contain the line number
* and the line of text from textLines at position tidx (with the class of
* the second cell set to the name of the change represented), and tidx + 1 will
* be returned. Otherwise, tidx is returned, and two empty cells are added
* to the given row.
*/
function addCells (row, tidx, tend, textLines, change) {
if (tidx < tend) {
row.appendChild(telt("th", (tidx + 1).toString()));
row.appendChild(ctelt("td", change, textLines[tidx].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
return tidx + 1;
} else {
row.appendChild(document.createElement("th"));
row.appendChild(celt("td", "empty"));
return tidx;
}
}
function addCellsInline (row, tidx, tidx2, textLines, change) {
row.appendChild(telt("th", tidx == null ? "" : (tidx + 1).toString()));
row.appendChild(telt("th", tidx2 == null ? "" : (tidx2 + 1).toString()));
row.appendChild(ctelt("td", change, textLines[tidx != null ? tidx : tidx2].replace(/\t/g, "\u00a0\u00a0\u00a0\u00a0")));
}
for (var idx = 0; idx < opcodes.length; idx++) {
code = opcodes[idx];
change = code[0];
var b = code[1];
var be = code[2];
var n = code[3];
var ne = code[4];
var rowcnt = Math.max(be - b, ne - n);
var toprows = [];
var botrows = [];
for (var i = 0; i < rowcnt; i++) {
// jump ahead if we've alredy provided leading context or if this is the first range
if (contextSize && opcodes.length > 1 && ((idx > 0 && i == contextSize) || (idx == 0 && i == 0)) && change=="equal") {
var jump = rowcnt - ((idx == 0 ? 1 : 2) * contextSize);
if (jump > 1) {
toprows.push(node = document.createElement("tr"));
b += jump;
n += jump;
i += jump - 1;
node.appendChild(telt("th", "..."));
if (!inline) node.appendChild(ctelt("td", "skip", ""));
node.appendChild(telt("th", "..."));
node.appendChild(ctelt("td", "skip", ""));
// skip last lines if they're all equal
if (idx + 1 == opcodes.length) {
break;
} else {
continue;
}
}
}
toprows.push(node = document.createElement("tr"));
if (inline) {
if (change == "insert") {
addCellsInline(node, null, n++, newTextLines, change);
} else if (change == "replace") {
botrows.push(node2 = document.createElement("tr"));
if (b < be) addCellsInline(node, b++, null, baseTextLines, "delete");
if (n < ne) addCellsInline(node2, null, n++, newTextLines, "insert");
if (n < ne) addCellsInline(node2, null, n++, thirdTextLines, "insert");
} else if (change == "delete") {
addCellsInline(node, b++, null, baseTextLines, change);
} else {
// equal
addCellsInline(node, b++, n++, baseTextLines, change);
}
} else {
b = addCells(node, b, be, baseTextLines, change);
n = addCells(node, n, ne, newTextLines, change);
n = addCells(node, n, ne, thirdTextLines, change);
}
}
for (var i = 0; i < toprows.length; i++) rows.push(toprows[i]);
for (var i = 0; i < botrows.length; i++) rows.push(botrows[i]);
}
tdata.push(node = document.createElement("tbody"));
for (var idx in rows) rows.hasOwnProperty(idx) && node.appendChild(rows[idx]);
node = celt("table", "diff" + (inline ? " inlinediff" : ""));
for (var idx in tdata) tdata.hasOwnProperty(idx) && node.appendChild(tdata[idx]);
return node;
}
};
difflib.js
var __whitespace = {" ":true, "\t":true, "\n":true, "\f":true, "\r":true};
var difflib = {
defaultJunkFunction: function (c) {
return __whitespace.hasOwnProperty(c);
},
stripLinebreaks: function (str) { return str.replace(/^[\n\r]*|[\n\r]*$/g, ""); },
stringAsLines: function (str) {
var lfpos = str.indexOf("\n");
var crpos = str.indexOf("\r");
var linebreak = ((lfpos > -1 && crpos > -1) || crpos < 0) ? "\n" : "\r";
var lines = str.split(linebreak);
for (var i = 0; i < lines.length; i++) {
lines[i] = difflib.stripLinebreaks(lines[i]);
}
return lines;
},
// iteration-based reduce implementation
__reduce: function (func, list, initial) {
if (initial != null) {
var value = initial;
var idx = 0;
} else if (list) {
var value = list[0];
var idx = 1;
} else {
return null;
}
for (; idx < list.length; idx++) {
value = func(value, list[idx]);
}
return value;
},
// comparison function for sorting lists of numeric tuples
__ntuplecomp: function (a, b) {
var mlen = Math.max(a.length, b.length);
for (var i = 0; i < mlen; i++) {
if (a[i] < b[i]) return -1;
if (a[i] > b[i]) return 1;
}
return a.length == b.length ? 0 : (a.length < b.length ? -1 : 1);
},
__calculate_ratio: function (matches, length) {
return length ? 2.0 * matches / length : 1.0;
},
// returns a function that returns true if a key passed to the returned function
// is in the dict (js object) provided to this function; replaces being able to
// carry around dict.has_key in python...
__isindict: function (dict) {
return function (key) { return dict.hasOwnProperty(key); };
},
// replacement for python's dict.get function -- need easy default values
__dictget: function (dict, key, defaultValue) {
return dict.hasOwnProperty(key) ? dict[key] : defaultValue;
},
SequenceMatcher: function (a, b, c, isjunk) {
this.set_seqs = function (a, b, c, ) {
this.set_seq1(a);
this.set_seq2(b);
this.set_seq3(c);
}
this.set_seq1 = function (a) {
if (a == this.a) return;
this.a = a;
this.matching_blocks = this.opcodes = null;
}
this.set_seq2 = function (b) {
console.log("Value in set ", b)
if (b == this.b) return;
this.b = b;
this.matching_blocks = this.opcodes = this.fullbcount = null;
this.__chain_b();
}
this.set_seq3 = function (c) {
console.log("Value in set ", c)
if (c == this.c) return;
this.c = c;
this.matching_blocks = this.opcodes = this.fullbcount = null;
this.__chain_c();
}
this.__chain_c = function () {
console.log("This is ", this.c)
var c = this.c;
var n = c.length;
var c2j = this.c2j = {};
var populardict = {};
for (var i = 0; i < c.length; i++) {
var celt = c[i];
if (c2j.hasOwnProperty(celt)) {
var indices = c2j[elt];
if (n >= 200 && indices.length * 100 > n) {
populardict[celt] = 1;
delete c2j[celt];
} else {
indices.push(i);
}
} else {
c2j[celt] = [i];
}
}
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt)) {
delete c2j[elt];
}
}
var isjunk = this.isjunk;
var junkdict = {};
if (isjunk) {
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete populardict[elt];
}
}
for (var elt in c2j) {
if (c2j.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete c2j[elt];
}
}
}
this.iscjunk = difflib.__isindict(junkdict);
this.iscpopular = difflib.__isindict(populardict);
}
this.__chain_b = function () {
var b = this.b;
var n = b.length;
var b2j = this.b2j = {};
var populardict = {};
for (var i = 0; i < b.length; i++) {
var elt = b[i];
if (b2j.hasOwnProperty(elt)) {
var indices = b2j[elt];
if (n >= 200 && indices.length * 100 > n) {
populardict[elt] = 1;
delete b2j[elt];
} else {
indices.push(i);
}
} else {
b2j[elt] = [i];
}
}
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt)) {
delete b2j[elt];
}
}
var isjunk = this.isjunk;
var junkdict = {};
if (isjunk) {
for (var elt in populardict) {
if (populardict.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete populardict[elt];
}
}
for (var elt in b2j) {
if (b2j.hasOwnProperty(elt) && isjunk(elt)) {
junkdict[elt] = 1;
delete b2j[elt];
}
}
}
this.isbjunk = difflib.__isindict(junkdict);
this.isbpopular = difflib.__isindict(populardict);
}
this.find_longest_match = function (alo, ahi, blo, bhi) {
var a = this.a;
var b = this.b;
var b2j = this.b2j;
var isbjunk = this.isbjunk;
var besti = alo;
var bestj = blo;
var bestsize = 0;
var j = null;
var k;
var j2len = {};
var nothing = [];
for (var i = alo; i < ahi; i++) {
var newj2len = {};
var jdict = difflib.__dictget(b2j, a[i], nothing);
for (var jkey in jdict) {
if (jdict.hasOwnProperty(jkey)) {
j = jdict[jkey];
if (j < blo) continue;
if (j >= bhi) break;
newj2len[j] = k = difflib.__dictget(j2len, j - 1, 0) + 1;
if (k > bestsize) {
besti = i - k + 1;
bestj = j - k + 1;
bestsize = k;
}
}
}
j2len = newj2len;
}
while (besti > alo && bestj > blo && !isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) {
besti--;
bestj--;
bestsize++;
}
while (besti + bestsize < ahi && bestj + bestsize < bhi &&
!isbjunk(b[bestj + bestsize]) &&
a[besti + bestsize] == b[bestj + bestsize]) {
bestsize++;
}
while (besti > alo && bestj > blo && isbjunk(b[bestj - 1]) && a[besti - 1] == b[bestj - 1]) {
besti--;
bestj--;
bestsize++;
}
while (besti + bestsize < ahi && bestj + bestsize < bhi && isbjunk(b[bestj + bestsize]) &&
a[besti + bestsize] == b[bestj + bestsize]) {
bestsize++;
}
return [besti, bestj, bestsize];
}
this.get_matching_blocks = function () {
if (this.matching_blocks != null) return this.matching_blocks;
var la = this.a.length;
var lb = this.b.length;
var queue = [[0, la, 0, lb]];
var matching_blocks = [];
var alo, ahi, blo, bhi, qi, i, j, k, x;
while (queue.length) {
qi = queue.pop();
alo = qi[0];
ahi = qi[1];
blo = qi[2];
bhi = qi[3];
x = this.find_longest_match(alo, ahi, blo, bhi);
i = x[0];
j = x[1];
k = x[2];
if (k) {
matching_blocks.push(x);
if (alo < i && blo < j)
queue.push([alo, i, blo, j]);
if (i+k < ahi && j+k < bhi)
queue.push([i + k, ahi, j + k, bhi]);
}
}
matching_blocks.sort(difflib.__ntuplecomp);
var i1 = 0, j1 = 0, k1 = 0, block = 0;
var i2, j2, k2;
var non_adjacent = [];
for (var idx in matching_blocks) {
if (matching_blocks.hasOwnProperty(idx)) {
block = matching_blocks[idx];
i2 = block[0];
j2 = block[1];
k2 = block[2];
if (i1 + k1 == i2 && j1 + k1 == j2) {
k1 += k2;
} else {
if (k1) non_adjacent.push([i1, j1, k1]);
i1 = i2;
j1 = j2;
k1 = k2;
}
}
}
if (k1) non_adjacent.push([i1, j1, k1]);
non_adjacent.push([la, lb, 0]);
this.matching_blocks = non_adjacent;
return this.matching_blocks;
}
this.get_opcodes = function () {
if (this.opcodes != null) return this.opcodes;
var i = 0;
var j = 0;
var answer = [];
this.opcodes = answer;
var block, ai, bj, size, tag;
var blocks = this.get_matching_blocks();
for (var idx in blocks) {
if (blocks.hasOwnProperty(idx)) {
block = blocks[idx];
ai = block[0];
bj = block[1];
size = block[2];
tag = '';
if (i < ai && j < bj) {
tag = 'replace';
} else if (i < ai) {
tag = 'delete';
} else if (j < bj) {
tag = 'insert';
}
if (tag) answer.push([tag, i, ai, j, bj]);
i = ai + size;
j = bj + size;
if (size) answer.push(['equal', ai, i, bj, j]);
}
}
return answer;
}
// this is a generator function in the python lib, which of course is not supported in javascript
// the reimplementation builds up the grouped opcodes into a list in their entirety and returns that.
this.get_grouped_opcodes = function (n) {
if (!n) n = 3;
var codes = this.get_opcodes();
if (!codes) codes = [["equal", 0, 1, 0, 1]];
var code, tag, i1, i2, j1, j2;
if (codes[0][0] == 'equal') {
code = codes[0];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
codes[0] = [tag, Math.max(i1, i2 - n), i2, Math.max(j1, j2 - n), j2];
}
if (codes[codes.length - 1][0] == 'equal') {
code = codes[codes.length - 1];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
codes[codes.length - 1] = [tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)];
}
var nn = n + n;
var group = [];
var groups = [];
for (var idx in codes) {
if (codes.hasOwnProperty(idx)) {
code = codes[idx];
tag = code[0];
i1 = code[1];
i2 = code[2];
j1 = code[3];
j2 = code[4];
if (tag == 'equal' && i2 - i1 > nn) {
group.push([tag, i1, Math.min(i2, i1 + n), j1, Math.min(j2, j1 + n)]);
groups.push(group);
group = [];
i1 = Math.max(i1, i2-n);
j1 = Math.max(j1, j2-n);
}
group.push([tag, i1, i2, j1, j2]);
}
}
if (group && !(group.length == 1 && group[0][0] == 'equal')) groups.push(group)
return groups;
}
this.ratio = function () {
matches = difflib.__reduce(
function (sum, triple) { return sum + triple[triple.length - 1]; },
this.get_matching_blocks(), 0);
return difflib.__calculate_ratio(matches, this.a.length + this.b.length);
}
this.quick_ratio = function () {
var fullbcount, elt;
if (this.fullbcount == null) {
this.fullbcount = fullbcount = {};
for (var i = 0; i < this.b.length; i++) {
elt = this.b[i];
fullbcount[elt] = difflib.__dictget(fullbcount, elt, 0) + 1;
}
}
fullbcount = this.fullbcount;
var avail = {};
var availhas = difflib.__isindict(avail);
var matches = numb = 0;
for (var i = 0; i < this.a.length; i++) {
elt = this.a[i];
if (availhas(elt)) {
numb = avail[elt];
} else {
numb = difflib.__dictget(fullbcount, elt, 0);
}
avail[elt] = numb - 1;
if (numb > 0) matches++;
}
return difflib.__calculate_ratio(matches, this.a.length + this.b.length);
}
this.real_quick_ratio = function () {
var la = this.a.length;
var lb = this.b.length;
return _calculate_ratio(Math.min(la, lb), la + lb);
}
this.isjunk = isjunk ? isjunk : difflib.defaultJunkFunction;
this.a = this.b = null;
this.set_seqs(a, b, c);
}
};
I have some js code that I would like to run only when the window is at a "large" screen size, let's say 900px. I want to use it like a media query in css, so the code can toggle on and off at a specific break point. So I'm assuming I need some sort of condition with the resize function like this:
$(window).resize(function () {
var viewportWidth = $(window).width();
if (viewportWidth < 900) {
}
});
And then put the code I want to execute between the curly brackets, but its not working.
This is the code that I would like to execute when the screen is resized to 900px:
function makeRowDiv(buildRow) {
var row = document.createElement('div');
row.className = 'row expanded row-spacing';
for (var i = 0; i < buildRow.length; ++i) {
row.appendChild(buildRow[i]);
}
return row;
}
window.onload = function () {
var work = document.getElementById('work'),
items = work.getElementsByTagName('div'),
newWork = document.createElement('div');
var buildRow = [],
count = 0;
for (var i = 0; i < items.length; ++i) {
var item = items[i];
if (item.className.indexOf('columns') == -1) {
continue;
}
// Extract the desired value.
var matches = /large-(\d+)\s* large-offset-(\d+)/.exec(item.className),
delta = parseInt(matches[1], 10) + parseInt(matches[2], 10);
if (count + delta > 12 && buildRow.length != 0) {
newWork.appendChild(makeRowDiv(buildRow));
count = 0;
buildRow = [];
}
buildRow.push(item.cloneNode(true));
count += delta;
}
if (buildRow.length != 0) {
newWork.appendChild(makeRowDiv(buildRow));
}
// Replace work with newWork.
work.parentNode.insertBefore(newWork, work);
work.parentNode.removeChild(work);
newWork.id = 'work';
};
I'm assuming that its possible to so with the
you can use a media query in javascript as well and use that as your condition
var mq = window.matchMedia( "(max-width: 900px)" );
if (mq.matches) {
// window width is less than 900px
} else {
// window width is more than 900px
}
Try this:
$(window).on('resize',function () {
var $width = $(window).width();
console.log($width);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You could do something like this
function makeRowDiv(buildRow) {
var row = document.createElement('div');
row.className = 'row expanded row-spacing';
for (var i = 0; i < buildRow.length; ++i) {
row.appendChild(buildRow[i]);
}
return row;
}
function loadData() {
var work = document.getElementById('work'),
items = work.getElementsByTagName('div'),
newWork = document.createElement('div');
var buildRow = [],
count = 0;
for (var i = 0; i < items.length; ++i) {
var item = items[i];
if (item.className.indexOf('columns') == -1) {
continue;
}
// Extract the desired value.
var matches = /large-(\d+)\s* large-offset-(\d+)/.exec(item.className),
delta = parseInt(matches[1], 10) + parseInt(matches[2], 10);
if (count + delta > 12 && buildRow.length != 0) {
newWork.appendChild(makeRowDiv(buildRow));
count = 0;
buildRow = [];
}
buildRow.push(item.cloneNode(true));
count += delta;
}
if (buildRow.length != 0) {
newWork.appendChild(makeRowDiv(buildRow));
}
// Replace work with newWork.
work.parentNode.insertBefore(newWork, work);
work.parentNode.removeChild(work);
newWork.id = 'work';
};
window.onload = loadData;
window.onresize = function(){
if(window.innerWidth < 900){
loadData();
makeRowDiv(buildRow)
}
}
Assuming you want to call the function that you added on window.onload for window resize event also.
I am optimizing a Java code to JS, but runs on Nashorn and do not own debug option. The input is val = "JPG ou PNG" and the output is "JPG ou PNG". Why does this happen? I need the output to be "jpg/png"
Function
function process(val) {
var cleaned = val.replaceAll("[•×\\tª°▪º⊗ fi ²●˚~ĩ`ũ]", "").trim().toLowerCase();
var out = [];
if (cleaned.contains("ou")) {
out = cleaned.split("ou");
}
else if (cleaned.contains("/")) {
out = cleaned.split("/");
}
else {
return cleaned;
}
for (var i = 0; i < out.length; i++) {
out[i] = out[i].trim();
}
return join(out, "/");
}
Three of your functions don't exist in javascript:
replaceAll(searchValue, newValue) in javascript is replace(searchValue, newValue)
contains(searchValue) in javascript is indexOf(searchValue) > -1
join(array, separator) in javascript is array.join(separator)
JSFIDDLE DEMO
Here's my solution:
function process(val) {
var cleaned = val.replace("[•×\\tª°▪º⊗ fi ²●˚~ĩ`ũ]", "").trim().toLowerCase();
var out = [];
if (cleaned.indexOf("ou") >= 0) {
out = cleaned.split("ou");
}
else if (cleaned.indexOf("/") >= 0) {
out = cleaned.split("/");
}
else {
return cleaned;
}
for (var i = 0; i < out.length; i++) {
out[i] = out[i].trim();
}
return join(out, "/");
}
Your logic was right, but strings in Javascript don't have 'replaceAll' and 'contains', so I replaced them with 'replace' and 'indexOf(x) >= 0'.
Also, you mentioned you don't have the option to debug in your environment, yet the function you provided is pretty standalone. This means you could easily copy it into another environment to test it in isolation.
For example, I was able to wrap this code in a HTML file then open it in my web browser (I had to implement my own 'join').
<html>
<body>
<script>
function join(val, divider) {
var out = "";
for(var i = 0; i < val.length; i++) {
if(out.length > 0) out += divider;
out += val[i];
}
return out;
}
function process(val) {
var cleaned = val.replace("[•×\\tª°▪º⊗ fi ²●˚~ĩ`ũ]", "").trim().toLowerCase();
var out = [];
if (cleaned.indexOf("ou") >= 0) {
out = cleaned.split("ou");
}
else if (cleaned.indexOf("/") >= 0) {
out = cleaned.split("/");
}
else {
return cleaned;
}
for (var i = 0; i < out.length; i++) {
out[i] = out[i].trim();
}
return join(out, "/");
}
var inval = "JPG ou PNG";
var outval = process(inval);
console.log(inval + " => " + outval);
</script>
</body>
</html>
I verified it works by opening up the console and seeing the output "JPG ou PNG => jpg/png".
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>