Piwik Pro Variable that counts words in <p> - javascript

So I'm trying to make a variable in Piwik Pro that counts words in all pages on my website withing a and gives me back a plain number. So far I came up with this but debug mode gives me an undefined in return.
function getWordCounts(nodeList) {
var wordCount = 0;
var totalWords = getWordCounts(document.querySelectorAll('p'));
for ( var i = 0; i < nodeList.length; i++ ) {
wordCount += nodeList[i].textContent.trim().split(' ').length;
}
return totalWords;
}
Tried using debug mode tested the tag without a function but with a simple number this worked. But cannot get the number to be the actual words in the

Related

Declaring and setting variable in JavaScript

I'm currently using the following JavaScript in a Google Chrome Extension to automate the 'add to cart' process for purchasing sneakers on nike.com;
var size_i_want = "11";
function fRun()
{enter code here
// Select size option.
var sizesList=document.getElementsByName("skuAndSize")[0];
for(var i=0; i<sizesList.length; i++)
{
if(sizesList.options[i].text.trim() == size_i_want)
{
sizesList.selectedIndex = i;
}
}
var aButtons = document.getElementsByTagName("button");
for(var i = 0; i < aButtons.length; ++i)
{
if(aButtons[i].className.indexOf("add-to-cart") > -1)
{
aButtons[i].click();
}
}
}
function fTick()
{
if(document.getElementsByName("skuAndSize")[0] != undefined)
{
setTimeout("fRun()", 600);
//fRun();
}else{
setTimeout("fTick()", 300);
}
}
setTimeout("fTick()", 300);
This script works perfectly for nike.com in the States, however does not work correctly for nike websites in other countries like the UK and Sweden.
As you can probably tell I am new to JavaScript and am still researching high and low to understand the language. However I understand this comes down to the fact that
var size_i_want = "11";
value is set as an integer (number) however on the Nike UK website the node that this affects contains letters, for example "UK 10.5".
Would somebody be able to help me declare a new variable and set it's value so that it contains both letters and numbers? I also have a feeling that this will impact the script as well, so help around that area is much appreciated too.
In javascript, variables are not typesafe, so you don't declare them as integers or strings. Coincidently:
var size_i_want = "11";
This is already a string. So you should already be able to add letters to it. Just change it to:
var size_i_want = "UK 10.5";
As millerbr already said javascript is not type safe.
The mix of letters and numbers should not have impact on the script, because
size_i_want = "11";
size_i_want = "UK 10.5";
are both strings.

Javascript array length through user input

I have a problem in Javascript I want to make a form which have one input text field and one button when I click on the button window.prompt is called.
It will prompt depend upon my array length but I want array length get through input text field when I write 10 it will prompt 10 times when I write 2 it will prompt 2 times.
How can i write this type of query?
I tried this code but its not working.
words = new Array (4);
function a() {
for ( k = 0 ; k < words.length ; k = k + 1 ) {
words[ k ] = window.prompt( "Enter word # " + k, "" ) ;
}
}
Maybe you forgot to call your function a().
Some remarks about your code:
You don't have to specify an initial array size, e.g. words = [] or words = new Array() is enough.
Also k=k+1 is usually written as k++.
A remark about asking questions:
Use punctuation to make sentences! Your whole question is one sentence.
Hopefully it's just the snippet of code but I hope you are using var somewhere to declare all those variables.
Otherwise this should do the trick, however not sure what you are trying to achieve but this sounds like a bad user experience.
Here is the jsffidle http://jsfiddle.net/R2bCz/1/
function Handler(event) {
var count = event.target.value;
var i = 0;
var words = [];
var word;
for (; i < count; i++) {
word = window.prompt("Enter word # " + i, "");
words.push(word);
}
}
$("#multi").on("change", Handler);

Code works in code tester but not in adressbar

If i input my code here:
http://writecodeonline.com/javascript/
It works as intended, but if i input it in my adressbar with "javascript:" infront the alert box just shows the original string.
What is going wrong?
var string = "Sunshine & Whiskey";
var stringFeedback;
var i = 0;
string = string.replace("&","%26");
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
alert(string);
Edit:
If i input in my Chromium console it works fine, but if i make a bookmark with the same code it doesn't.
Any suggestions on how to fix that?
Try initialising i before the loop:
var i = 0;
do {
stringFeedback = string.search(/[ ]/);
string = string.replace(/[ ]/,"%20");
i += 1;
} while (i < 5);
Whatever, I recommend you use your browser console to test these code snippets.
You can use
encodeURIComponent("Sunshine & Whiskey");
That returns
Sunshine%20%26%20Whiskey
without any loop, it's a native method of javascript that is supported by all Browser.
MDN documentation

