I was checking some simple solutions for showing multiple web pages for some dashboard and currently fighting with simple HTML page with javascript inside to achieve what I want to see there.
var urls = new Array();
urls[0] = "https://stackoverflow.com/"
urls[1] = "https://www.google.com"
var arrayLength = urls.length;
for (var i = 0; i < arrayLength; i++) {
window.location.assign(urls[i]);
sleep(3000);
}
function sleep(milliseconds) {
var start = new Date().getTime();
for (var i = 0; i < 1e7; i++) {
if ((new Date().getTime() - start) > milliseconds) {
break;
}
}
}
Currently this page opens only first page (after some time) and looks like it doesn't do iteration trough other pages. Maybe you could help me to make it work? I want to rotate those pages forever on screen (will add some infinite while loop after making this part working).
Currently this page opens only first page (after some time) and looks
like it doesn't do iteration trough other pages.
Once you change your window.location, and go to the first url from the array, you are losing all of your JS code (as it is not present in just opened url any more).
You can do this by installing a chrome plugin (which will not lose your JS after window.location change).
The plugin will run the added JS at DOMContentLoaded (no need to attach any event listener).
I needed also to do this, check things on the page, store some information and move on to the next page. I know, this can be done with Python and other stuff but by doing this it can be done on the FE side also.
I used the localStorage to store my information.
I pasted this into the browser console to prepare all the stuff and clean the localStorage:
// clear the localStorage
localStorage.clear();
// set an array that will keep all our pages to iterate into the localStorage
localStorage.setItem(
"pages",
JSON.stringify([
"https://my-page-1.html",
"https://my-page-2.html",
"https://my-page-3.html",
"https://my-page-4.html",
])
);
// set an array that will keep our findings
localStorage.setItem("resultArray", JSON.stringify([]));
// move to the first page of the iteration
window.location.href = "https://my-page-1.html";
After doing this, I opened the plugin interface and added the following code:
(function check() {
// array saved into the localStorage that contains all the pages to iterate
const pagesArray = JSON.parse(localStorage.getItem("pages"));
// array to store your stuff
const resultArray = JSON.parse(localStorage.getItem("resultArray"));
// whatever you want to check on that page
const myFancyCondition = true;
if (myFancyCondition) {
// push any data to the array so that you can check it later
resultArray.push({
page: pagesArray[0],
message: "I found what I was looking for!",
});
}
//remove the current page from the array
pagesArray.shift();
//reset the array value after the first page was already checked
localStorage.setItem("pages", JSON.stringify(pagesArray));
//store the array data
localStorage.setItem("resultArray", JSON.stringify(resultArray));
// quit if the iteration is over and there are no more pages to check
if(!pagesArray.length) return;
//go to the next page
window.location.href = pagesArray[0];
})();
Then, to check the results you just need to read the data from the localStorage like:
JSON.parse(localStorage.getItem('resultArray'))
I hope this helps :)!
I was noticing that W3Schools has a tutorial on what they're calling W3.JS, which in my opinion appears to compete with jQuery. I was having trouble finding information on it from any source other than w3Schools themselves.
W3Schools does appear (in my opinion) to have some propensity to promote semi-abandonware. For example, AppML.
Is this library actually used anywhere? What is its history (especially its release history) and if this is actually going to be developed into something that would actually be worth considering using?
Note: I'm not seeking a library recommendation here - I do realize that that's explicitly off-topic - I'm just asking for background information on this particular library.
The W3 JS library has a couple of attractive properties.
1. It's very lite.
2. There's not much of a learning curve; I was able to get a few things "working" with little to no documentation (and beyond w3schools.com, there's not much.)
I tried several different pieces of functionality in the library and here's my take on it.
To try and gain some separation of concerns, I stumbled on this library looking for the ability to use a PHP-like include statement to pull in an HTML fragment file. W3.JS provides the ability to add an attribute to a div element
<div w3-include-html="frags/content.html"></div>
And with a JQuery UI-esque initialize statement, the file's contents would be loaded into your div element on the client side.
<script>
w3.includeHTML();
</script>
This does work but it's about all that does. I used the library on a legacy App I inherited that was done in Classic ASP on the server side. One thing I relied upon from JQuery was the AJAX function for POST requests to a crude ASP page I used as a "data access layer." The page would use a POST variable like an enum to tell it which function to call and then subsequent variables as needed in each function. Below is an example of W3.JSs ability to perform a Web Request and then use it's display-object function with an HTML object (here an un-ordered list) to displayed a retrieved JSON object that has an attribute "customers" that is an array. This will generate LI elements with an innerHTML that is an attribute of each customer instance; "CustomerName." ({{CustomerName}}) is a place holder here.
<ul id="id01">
<li w3-repeat="customers">{{CustomerName}}</li>
</ul>
<script>
w3.getHttpObject("CommonServerFns.asp?operation=1", controllerFn);
function controllerFn(myObject) {
//myObject looks like {"customers":[{"CustomerName":"Mike Jones"}]}
w3.displayObject("id01", myObject);
}
</script>
So to even try the above example I had to convert my data page to use the Query String of a GET request, which I didn't have a problem with. However, used in Lieu of a JQuery AJAX request and a vanilla JS callback function, like below.
$.ajax({
url: "ServerCommonFns.asp",
type: "POST",
data: '{"operation":1}',
complete: function(jqXHR, statusMsg){
//if status is 200, jqXHR.responseText has my serialized JSON
var retData = JSON.parse(jqXHR.responseText);
var tgtListElement = document.getElementById("id01");
//Clear the placeholder code from the list and go to work...
tgtListElement.innerHTML = "";
for(var index = 0;index<retData.length;index++){
var listNode = document.createElement("li");
listNode.innerHTML = retData[index].CustomerName;
tgtListElement.appendChild(listNode);
}
});
So W3JS looks like the preferred solution, it's less code for sure. However, in the app I worked on, I timed the web requests for both method and the results were shocking. The request returned a JSON string that was roughly 737K in size and the request took ~2.5 seconds to complete. My JQuery solution took about ~4.5 seconds including the ~2.5 second request. The W3.JS solution took anywhere from 17 - 27 seconds to complete. I did some tweaking thinking that I had made a mistake and that was the only way the "Better & Faster Javascript Library" could be running that poorly but it appears not. I don't know why but the W3 JS solution was clearly not usable in my app.
I tried to use this library again early last week; thinking an application less data intensive might work much better. If you've read this far I'll save you a few more lines of reading....it wasn't. This app used Classic ASP with another "data access layer" type ASP page, again utilized with JQuery and Vanilla JS using the AJAX function. I built a JS function to pass as param/function ptr like so
var sortAsc = true;
//JSONObj looks like {"faqs":[{id:1,createdBy:"Les Grossman"},
//{id:2,createdBy:"Jeff Portnoy"}]};
var JSONObj = null;
function compareFn(a, b){
if(a.id < b.id) return sortAsc ? 1 : -1;
if(a.id > b.id) return sortAsc ? -1 : 1;
return 0;
}
//Assign my onclick event handler
document.getElementById("faqId").onclick = function(){
JSONObj.sort(compareFn);
sortAsync = !sortAsync;
//Logic below to clear and reload the rows in my HTML table...
//See above example for pretty much identical code
}
This again is fairly code intensive and I didn't want to have to fire of a web request everytime a column header was clicked (to use the sort ability of a SQLite Query) rather than a custom JS function. So I tried using the w3.sortHTML() function to do the job. It looked something like this but I kept my JQuery AJAX code to load the table initially and used the sortHTML() function post load for sorting. The w3.sortHTML function takes params in this order
Repeating element container unique selector ("Select, UL, OL, Table, etc.").
Repeating element group selector (option, li, tr, etc.) In this instance I use .faq as I've applied it to all table -> tr instances.
Selector for attribute/element of repeating group to sort by (Keeps track of ascending/descending sort order internally.)
FAQ Number
FAQ Name
1
Tug Speedman
2
Alpa Chino
3
Kirk Lazarus
...
I'm using this page to display FAQ Data from our HelpDesk system (uses my login to scrape data into a SQLite database so any user can see FAQ data without needing a login/license for a Helpdesk system.) The web request returns a JSON string roughly 430 KB in size and creates 320 table rows with 5 table columns (for our e.g. only two columns are coded for.) This request takes ~3 seconds to complete. My JQuery/JS AJAX request w/ callback function roughly ~5.5 seconds total, including the ~3 secs for web request/response. My custom sort fn took less than 1 second, regardless of sort by column (only id shown in example), to sort my ret data obj (sorted as a global object "JSONObj"), clear the table and refill the table with sorted rows. Again, lots of code to do this so I thought W3 JS might help me out. My W3 JS sort implementation takes ~8 seconds to sort integer/numeric data and ~10 seconds to sort text/string data. This is way too long for my needs (again) so I reverted back to my JQuery/JS solution.
In conclusion, it seems that anything of greater than trivial size begets really poor performance in this library. I think the creators of W3.JS had their functional requirements correct as the library does boast some very useful abstracted functionality but it's no replacement for JQuery and other existing frameworks or even your good old fashioned Javascript code. Wish things had worked out; would have been really helpful.
EDIT -
So I've been going through the source of the library and, while there are several shorthand methods for web reqs, there is simply a w3.http() method with the following signature.
function (target, readyfunc, xml, method)
The params are appropriately named except for xml which is just a string value. I was able to get this working with my previously mentioned ASP page that handles POST requests. I invoked it like so.
w3.http("ServerCommonFns.asp", httpCallBack, "operation=1", "post");
function httpCallBack(){
if(this.readyState == 1){
console.log("Setting needed header...");
this.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
}
else if(this.readyState == 4){
console.log("Parsing response....");
//document.getElementById("main").innerHTML = JSON.stringify(this.responseText);
var responseObj = JSON.parse(this.responseText);
var respDataObj = JSON.parse(responseObj.retdata);
var tableObj = document.getElementById("responseTable");
tableObj.innerHTML = "";
for(var index=0;index<respDataObj.length;index++){
var newRow = document.createElement("tr");
newRow.innerHTML = "<td>" + respDataObj[index].MACHINE_ID + "</td>";
tableObj.appendChild(newRow);
}
return false;
}
}
You'll see httpCallBack is used like it's the listener for the onreadystatechange event for the internal xhr object because it is just that. In order to work in my instance, I had to set the content-type header before the request was opened so my xml/param argument was interpreted properly. So W3.JS can do POST requests but the w3.http() function is little more than a simple wrapper around the Javascript XMLHttpRequest() object. Also, the requests are invoked Asynchronously and there's no way to change that behavior so just FYI.
--SECOND EDIT. So I've got a lull in work and I felt I may have given W3.JS less than it's due. Today I experimented with a few things and examined the source for a little insight. I found a couple things that I find at least neat and I thought I'd finish this wall of text with them. Below this is the source for what I did today. I tried combining a few W3.JS functions with an existing data source for an app I wrote for our MFG Q/A folks.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Test Page</title>
<script src="https://www.w3schools.com/lib/w3.js"></script>
<script>
var xhrObj = null;
var jsonObj = null;
var sortAsc = true;
function w3ReadyStateChanged(){
if(this.readyState == 1){
console.log("Preparing Request/Setting needed header...");
this.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
}
else if(this.readyState == 4){
console.log("Parsing response....");
//document.getElementById("main").innerHTML = JSON.stringify(this.responseText);
var responseObj = JSON.parse(this.responseText);
if(responseObj.retcode != 1){
console.log("A retcode of: " + responseObj.retcode + " has indicated a failed web request...");
return false;
}
jsonObj = {};
//var respDataObj = JSON.parse(responseObj.retdata);
jsonObj.retdata = JSON.parse(responseObj.retdata);
//
console.log("Starting Display: " + new Date())
w3.displayObject("responseTable", jsonObj);
console.log("Display Finished: " + new Date())
//This is to stop page refresh.
return false;
}
}
function tryw3xhr(){
w3.http("ParCommonFns.asp", w3ReadyStateChanged, "operation=13&useCriteria=false&openPARs=1", "POST");
}
function compareFn(a, b){
if(parseInt(a[0]) > parseInt(b[0]))
return 1;
else if(parseInt(a[0]) < parseInt(b[0]))
return -1;
else
return 0;
}
function sortContainerData(containerElementId, repeatingSelector, sortByIndex){
//w3.sortHTML('#responseTable','tr.dataRow')
var dataObj = {};
var containerElement = document.getElementById(containerElementId);
if(!containerElement){
console.log("Couldn't locate a table or list with ID: " + containerElementId);
return false;
}
//
var sortElements = containerElement.querySelectorAll(repeatingSelector);
if(!sortElements || sortElements.length == 0){
console.log("repeatingSelector failed to yield results: ");
return false;
}
//
dataObj.sortElements = new Array(sortElements.length);
for(var i = 0;i<sortElements.length;i++){
var tempArray = new Array(sortElements[i].children.length);
for(var j = 0;j<sortElements[i].children.length;j++){
tempArray[j] = sortElements[i].children[j].innerHTML;
}
dataObj.sortElements[i] = tempArray;
}
//w3.sortHTML('#responseTable', '.dataRow', 'td')
console.log("Starting Sort: " + new Date());
var t0 = performance.now();
var doCustom = false, didSwap = false;
if(doCustom){
var sortLen = dataObj.sortElements.length;
var j = 0;
//if (parseInt(dataObj.sortElements[i][sortByIndex]) == dataObj.sortElements[i][sortByIndex])
// compareInt = true;
for (var i = 0; i < sortLen - 1; i++){
didSwap = false;
j = i + 1;
while (j < sortLen && parseInt(dataObj.sortElements[i][sortByIndex]) >= parseInt(dataObj.sortElements[j][sortByIndex])) {
j++;
}
//If j equals sortLen, then i is greater than all others so we stick it on top.....
if (i + 1 == j)
break;
if (j == sortLen) {
dataObj.sortElements.push(dataObj.sortElements[i].slice());
dataObj.sortElements.splice(i, 1);
didSwap = true;
} else if (j > (i + 1)) {
dataObj.sortElements.splice(j, 0, dataObj.sortElements[i].slice());
dataObj.sortElements.splice(i, 1);
didSwap = true;
}
if (didSwap)
i--;
//if(i % 50 == 0)
// console.log("Handled: " + i);
}
//This is cheating but it should work.....
if (!sortAsc) dataObj.sortElements.reverse();
}
else{
dataObj.sortElements.sort(compareFn);
}
sortAsc = !sortAsc;
console.log("Sort Time (MS): " + (performance.now() - t0));
//
console.log("Starting Reload: " + new Date()) ;
var containerBody = containerElement.querySelector("tbody");
containerBody.innerHTML = "";
for(var i = 0;i<dataObj.sortElements.length ;i++){
var newRow = document.createElement("tr");
newRow.classList.add("dataRow");
//
for(var j =0;j<dataObj.sortElements[i].length;j++){
var newCol = document.createElement("td");
newCol.innerHTML = dataObj.sortElements[i][j];
newRow.appendChild(newCol);
}
//
containerBody.appendChild(newRow);
}
console.log("Ops complete: " + new Date()) ;
return false;
}
window.onload = function () {
document.getElementById("invokeBtn").disabled = true;
tryw3xhr();
document.getElementById("invokeBtn").disabled = false;
w3.hide("#conditionalContent");
};
//
function runW3JSFn() {
var w3TargetId = "#w3Target";
var w3FunctionsSelect = document.getElementById("w3Functions");
if (w3FunctionsSelect.value == "show") {
w3.show(w3TargetId);
}
else if (w3FunctionsSelect.value == "hide") {
//Doesn't preserve space....
w3.hide(w3TargetId);
}
else if (w3FunctionsSelect.value == "toggle") {
w3.toggleShow(w3TargetId);
}
else if (w3FunctionsSelect.value == "addStyle") {
//But no remove style?
w3.addStyle(w3TargetId, 'border', '2px solid green');
}
else if (w3FunctionsSelect.value == "addClass") {
w3.addClass(w3TargetId, 'w3Class');
}
else if (w3FunctionsSelect.value == "removeClass") {
//Italics should go away.....
w3.removeClass(w3TargetId, 'w3Class');
}
else if (w3FunctionsSelect.value == "toggleClass") {
//Italics should go away.....
w3.toggleClass(w3TargetId, 'w3Class');
}
else if (w3FunctionsSelect.value == "filterTable") {
//Italics should go away.....
document.querySelector(w3TargetId).innerHTML = "<h2> Try an ID # in the box below....</h2>";
}
else { document.querySelector(w3TargetId).innerHTML = "<h2> Invalid function specified....</h2>"; }
}
//
function doVanillaJSFn() {
var w3TargetId = "#w3Target";
var w3FunctionsSelect = document.getElementById("w3Functions");
if (w3FunctionsSelect.value == "show") {
document.querySelector(w3TargetId).style.display = 'block';
}
else if (w3FunctionsSelect.value == "hide") {
//Doesn't preserve space....
document.querySelector(w3TargetId).style.display = 'none';
}
else if (w3FunctionsSelect.value == "toggle") {
var tgtElement = document.querySelector(w3TargetId);
if (tgtElement.style.display == 'block')
tgtElement.style.display = 'none';
else
tgtElement.style.display = 'block';
}
else if (w3FunctionsSelect.value == "addStyle") {
//$(tgtElement).css("attr", "val");
//Works....
document.querySelector(w3TargetId).setAttribute("style", "border: 4px solid green");
//But better.....
if(confirm("Try Better way ?"))
document.querySelector(w3TargetId).border = "4px solid green";
}
else if (w3FunctionsSelect.value == "addClass") {
document.querySelector(w3TargetId).classList.add("w3Class");
}
else if (w3FunctionsSelect.value == "removeClass") {
//Italics should go away.....
document.querySelector(w3TargetId).classList.remove("w3Class");
}
else if (w3FunctionsSelect.value == "toggleClass") {
//Italics should go away.....
var tgtElement = document.querySelector(w3TargetId);
if (tgtElement.classList.contains("w3Class"))
tgtElement.classList.remove("w3Class");
else
tgtElement.classList.add("w3Class");
}
else if (w3FunctionsSelect.value == "filterTable") {
//Italics should go away.....
document.querySelector("#filterCtrl").oninput = function () { myCustomFilter() };
document.querySelector(w3TargetId).innerHTML = "<h2> Try it now....</h2>";
}
else { document.querySelector(w3TargetId).innerHTML = "<h2> Invalid function specified....</h2>"; }
}
function myCustomFilter() {
var tableElement = document.getElementById("responseTable");
var filterData = document.getElementById("filterCtrl").value.trim().toLowerCase();
////
for (var i = 1; i < tableElement.rows.length; i++) {
var foundRowMatch = false;
if (filterData == "") {
tableElement.rows[i].style.display = 'table-row';
continue;
}
for (var j = 0; j < tableElement.rows[i].cells.length; j++) {
var cellSplit = tableElement.rows[i].cells[j].innerHTML.trim().split(' ');
for (var k = 0; k < cellSplit.length; k++) {
if (cellSplit[k].trim().toLowerCase() == filterData) {
foundRowMatch = true;
break;
}
}
if (foundRowMatch) break;
}
// //
if (!foundRowMatch) tableElement.rows[i].style.display = 'none';
else tableElement.rows[i].style.display = 'table-row';
}
//
return false;
}
</script>
<style>
#parHeaders{
background-color: red;
border-bottom: 4px solid black;
}
.w3Class {
font-style:italic;
}
</style>
</head>
<body>
<select id="w3Functions">
<option value="show">Show</option>
<option value="hide">Hide</option>
<option value="toggle">Toggle</option>
<option value="addStyle">Add Style</option>
<option value="addClass">Add Class</option>
<option value="removeClass">Remove Class</option>
<option value="toggleClass">Toggle Class</option>
<option value="filterTable">Filter Table</option>
</select>
<button id="invokeBtn" onclick="runW3JSFn(); return false;">Try w3 function</button>
<button id="invokeBtnAlternate" onclick="doVanillaJSFn(); return false;">Try JS Alternate Function</button>
<div id="w3Target"><h2>This Is My W3 Functions Target!!!!</h2></div>
<br/><br/>
Filter Data By Id: <input id="filterCtrl" type="text" oninput="w3.filterHTML('#responseTable', '.dataRow', this.value);" />
<br/>
<div><table id="responseTable">
<thead>
<tr id="parHeaders">
<th id="parIdHdr" onclick="sortContainerData('responseTable', 'tr.dataRow', 0);return false;">ID</th>
<th id="parTypeHdr">TYPE</th>
<th id="dateSubmittedHdr">SUBMITTED DATE</th>
<th id="priorityLevelHdr">PRIORITY LEVEL</th>
<th id="issueDescHdr">ISSUE DESC</th>
</tr>
</thead>
<tbody>
<tr class = "dataRow" w3-repeat="retdata">
<td>{{PAR_ID}}</td>
<td>{{PAR_TYPE}}</td>
<td>{{DATE_SUBMITTED}}</td>
<td>{{PRIORITY_LEVEL}}</td>
<td>{{ISSUE_DESC}}</td>
</tr>
</tbody>
</table></div>
<div id="conditionalContent"><h2>Loading.......</h2></div>
</body>
</html>
So what I was trying to do was use w3.http() to get a JSON string from my unmodified data source (classic ASP page still) and then use the w3.displayObject() with my retrieved JSON object to populate a table with rows. I tried a similar scenario previously and was met with very poor performance but in the source I examined, I didn't see any obvious bottlenecks so I thought I'd try again. My web request takes ~9 seconds to query 750K worth of data. I used this object to retest w3.displayObject and was surprised. Using the above placeholders, which are simply
{{attribute names}} of my parsed JSON object, I was able to load 677 rows with 5 columns per row in just a few hundred milliseconds. So for a simple grab and go type operation, I would rate this as acceptable. So then I tried to use the w3.sortHTML() function to sort the rows by the first column, an integer value. This was met with problems when I got it working, it took ~30 seconds to work and it froze my browser a couple times. And then when it did finally print the "sorted" rows, they weren't sorted by integer or numerical value but rather by strings so a value of "100" was followed by the value "11" because the first char matches but for the second, the "1" alphachar is higher than "0". I did a little more tooling and I re-read the source to confirm no-joy; as this sort functionality would be a big help to me. I found out that while W3.JS support sorting lists as well as tables, it does a modified version of a bubble sort and does so by deleting and inserting rows/items in the DOM, not in memory. So I'm going to confirm my prior assertion that this functionality is not a practical sorting implementation.
I mentioned above that JS Array objects have a sort function you can provide a +, 0, or - int value to. To compare, I wrote my own function to sort a table. It works by sorting an array of arrays (each table row column "td"'s innerHTML being put in an Array and then pushed to a containing Array. Then I wrote a modified bubble sort on the first column (my ID column.) I ran into a few problems and it took me 2+ hours to get right. Firstly, it took me 3 - 4 tries to correctly deep copy an array. This is what I thought should do the trick but it would seem not.
var tempArray = new Array(dataObj.sortElements[i]);
What did work was this:
var tempArray = dataObj.sortElements[i].slice();
Then I cut away the array I was moving using this:
dataObj.sortElements.splice(i, 1);
Finally, I used splice again to insert the array in it's proper place while not cleaving any indexes. I also used push to tack it on the end if it encountered no greater compare value. My sort function worked when sorting values in an Ascending direction but, going off sheer memory from my data structures course, I couldn't remember everything I needed to quickly modify for a search in a Descending direction. So I cheated and just sorted Asc and then used array.reverse() to get what I needed. I timed my custom function and worst case it took 56 milliseconds to sort and best case it took .05 milliseconds (the closer to sorted the table is, the better it does.) Then I tried the array.sort() function for comparison.
function compareFn(a, b){
if(parseInt(a[0]) > parseInt(b[0]))
return 1;
else if(parseInt(a[0]) < parseInt(b[0]))
return -1;
else
return 0;
}
//Invoked like so.....
dataObj.sortElements.sort(compareFn);
Worst case the built in function took 4.5 MS and worst case 2.5. So, if you can't sort the data using your database engine, save yourself the time and trouble and just use array.sort() for consistent results on anything other than data of an overwhelming volume.
As far as the utility functions of W3.JS, I implemented Vanilla JS solutions in an adjacent function and their util functions seemed to work as advertised, though some seemed repetitious (e.g. addClass, removeClass, toggleClass. Just have a param for toggleClass?)
So w3.http, with a little customization, seems to work adequately and w3.displayObject is also worth checking out. The last thing that caught my attention was the w3.filterHTML() function with the following signature.
w3.filterHTML('#responseTable', '.dataRow', this.value)
It's the unique selector of your table/list, the selector of the tr or ul element and the value to filter against (the value of a text input in this case.) After some tinkering, I was able to filter the data that I retrieved using w3.http and displayed using w3.displayObject(). This function iterates through all rows and all cells of rows to see if the match value is contained in the text of the field. No way to force a numeric comparison but the response was snappy with no discernable lag. So for my actual final conclusion, this library does provide some functionality that's at least worth benchmarking for yourself and it is very light but it isn't going to liberate you from JQuery. That said, you can see in my example that most things W3.JS can do can also be down in good ol' fashioned Vanilla JS. JQuery has been a dependency for just about every web application for the past decade and change but what do you do if you inherit a web app that references an outdated version of JQuery that you can't simply replace? This happened to me on my most recent web application project and I had to learn how to do most JQuery functions with regular JavaScript. It really wasn't that hard, it liberated me from yet another external dependency and, dare I say it, some of it was kinda fun. So try it yourself. Even if you don't use it, you may discover something helpful to archive for later use. Cheers!
W3.JS, which appears to be at least a partial attempt to compete with jQuery.
It does cover the same basic areas as jQuery. i.e. it is a generic library of DOM helper functions with added Ajax.
I was having trouble even finding information on it from anyone other than them.
That is because it is their library (taking their approach of "Slap W3 at the start of the name and hope people associate it with the W3C" to extremes) and practically nobody else is bothering with it.
W3Schools does appear to have at least some propensity to promote semi-abandonware as the next great thing. Is that what this is?
It does appear so, but that's speculating on the future.
Is this library actually used anywhere?
Nowhere major. Some people who are stumbling across W3Schools and making their first steps on the authoring for the WWW by learning from them are using it. Questions about it crop up on Stackoverflow from time to time.
Does anyone know its history (especially its release history)
The download page has some information.
It includes the rather unhelpful statement W3.JS is free to use. No license is necessary (which is exceptionally vague; free software licenses exist for a reason).
It also has a change log at the bottom.
There is no sign of a version control repository anywhere.
and if this is actually going to be developed into something that would actually be worth considering using?
Opinion, so no comment.
w3.js = tiny, powerful, intuitive
Looks like someone did what we all do every now and then: implement a smaller subset of a formerly existing useful framework and provide only those functions that 95% of the projects really use. That is,
Add/remove classes, styles, HTML elements
Ajax communication
Model-based HTML iterator (lists)
Also there's sorting which is very useful and straightforward: you take one look and use it right away. It just works. That's what I love about w3.js - that, and the size, which seems to be 13k uncompressed-unminified. I wouldn't even bother to minify it.
I'm absolutely a fan of jQuery; it changed the way we think, became a de facto standard, and for a reason. But today most of the Sizzle part is implemented in the browser itself so the main advantages are available without jQuery.
I'm not sure why you want to ask this question, exactly; if you are concerned that jQuery is somehow inadequate, don't be: jQuery is a brilliant library and it will continue to be a part of the JS community for a long, long time.
W3Schools markets themselves as an easy-to-pick-up resource for brand new programming students, hence the cheerful coloring scheme on their site and the simplified language used in their articles. They are probably trying to cater to users who feel intimidated by the complexity of jQuery. Whether this attempt will be successful though, I cannot tell.
W3.js is a small, easy to troubleshoot helper library that has trimmed-back functionality. I use it in quick, toss-together apps because I find it easier to troubleshoot and document and it is easier to approach for people that are not familiar with jQuery's extensive feature set. It's kind of like a non-optimized, "culture-free" jQuery in that it depends very little on tribal/cultural knowledge to be easy to understand.
I don't see W3schools going anywhere, it's frequented by an endless supply of novice developers which seems to be the target for its w3.css and w3.js. If you do use it, I'd probably shy away from linking it in from their site/CDN. Probably best to have a local copy else risk your site becoming non-functional if/when the file become unavailable. I also wouldn't trust it in large-scale production applications just because as others have mentioned, it's likely not used enough by people that would notice problems with its code. I know I only use it for pet projects and honestly, I've never dug through the source. (I may now that I think about this though)
First, I know that there is a few similar questions here but after reading probably a dozen I didn't quite find what I'm looking for, as I'm new to JS and Ajax requests.
So, let me explain what I have and what I want:
I have this small webapp doing a search on an API that returns a JSON with a maxResult of 40 items. It can be only 1 item but most of the time is more.
Right now I have everything working and appending the result in the front end, but now I want to make a pagination as 40 results are to much.
I would like to have 5 items per page, and the pages should be ajax, I don't want to reload the entire website, just page inside a container.
EDIT: check the final code w/o pagination here:
https://github.com/fleps/gbooks-webapp/blob/master/src/js/app.js
Ok, so, when searching I saw a few examples where after appending everything to the HTML a script ran and create the pagination by splinting the content, but I'm not sure that's the right way. Shouldn't the correct approach be to split the result on the $.each part and store it and append it to the HTML just when the user requests the next/n page? Wouldn't make the application lighter/faster?
Either way I don't know how to do it as I'm new on all this.
I looked a few jQuery pagination plugins but really didn't understand how to use them with my code and what's the best approach thinking about good JS practices and performance.
Btw I'm using jQuery and Bootstrap 4 UI so I would like to use the pagination UI from them if possible.
Sorry if this is too long and thank's for any help =)
Here is how it could be :
const itemsPerPage = 5;
let items = null;
renderWithPagination(start, items) {
let divs = [];
for(var i=start; i<data.length; i++) {
divs.push(`
<div class="book">
// MyHTML+ Vars
</div>`);
});
}
const prevStart = start - itemsPerPage;
const nextStart = start + itemsPerPage;
let pagination = '';
if(prevStart >= 0) {
pagination += `<button id="prev" data-start="${prevStart}">Previous</button>`;
}
if(nextStart >= 0) {
pagination += `<button id="next" data-start="${nextStart}">Previous</button>`;
}
searchResult.innerHTML = divs.join('') + pagination;
}
...
success: function (data) {
items = data.items;
renderWithPagination(0, items)
}
...
$(document).click('#prev,#next', function() {
renderWithPagination(+$(this).attr('data-start'), items);
});
I created an action using Action wizard in Acrobat Pro X.
A JavaScript is running when action started.
What this Javascript Do? suppose 100 page in opened pdf, this javascript extract all as seperate pages and rename it as user defined style.
e.g. Hello_001.pdf,Hello_002.pdf,Hello_003.pdf,Hello_004.pdf,... and so on,
i want a Custom Menu which target this action to execute.
It seems to me that you can find your answer in the link you gave. Important is that your script/function works correctly. So test it before in the js console. However here an example, where you can replace the script with yours. Regards, Reinhard
EDIT: (25.11.) Thought can use it by myself, but then I want to have it sortable. So I introduced leading zeros in the extract filename -> function changed.
//Save this in the ....\Acrobat\Javascripts\ program or user directory
// as whatever.js to load as Add-In
//-> create a submenu as first position under "Edit"
app.addSubMenu({ cName: "Specials", cParent: "Edit", nPos: 0 });
//-> now create a Menuitem for the function you will execute
app.addMenuItem({ cName: "Extract all Pages to file", cParent: "Specials", cExec: "extractAll()"});
//-> state your function (extract all Pages with leading zeros)
extractAll = app.trustedFunction(function (){
var re = /.*\/|\.pdf$/ig;
var filename = this.path.replace(re,"");
var lastPage = this.numPages;
var lz = Math.pow(10, (lastPage).toString().length); //calc full decimals (10,100,..)
app.beginPriv(); // Explicitly raise privilege
for ( var i = 0; i < lastPage; i++ ) {
var zPgNo = (lz + i+1).toString().slice(1); //calc actual, cut leading 1 = zerofilled PgNo
this.extractPages({
nStart: i,
nEnd: lastPage -1,
cPath : filename + "_page_" + zPgNo + ".pdf"
});
};
app.endPriv();
app.alert("Done!");
})
You can't trigger an Action to run from a menu item. However, you can create an application level JavaScript that contains a function that does what you want and then call that function from either an Acrobat Action or a custom Menu Item or both. The answer from ReFran shows how to add the custom menu item.
Not on Chrome, but on Firefox the browser just get freeze every time I make an ajax request.
Here's the deal...
The ajax request receive a huge html, where the length is more than 75,000.
<div> ... <table> ... etc ... </table> ... </div>
So I start to use replace to get something better:
var html = data.replace(/\r?\n|\r/g, '').replace(/\s{2,}/g, ' ')
Than I got 55,000 that is not enough.
So I've been searching but until now I got nothing that can help.
Here's what I tried:
1.
asyncInnerHTML(html, function(fragment){
$(tab).get(0).appendChild(fragment); // myTarget should be an element node.
});
2.
var node = document.createTextNode(html);
$(tab).get(0).innerHTML = node;
3.
$(tab).get(0).innerHTML = html;
4.
$(tab).append(html);
5.
$(tab).html(html);
The only thing that was fast what the second one, where the javascript add the nodeContent, of course that was not what I want, because I need the HTML rendered and not the html in text/string form.
I hope that someone could help me.
Anyway, thanks.
Here's a piece of code that parses out the rows from your table HTML and then adds them one at a time to give the browser more time to breathe while parsing your HTML. This parsing logic is specific to your HTML and makes some assumptions about that HTML:
function addLargeHTML(parent, h) {
var d = document.createElement("div");
var pieces = extractRows(html);
d.innerHTML = pieces.core;
var tbody = $(d).find("tbody");
$(parent).append(d);
var cntr = 0;
function next() {
if (cntr < pieces.rows.length) {
tbody.append(pieces.rows[cntr]);
++cntr;
setTimeout(next, 1);
}
}
next();
}
function extractRows(h) {
var body;
var h = h.replace(/<tbody>(.*?)<\/tbody>/, function(match, p1) {
body = p1;
return "<tbody></tbody>";
});
var rows = body.match(/<tr.*?<\/tr>/g);
return {core: h, rows: rows};
}
You can see it working in this jsFiddle (select the "Add Row by Row" button): http://jsfiddle.net/jfriend00/z7jn4p12/.
Since I could not reproduce your original problem in Firefox, I can't really say whether this would fix what you saw or not. But, it does break the HTML up into smaller pieces so if that was really the problem, this should help.
The Skype Toolbar for Firefox is an extension that detects phone numbers in web pages, and re-renders them as a clickable button that can be used to dial the number using the Skype desktop application.
So, when the HTML is rendered, the skype extension try to find shit at my code making the browser stop work for a moment.
Thanks for all help.