I understand that this question has been asked many a times and the general consensus is that spam-bots will always figure out a way to harvest emails eventually so it is a lost cause. But I want a newly created email visible on a page that I created and I want at least something that protects it from spam-bots. Here is a simple JavaScript technique I wish to use:
$(document).ready(function() {
setEmailAddress("abc#xyz.com");
});
function setEmailAddress(emailValue) {
$("#spanTest").append($("<a>").attr("href", "javascript:location='mailto:" + obfuscateString(emailValue) + "';void 0").text(obfuscateString(emailValue)));
}
function obfuscateString(plaintext) {
var obfuscated = "";
for (var i = 0; i < plaintext.length; i++) {
obfuscated += "\\u00" + plaintext.charCodeAt(i).toString(16);
}
return obfuscated;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="spanTest"></span>
Here are the questions:
If the email abc#xyz.com is picked up from a database and passed to the method setEmailAddress then since the html crawled by the bot in the first place will not find an email, do I still need to obfuscate it on the page?
You will notice that the link text of anchor is not obfuscated. If I need to obfuscate that part too, is it possible to achieve that without using eval?
Note: I already have a Contact form on the page that uses reCaptcha but this query is for when I wish to have an email visible on the page as well.
EDIT:
After reading the comments, I think I need to emphasize on the question no. 2 above. Please see above updated code.
As you can see, I am trying to hide/obfuscate the link text as well. I understand that I need to document.write the produced result by the method obfuscateString but using eval for that is not recommended. Is there a way to obfuscate this part of text too?
So I ended up using the following:
$(document).ready(function() {
setEmailAddress("abc#xyz.com");
});
function setEmailAddress(emailValue) {
$("#spanTest").append($("<a>").attr("href", "javascript:location='mailto:" + obfuscateString(emailValue) + "';void 0").html("<img src='https://i.stack.imgur.com/CFrNW.png' />"));
}
function obfuscateString(plaintext) {
var obfuscated = "";
for (var i = 0; i < plaintext.length; i++) {
obfuscated += "\\u00" + plaintext.charCodeAt(i).toString(16);
}
return obfuscated;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span id="spanTest"></span>
That is, I changed the part in the code for the link text.
From this:
.text(obfuscateString(emailValue))
to
this:
.html("<img src='https://i.stack.imgur.com/CFrNW.png' />")
It will render an image (of the email) in place of text. Your suggestions are still welcome.
I am trying to create a simple clipboard extension. I have 6 textarea objects that are used as copy/paste platforms. I want these objects to 'remember the text' for future uses (even after the extension is closed).
I this is how the textarea object was built like:
<table>
<tr>
<td>
<textarea id="container_1" class="container" rows="4" cols="50" value="" focusout="SetTextBoxString(1)"></textarea>
</td>
<td>
<textarea id="container_2" class="container" rows="4" cols="50" value="" focusout="SetTextBoxString(2)"></textarea>
</td>
</tr>
(...)
notice that the id is container + the number of the object (goes on until 6)
in the JavaScript side, I use the onload event to loop through all of these objects and get from the data from the global storage and put it in the textareas. For the input, I use the SetTextBoxString() object to "send" whats in that field to the global storage. here is the js:
var texts = [];
Load_func()
{
for (var i = 1; i <= 6; i++) {
chrome.storage.sync.get(["Txt_" + index], function (items) {
var obj = JSON.parse(items);
var txt = "Txt_" + i
texts.push(obj.txt)
document.getElementById("container_" + i).innerHTML = texts[i]
});
if (!texts[i])
{
document.getElementById("container_" + i).value = "add"
}
}
}
SetTextBoxString(index)
{
var sorcestring = "Txt_" + index;
chrome.storage.sync.set({ sorcestring : document.getElementById("container_" + index).innerHTML }, function () {
});
}
It's working fine, but when I refresh the page the text disappears. What have I done wrong?
I know it's a long question, I have done everything I can to make it shorter, no luck. I really appreciate if you will help me. thank you in advance!
sources:
How can I save information locally in my chrome extension?
You can move to using JQuery if you want, but some people believe its rather useless, I created this code in JQuery a while back for a similar project to yours, but more of a "notebook"
I cant seem to get this code to "successfully" work 100% if I use normal javascript, so unfortunately unless you want to hook big chunky ol' JQuery to your project, this answer isnt very useful.
Anyways, this code will auto adapt to how many "Inputs" you have, it saves their data and then binds it to a local storage. Im new to Extensions too, but if i had to guess why your current code isnt working, its possible your extension is trying to save the data so some unknown URL, as local storage is mostly based on websites alone, and cant be accessed by other websites (Security reasons obviously).
You can adjust this with your current code to allow it to autosave based on the change of the textarea, like you already have, but for now, its saved by the activation of a button, as seen below.
<button id="saveBtn">Save Text</button>
$(document).ready(function () {
var savesbtn = document.getElementById("saveBtn");
//FILL TEXT AREAS WITH NOTES
for (var i = 1; i < 11; i++) {
$("#container_" + i).val(localStorage.getItem("textCopy" + i)); /* Most of this simply adds a
1/2/3/4 etc if your ID is so, and saves it under that number, henceforth auto-adjusting per textarea,
henceforth only requiring 1 save, instead of many. */
}
function saveNotes() { // Saves the current value of the inputs.
// Save data to localstorage
for (var i = 1; i < 11; i++) {
localStorage.setItem("textCopy" + i, $("#container_" + i).val());
}
};
savesbtn.addEventListener("click", saveNotes);
});
If this still fails to load from local storage, your best bet is to try an alternate form of storage, be it, SQL or some other form.
Also heres a good example of how I used this (sorry if it doesnt turn out well, I havent set the dimensions correctly for every screen type, and so far it really only looks good on my screen.): https://codepen.io/SkylerSpark/pen/KjodVe
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)
I am completely new to drupal and still struggling with the structure (also I have no experience in PHP, I've mostly worked with C and matlab ealier).
I am writing a page that makes calls/queries (using javascript) to parse.com, this works as long as I manually enter the UUID. How can I get it from the drupal-database (MySQL) to my webpage/javascript the easiest way?
Please tell me if I left out important stuff, I am an engineer and have done quite a bit of programming, but never any web-development so I know very little about all this.
Any help appreciated.
I suppose that you have connected your JS file and you use Drupal behavior:
So to send a php variable value to js you need:
drupal_add_js(array('myModule' => array('my_var' => $my_var)), 'setting');
and to access it in JavaScript:
Drupal.behaviors.example_behavior = {
attach: function(context, settings) {
// Check if the variable exist.
var dSettings = Drupal.settings;
if (dSettings.myModule != undefined) {
x = (dSettings.myModule != undefined) ? dSettings.myModule.my_var : '';
if (terms.length && x != '') {
// Variable exist.
}
}
}
}
Source
I am using code in an aspx page (javascript) that is displayed using the sharepoint 2010 UI framework dialog functions.
However, it throws an error. I can't get at the exact details. But here's the code
function DoReject(rejectype) {
rejecttype = rejectype;
this.clientContext = new SP.ClientContext.get_current();
var targetList = clientContext.get_web().get_lists().getByTitle('Applications');
var qs =window.location.search.substring(1);
var arrs = qs.substring(0,qs.indexOf('&',0)).replace('arr=','').split(',');
for (var i = 0; i < arrs.length;i++) {
k = arrs[i];
if (k != null && k != '') {
try {
this.applicant = targetList.getItemById(k);
applicant.set_item('ApplicationStatus', 'REJECTED');
applicant.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.doNothingReject), Function.createDelegate(this, this.rejectError));
this.applicant = targetList.getItemById(k);
clientContext.load(applicant, 'EMail', 'CrisDBID', 'ApplyJobTitle', 'JobRef', 'BrandId');
clientContext.executeQueryAsync(Function.createDelegate(this, this.DoRejectSuccess), Function.createDelegate(this, this.rejectError2));
}
catch (e) {
alert(e);
}
}
}
}
Note i haven't included the success / error methods, as they are superfluous in this. And the ids return correctly - they are passed into the query string. So the variable k is definitely the id of the list item.
In the error event rejectError, I use the signature
rejectError(e)
Does anyone know how to get the error details from the parameter / whats wrong with the code?
is it possible to call list operations on a page that isn't the native list page using the javascript object model?
thanks in advance
M
What browser do you get the error in? Is the error consistent between browsers? I would recommend that you debug the javascript and look at the variables at the line before it fails to see what's going on.
On a side note the first snippet you pasted looks like a standard train-wreck so if the code fails there it's likely one of these are undefined (if clientContext, get_web() or get_lists() does not return a value). I don't know anything about Sharepoint UI framework so "list operation" etc doesn't say much to me.