Google Apps Script random string generating

i am new to Google apps script, i want to create string of random characters in the code given below in variable body2.
function myfunction() {
var files = DriveApp.getFiles();
while (files.hasNext(`enter code here`)) {
Logger.log(files.next().getName());
}
var recipient = Session.getActiveUser().getEmail();
var subject = 'A list of files in your Google Drive';
var body1 = Logger.getLog();
var body2;
for(var i=0;i<6;i++)
{
body2[i]=BigNumber.tostring("Math.floor(Math.random()*11)");
}
body=body1+body2;
MailApp.sendEmail(recipient, subject, body);
};
but when i run this function, it says "TypeError: Cannot find function tostring in object 0. (line 12, file "Code") " i can't understand how to solve this error?
Why we have to multiply random by 11 , can it be multiplied with any integer number?
what if i want that string in only capital letters.!
Some other question
1) i don't have enough knowledge of JavaScript, is it good to learn GAS directly?
2) i can't find proper written material or documentation for GAS , the material available at Google's official site is seems to be updating time by time , what to do then ? any link to material would help me .!
I guess I just figured
function randomStr(m) {
var m = m || 15; s = '', r = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (var i=0; i < m; i++) { s += r.charAt(Math.floor(Math.random()*r.length)); }
return s;
};
Hope someone finds it helpful.
As for a random string use this its better:
Math.random().toString(36). 36 is the base thus will use letters and numbers in the string.
As for gas documentation, the official page is pretty complete. It changes because it constantly improves and adds new services.
I have this charIdGeneration() in my GAS library
function charIdGenerator()
{
var charId ="";
for (var i = 1; i < 10 ; i++)
{
charId += String.fromCharCode(97 + Math.random()*10);
}
//Logger.log(charId)
return charId;
}

Split Content on CKEDITOR and get HTML of each part

I have a CKEDITOR and i am trying to split the content in n parts, the user indicates how many parts he wants, by puting the cursor on a specific position of the CKEDITOR, after that with an option at the context-menu the user selects "Split Block", this inserts a tag in HTML:
the user can do this n times in CKEDITOR, it is to indicate how many blocks the user wants to split the content, each hr inserted is one block.
So when the user finish, click at the context-menu "Process Split", this action should execute and split the content in n parts.
this is my code to split the content:
var index = 0;
var tmpItem = null;
var ranges = new Array();
var elements = editor.document.getElementsByTag( 'hr' );
for ( var i = 0; i < elements.count() ; i++ )
{
var item = elements.getItem( i );
ranges[index] = new CKEDITOR.dom.range( editor.document );
if(tmpItem!=null)
ranges[index].setStart(tmpItem, CKEDITOR.POSITION_BEFORE_START);
else{
ranges[index].setStartAfter(editor.document.getBody().getFirst());
}
if(item.hasClass('split-end')){
ranges[index].setEnd(item, CKEDITOR.POSITION_BEFORE_START);
ranges[index].select();
index++;
var sel = editor.getSelection();
var ran = sel.getRanges();
var el = new CKEDITOR.dom.element("div");
for (var j = 1, len = ran.length; j < len-1; ++j) {
el.append(ran[j].cloneContents());
}
console.log( el.getHtml() );
}
tmpItem = item;
}
The problem is: how to select from begining of the document to the first HR and so on.
Thanks a lot, i have been trying to do this for over a week, and i dont know what else try.
I'm not analyzing your code carefully, because I don't even know what you're trying to achieve. But here're some notes that can help you.
You use CKEDITOR.dom.range#setStart and #setEnd improperly. You should utilize setStartAt and setEndAt. Methods you used take offset as a second argument, not a position.
To select content from the beginning of the document to the first HR (including it):
var range = new CKEDITOR.dom.range( document );
range.setStart( document.getBody(), 0 );
range.setEndAt( hr, CKEDITOR.POSITION_AFTER_END );
range.select();
In your code I see that you're trying to select many ranges - it won't work this way. AFAIK only Firefox handles multiple selection, but I don't know if CKEditor does. If yes, then CKEDITOR.dom.selection#selectRanges is what you need. However, if you're only trying to extract contents of ranges then you don't have to select them first.

Categories