Jquery Latter Shuffle - javascript

I'm try to animate (Shuffle) Pre-Typed Text using This plugin Text Shuffle Plugin
But issue is, this is only work when we type in text box. I want to do that when page load.
Here is its Online demo link. DEMO
Here Is Fiddle Link. Fiddle
Unfortunately I am unable to create its fiddle. I just want the onload effect on pre define 's ID
JS Code
$.fn.shuffleLetters = function(prop){
var options = $.extend({
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "" // Use this text instead of the contents
},prop)
return this.each(function(){
var el = $(this),
str = "";
if(options.text) {
str = options.text.split('');
}
else {
str = el.text().split('');
}
// The types array holds the type for each character;
// Letters holds the positions of non-space characters;
var types = [],
letters = [];
// Looping through all the chars of the string
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
el.html("");
// Self executing named function expression:
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at this position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
el.text(strCopy.join(""));
setTimeout(function(){
shuffle(start+1);
},1000/options.fps);
})(-options.step);
});
};

Related

How to underline charachters in InDesign with JavaScript?

I started writing this piece of code for InDesign to underline all letters except from the one with descendants, and added a dialog window to chose stroke and offset of the line.
Now I have two problems:
the program underlines all letters
the stroke and offset won't change
I'm a beginner in Javascript and it's the first time coding for InDesign. Does someone have a clue? Thank you!
// UNDERLINE ALL BUT NO DESCENDANTS
//Make certain that user interaction (display of dialogs, etc.) is turned on.
app.scriptPreferences.userInteractionLevel = UserInteractionLevels.interactWithAll;
if (app.documents.length != 0){
try {
// Run script with single undo if supported
if (parseFloat(app.version) < 6) {
main();
} else {
app.doScript(main, ScriptLanguage.JAVASCRIPT, undefined, UndoModes.ENTIRE_SCRIPT, "Expand State Abbreviations");
}
// Global error reporting
} catch ( error ) {
alert( error + " (Line " + error.line + " in file " + error.fileName + ")");
}
}else{
alert("Open a document first before running this script.");
}
///MAIN FUNCTION
function main(){
if(app.selection.length != 0){
myDisplayDialog();
}
}
//INTERFACE
function myDisplayDialog(){
//declare variables
//general
var myDoc = app.activeDocument;
var mS = myDoc.selection;
// dialog
var myDialog = app.dialogs.add({name:"Underliner"});
var myLabelWidth = 70;
with(myDialog.dialogColumns.add()){
with(borderPanels.add()){
with(dialogColumns.add()){
with(dialogRows.add()){
staticTexts.add({staticLabel:"Stroke:", minWidth:myLabelWidth});
staticTexts.add({staticLabel:"Offset:", minWidth:myLabelWidth});
}
}
with(dialogRows.add()){
staticTexts.add({staticLabel:""});
var myStroke = measurementEditboxes.add({editValue:1, editUnits:MeasurementUnits.points});
var myOffset = measurementEditboxes.add({editValue: 15, editUnits:MeasurementUnits.points});
}
}
}
var myResult = myDialog.show();
if(myResult == true){
var myStroke = myStroke.editValue;
var myOffset = myOffset.editValue;
myDialog.destroy();
underline(mS,myStroke,myOffset);
}
else{
myDialog.destroy();
alert("Invalid page range.");
}
}
//REAL FUNCTION
function underline(charList,stroke, offset){
var len = charList.length;
const doNotUnderline = ['g','j','p','q','y'];
for (var i=0; i < len; i++){
try{
var myChar = charList[i];
//console.log(typeof myText);
if (includes(myChar, doNotUnderline) == false)
{
myChar.underline = true;
myChar.underlineWeight == stroke;
myChar.underlineOffset == offset;
} else {
myChar.underline = false;
}
}catch(r){
alert(r.description);
break;
}
}
}
//function to know if char is in array
function includes(elemento,array)
{
var len = array.length;
for(var i=0; i<len ;i++)
{
if(array[i]==elemento){return true;}
}
return false;
}
Try these changes in the function underline():
//REAL FUNCTION
function underline(words,stroke, offset) { // <------ here 'words' instead of 'charList'
var charList = words[0].characters; // <------ here get 'characters' of the 'words'
var len = charList.length;
const doNotUnderline = ['g','j','p','q','y'].join(); // <------- here '.join()'
for (var i=0; i < len; i++){
try{
var myChar = charList[i];
// if (includes(myChar, doNotUnderline) == false) // <----- no need
if (doNotUnderline.indexOf(myChar.contents) < 0) // <------ 'indexOf()' instead of 'includes()'
{
myChar.underline = true;
myChar.underlineWeight = stroke; // <------- here '=' instead of '=='
myChar.underlineOffset = offset; // <------- here '=' instead of '=='
} else {
myChar.underline = false;
}
}catch(r){
alert(r.description);
break;
}
}
}
Probably there can be another improvements as well. It's need additional researches. But if you change these lines it should work to a degree.
And there is one little thing that improves user experience greatly: to keep last used values in the input fields. It can be done pretty easy, let me know it you need it.
Update
Here is the way I'm using to store and restore any preferences of my scripts.
Add somewhere at the start of your script these lines:
// get preferences
var PREFS = { stroke: 1, offset: 15 }; // set default prefs
var PREFS_FILE = File(Folder.temp + '/underline_prefs.json'); // the file with preferences
if (PREFS_FILE.exists) PREFS = $.evalFile(PREFS_FILE); // get the prefs from the file
Now you can use the global values PREFS.stroke and PREFS.offset anywhere you want. In your case they go here:
with(dialogRows.add()){
staticTexts.add({staticLabel:""});
var myStroke = measurementEditboxes.add({editValue:PREFS.stroke, editUnits:MeasurementUnits.points});
var myOffset = measurementEditboxes.add({editValue:PREFS.offset, editUnits:MeasurementUnits.points});
}
This way script will get the stroke and weight from the file underline_prefs.json that will be stored in the standard temporary folder of current user.
Final step is to save the values back into the file after the script got them from the dialog window.
I'd put this piece of code here:
if (myResult == true) {
var myStroke = myStroke.editValue;
var myOffset = myOffset.editValue;
myDialog.destroy();
underline(mS, myStroke, myOffset);
// save preferences here
PREFS.stroke = myStroke;
PREFS.offset = myOffset;
PREFS_FILE.open('w');
PREFS_FILE.write(PREFS.toSource());
PREFS_FILE.close();
} else {
myDialog.destroy();
alert("Invalid page range.");
}
Voilá. Now don't need to type the values every time they differ from default ones.

How to highlight first occurrence of a string in a UIWebView?

I use the javascript code below to find all occurrences of a string in UIWebView:
UIWebViewSearch.js:
var uiWebview_SearchResultCount = 0;
/*!
#method uiWebview_HighlightAllOccurencesOfStringForElement
#abstract // helper function, recursively searches in elements and their child nodes
#discussion // helper function, recursively searches in elements and their child nodes
element - HTML elements
keyword - string to search
*/
function uiWebview_HighlightAllOccurencesOfStringForElement(element,keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
var count = 0;
var elementTmp = element;
while (true) {
var value = elementTmp.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break;
count++;
elementTmp = document.createTextNode(value.substr(idx+keyword.length));
}
uiWebview_SearchResultCount += count;
var index = uiWebview_SearchResultCount;
while (true) {
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) break; // not found, abort
//we create a SPAN element for every parts of matched keywords
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx,keyword.length));
span.appendChild(text);
span.setAttribute("class","uiWebviewHighlight");
span.style.backgroundColor="yellow";
span.style.color="black";
index--;
span.setAttribute("id", "SEARCH WORD"+(index));
//span.setAttribute("id", "SEARCH WORD"+uiWebview_SearchResultCount);
//element.parentNode.setAttribute("id", "SEARCH WORD"+uiWebview_SearchResultCount);
//uiWebview_SearchResultCount++; // update the counter
text = document.createTextNode(value.substr(idx+keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
//alert(element.parentNode);
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
}
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i=element.childNodes.length-1; i>=0; i--) {
uiWebview_HighlightAllOccurencesOfStringForElement(element.childNodes[i],keyword);
}
}
}
}
}
// the main entry point to start the search
function uiWebview_HighlightAllOccurencesOfString(keyword) {
uiWebview_RemoveAllHighlights();
uiWebview_HighlightAllOccurencesOfStringForElement(document.body, keyword.toLowerCase());
}
// helper function, recursively removes the highlights in elements and their childs
function uiWebview_RemoveAllHighlightsForElement(element) {
if (element) {
if (element.nodeType == 1) {
if (element.getAttribute("class") == "uiWebviewHighlight") {
var text = element.removeChild(element.firstChild);
element.parentNode.insertBefore(text,element);
element.parentNode.removeChild(element);
return true;
} else {
var normalize = false;
for (var i=element.childNodes.length-1; i>=0; i--) {
if (uiWebview_RemoveAllHighlightsForElement(element.childNodes[i])) {
normalize = true;
}
}
if (normalize) {
element.normalize();
}
}
}
}
return false;
}
// the main entry point to remove the highlights
function uiWebview_RemoveAllHighlights() {
uiWebview_SearchResultCount = 0;
uiWebview_RemoveAllHighlightsForElement(document.body);
}
function uiWebview_ScrollTo(idx) {
var scrollTo = document.getElementById("SEARCH WORD" + idx);
if (scrollTo) scrollTo.scrollIntoView();
}
And in my ViewController.swift file, I load the javascript file and perform a search like so:
func highlightAllOccurencesOfString(str:String) -> Int {
let path = Bundle.main.path(forResource: "UIWebViewSearch", ofType: "js")
var jsCode = ""
do{
jsCode = try String(contentsOfFile: path!)
myWebView.stringByEvaluatingJavaScript(from: jsCode)
let startSearch = "uiWebview_HighlightAllOccurencesOfString('\(str)')"
myWebView.stringByEvaluatingJavaScript(from: startSearch)
let result = myWebView.stringByEvaluatingJavaScript(from: "uiWebview_SearchResultCount")!
}catch
{
// do something
}
return Int(result)!
}
This finds and highlights all occurrences of a string within the webview, but I only want the first occurrence highlighted.
For example, with this code when I call:
highlightAllOccurencesOfString(str:"Hello")
All instances of "Hello" gets highlighted in the webview:
Hello Frank, Hello Noah
But I want this result:
Hello Frank, Hello Noah
How do I modify the javascript code to highlight only the first occurrence of a searched string?
UPDATE: I tried JonLuca's answer below but nothing got highlighted.
Any help would be greatly appreciated
The function is operating like a tree, where it checks if the element is a text node, and if not it calls itself on every one of its children.
You have to let the caller know that you found a single element to highlight, and then leave.
Also, the way this searches through it does not guarantee that what you consider is the "first" occurrence of the word will be the first occurence within the document.body tree.
Within the code, have it return true if it found a word to highlight, and false otherwise. That'll prevent it from continuing its search. Modify the js like so:
function uiWebview_HighlightAllOccurencesOfStringForElement(element, keyword) {
if (element) {
if (element.nodeType == 3) { // Text node
var count = 0;
var elementTmp = element;
var value = elementTmp.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) {
return false;
}
count++;
elementTmp = document.createTextNode(value.substr(idx + keyword.length));
uiWebview_SearchResultCount += count;
var index = uiWebview_SearchResultCount;
var value = element.nodeValue; // Search for keyword in text node
var idx = value.toLowerCase().indexOf(keyword);
if (idx < 0) {
return false;
} // not found, abort
//we create a SPAN element for every parts of matched keywords
var span = document.createElement("span");
var text = document.createTextNode(value.substr(idx, keyword.length));
span.appendChild(text);
span.setAttribute("class", "uiWebviewHighlight");
span.style.backgroundColor = "yellow";
span.style.color = "black";
index--;
span.setAttribute("id", "SEARCH WORD" + (index));
//span.setAttribute("id", "SEARCH WORD"+uiWebview_SearchResultCount);
//element.parentNode.setAttribute("id", "SEARCH WORD"+uiWebview_SearchResultCount);
//uiWebview_SearchResultCount++; // update the counter
text = document.createTextNode(value.substr(idx + keyword.length));
element.deleteData(idx, value.length - idx);
var next = element.nextSibling;
//alert(element.parentNode);
element.parentNode.insertBefore(span, next);
element.parentNode.insertBefore(text, next);
element = text;
return true;
} else if (element.nodeType == 1) { // Element node
if (element.style.display != "none" && element.nodeName.toLowerCase() != 'select') {
for (var i = element.childNodes.length - 1; i >= 0; i--) {
if (uiWebview_HighlightAllOccurencesOfStringForElement(element.childNodes[i], keyword)) {
return true;
}
}
}
}
}
}
This isn't guaranteed to be correct, or that it covers all of your use cases. However, I had it return true on the first occurrence of finding the highlighted word. It should stop executing and not highlight any other words.
Let me know if this works or not - I don't have the ability to test it right now.

Trouble excluding class from jquery function

I have a function that scrambles letters based on shuffleLetters.js. It's working great, but I can't seem to exclude classes that are nested in the class that I'm targeting.
So I want to scramble the characters in my menu items. So I give them a class of .shuffle and call the function like so:
$(function(){
var container = $(".shuffle")
container.shuffleLetters();
});
Where .shuffleLetters engages the plugin. The problem is that it's scrambling all the characters that are nested within that menu item, which I don't want.
I've read about the .not method, but can't get it to work properly.
Here's what I'm trying:
<li class="shuffle">title
<li class="no-shuffle">sub-title
</li>
</li>
then I'm writing my js like so (or every possible variation of):
$(function(){
var container = $(".shuffle").not('.no-shuffle')
container.shuffleLetters();
});
This is not working though.
Can anyone point me in the right direction here, racking my brain for hours.
as always, thanks in advance!
Edit: Here's the shuffleLetters.js:
(function($){
$.fn.shuffleLetters = function(prop){
var options = $.extend({
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "", // Use this text instead of the contents
"callback" : function(){} // Run once the animation is complete
},prop)
return this.each(function(){
var el = $(this),
str = "";
// Preventing parallel animations using a flag;
if(el.data('animated')){
return true;
}
el.data('animated',true);
if(options.text) {
str = options.text.split('');
}
else {
str = el.text().split('');
}
// The types array holds the type for each character;
// Letters holds the positions of non-space characters;
var types = [],
letters = [];
// Looping through all the chars of the string
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
el.html("");
// Self executing named function expression:
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
// The animation is complete. Updating the
// flag and triggering the callback;
el.data('animated',false);
options.callback(el);
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at thsi position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
el.text(strCopy.join(""));
setTimeout(function(){
shuffle(start+1);
},1000/options.fps);
})(-options.step);
});
};
function randomChar(type){
var pool = "";
if (type == "lowerLetter"){
pool = "abcdefghijklmnopqrstuvwxyz0123456789";
}
else if (type == "upperLetter"){
pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
else if (type == "symbol"){
pool = ",.?/\\(^)![]{}*&^%$#'\"";
}
var arr = pool.split('');
return arr[Math.floor(Math.random()*arr.length)];
}
})(jQuery);
Try wrapping text node "title" in .shuffle li within span element
(function($){
$.fn.shuffleLetters = function(prop){
var options = $.extend({
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "", // Use this text instead of the contents
"callback" : function(){} // Run once the animation is complete
},prop)
return this.each(function(){
var el = $(this),
str = "";
// Preventing parallel animations using a flag;
if(el.data('animated')){
return true;
}
el.data('animated',true);
if(options.text) {
str = options.text.split('');
}
else {
str = el.text().split('');
}
// The types array holds the type for each character;
// Letters holds the positions of non-space characters;
var types = [],
letters = [];
// Looping through all the chars of the string
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
el.html("");
// Self executing named function expression:
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
// The animation is complete. Updating the
// flag and triggering the callback;
el.data('animated',false);
options.callback(el);
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at thsi position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
el.text(strCopy.join(""));
setTimeout(function(){
shuffle(start+1);
},1000/options.fps);
})(-options.step);
});
};
function randomChar(type){
var pool = "";
if (type == "lowerLetter"){
pool = "abcdefghijklmnopqrstuvwxyz0123456789";
}
else if (type == "upperLetter"){
pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
else if (type == "symbol"){
pool = ",.?/\\(^)![]{}*&^%$#'\"";
}
var arr = pool.split('');
return arr[Math.floor(Math.random()*arr.length)];
}
})(jQuery);
$(function() {
var container = $(".shuffle span:first")
container.shuffleLetters();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<ul>
<li class="shuffle"><span>title</span>
<ul>
<li class="no-shuffle">sub-title
</li>
</ul>
</li>
</ul>

Clearing multiple timeouts properly

I've been struggling for the past day trying to solve this one.
I'm trying to get some funky text effects going, basically a glorified string creation.
It writes a line a bit like a billboard and to do it I've used setTimeout.
Thing is I would like to put it in a function so I can reuse it and call it multiple times on different elements.
The problem is that I then need to update the text maybe halfway to a new text.
To do so I clear the timeout, but unless the timer variable is outside the scope it doesn't clear.
I can't really have it outside the function because of practicality;
I'm not sure how many times it is going to be called and it just feels wrong to declare 20 time variables outside the function.
Here's the code working CORRECTLY on one item
(click multiple times to interrupt and restart)
var t;
function writeStats(str,dest) {
var options = {
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "" // Use this text instead of the contents
}
function randomChar(type){
var pool = "";
if (type == "lowerLetter"){
pool = "abcdefghijklmnopqrstuvwxyz0123456789";
}
else if (type == "upperLetter"){
pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
else if (type == "symbol"){
pool = ",.?/\\(^)![]{}*&^%$#'\"";
}
var arr = pool.split('');
return arr[Math.floor(Math.random()*arr.length)];
}
str = str.split('');
var types = [],
letters = [];
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
clearTimeout(t);
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at this position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
//el.text(strCopy.join(""));
el = strCopy.join("");
//console.log(el);
$('.'+dest).text(el);
t = setTimeout(function(){
shuffle(start+1);
},500/options.fps);
})(-options.step);
}
$(document).ready(function(){
$(document).click(function(){
writeStats('this sentence is a great one','t1');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="t1"></div>
<div class="t2"></div>
and a Fiddle script: https://jsfiddle.net/phjzfw15/
If I bring the t variable inside the function like so it doesn't work as before:
function writeStats(str,dest) {
var t;
var options = {
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "" // Use this text instead of the contents
}
function randomChar(type){
var pool = "";
if (type == "lowerLetter"){
pool = "abcdefghijklmnopqrstuvwxyz0123456789";
}
else if (type == "upperLetter"){
pool = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
}
else if (type == "symbol"){
pool = ",.?/\\(^)![]{}*&^%$#'\"";
}
var arr = pool.split('');
return arr[Math.floor(Math.random()*arr.length)];
}
str = str.split('');
var types = [],
letters = [];
for(var i=0;i<str.length;i++){
var ch = str[i];
if(ch == " "){
types[i] = "space";
continue;
}
else if(/[a-z]/.test(ch)){
types[i] = "lowerLetter";
}
else if(/[A-Z]/.test(ch)){
types[i] = "upperLetter";
}
else {
types[i] = "symbol";
}
letters.push(i);
}
clearTimeout(t);
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i,
len = letters.length,
strCopy = str.slice(0); // Fresh copy of the string
if(start>len){
return;
}
// All the work gets done here
for(i=Math.max(start,0); i < len; i++){
// The start argument and options.step limit
// the characters we will be working on at once
if( i < start+options.step){
// Generate a random character at this position
strCopy[letters[i]] = randomChar(types[letters[i]]);
}
else {
strCopy[letters[i]] = "";
}
}
//el.text(strCopy.join(""));
el = strCopy.join("");
//console.log(el);
$('.'+dest).text(el);
t = setTimeout(function(){
shuffle(start+1);
},500/options.fps);
})(-options.step);
}
$(document).ready(function(){
$(document).click(function(){
writeStats('this sentence is a great one','t1');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<div class="t1"></div>
<div class="t2"></div>
... and the relative fiddle if you prefer it there: https://jsfiddle.net/phjzfw15/1/
If you run the snippet you'll see it doesn't work properly anymore.
Clicking repeatedly will show you that the old sentence is still there and it gets overwritten.
How can I get this working clearing the timeout correctly inside the function?
I thought the "t" variable was local to each function and a separate instance of it would have been created?
Thanks!
Ok, here's a dumbed down version (maybe the amount of code was too much before)
CORRECT VERSION
var starr = [
'bloop the boop',
'cammy the shadow',
'i like cauliflower',
'bro, i kick u hard',
'like measels? I dont.',
'eat fish and pie'
];
var timer;
function writeStats(str, dest) {
$('.'+dest).text('');
var options = {
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "" // Use this text instead of the contents
}
str = str.split('');
clearTimeout(timer);
var ll = '';
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i, len = str.length, el;
if(start>=len){
return;
}
ll = ll + str[start];
$('.'+dest).text(ll);
timer = setTimeout(function(){
shuffle(start+1);
},1500/options.fps);
})(0);
}
$(document).ready(function(){
var index = 0;
$(document).click(function(){
writeStats(starr[index],'t1');
if (index == 5) index = 0; else index++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
Correct version
<div class="t1">Click anywhere multiple times</div>
NOT WORKING VERSION
var starr = [
'bloop the boop',
'cammy the shadow',
'i like cauliflower',
'bro, i kick u hard',
'like measels? I dont.',
'eat fish and pie'
];
function writeStats(str, dest) {
var timer;
$('.'+dest).text('');
var options = {
"step" : 8, // How many times should the letters be changed
"fps" : 25, // Frames Per Second
"text" : "" // Use this text instead of the contents
}
str = str.split('');
clearTimeout(timer);
var ll = '';
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i, len = str.length, el;
if(start>=len){
return;
}
ll = ll + str[start];
$('.'+dest).text(ll);
timer = setTimeout(function(){
shuffle(start+1);
},1500/options.fps);
})(0);
}
$(document).ready(function(){
var index = 0;
$(document).click(function(){
writeStats(starr[index],'t1');
if (index == 5) index = 0; else index++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
NOT WORKING VERSION (please note I just moved the timer declaration inside the function)
<div class="t1">Click anywhere multiple times fast</div>
Finally made it to work.
For posterities...
var starr = [
'bloop the boop',
'cammy the shadow',
'i like cauliflower',
'bro, i kick u hard',
'like measels? I dont.',
'eat fish and pie'
];
var writer = function(){
var timer;
this.writeStat = function(str,dest) {
var options = { "step" : 8, "fps" : 25, "text" : "" }
str = str.split('');
clearTimeout(timer);
var ll = '';
(function shuffle(start){
// This code is run options.fps times per second
// and updates the contents of the page element
var i, len = str.length, el;
if(start>=len){
return;
}
ll = ll + str[start];
$('.'+dest).text(ll);
timer = setTimeout(function(){
shuffle(start+1);
},1500/options.fps);
})(0);
}
}
$(document).ready(function(){
var index = 0;
w = new writer;
y = new writer;
$(document).click(function(){
w.writeStat(starr[index],'t1');
y.writeStat(starr[index],'t2');
if (index == 5) index = 0; else index++;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<div class="t1"></div>
<div class="t2"></div>

unescape not working in profanity filter

I am trying to make a profanity filter with javascript. I was successful but when I encode the bad words I can't get it
to work. I have been working on this for two days straight.
I have tried to unescape the code in a variable and then use the variable when matching. I have tried unescaping in the
match code too. I have tried mixing in document.write and everything else I can think of.
My original functioning code:
var badwords = /fck|psssy|ssshole/i;
Baddata1 = FirstName.value;
Baddata2 = LastName.value;
if (Baddata1.match(badwords))
{
checker();
FirstName.focus();
return false;
}
if (Baddata2.match(badwords))
{
checker();
LastName.focus();
return false;
}
function checker()
{
window.alert("Please Remove Bad Words");
}
You can reverse the string by subtracting char codes from 0xffff to encode, then, reverse it back again to get clear text. Use "new RegExp" to construct:
var encstr = "ン゙ロテム゙フヒニテネミヘロ"; // "bad|nasty|word" put through reverse() function
var badwords = new RegExp(reverse(encstr), "i");
var Baddata1 = "bad";
var Baddata2 = "LastName";
function reverse(str) {
var sout = "", ix;
if (!str) {
return "";
}
for (ix = 0; ix < str.length; ++ix) {
sout += String.fromCharCode(0xffff - str.charCodeAt(ix));
}
return sout;
}
if (Baddata1.match(badwords))
{
checker();
FirstName.focus();
return false;
}
if (Baddata2.match(badwords))
{
checker();
LastName.focus();
return false;
}
function checker()
{
window.alert("Please Remove Bad Words");
}
Working jsfiddle here.
If you don't like using high character codes, I can easily substitute various encoding functions which don't, though this one is the most compact.
Edit: To get the reversed string, either use a JS debugger to call reverse, or, add temporary code like this:
console.log(reverse("bad|nasty|word"));
This works because reverse(reverse(string1)) === string1. reverse undoes itself.
You could also keep a list of words in a separate script, and use JS string join passed to reverse to make the list, for example:
var wordlist = ["bad", "nasty", "word"];
var joined = wordlist.join("|");
console.log('var encstr = "' + reverse(joined) + '"');
Once you've copied the string from the debug console and pasted it, the separate script could easily check that it's correct:
var encstr = "ン゙ロテム゙フヒニテネミヘロ";
alert("encstr " + (reverse(encstr) === joined ? "matches" : "does NOT match") + " original");
Edit 2: If you don't want to use high char codes that fall into international ranges, just use an encoding like base64, or this simple set:
function encodeStr(str) {
var sout = "", ix;
if (!str) {
return "";
}
for (ix = 0; ix < str.length; ++ix) {
if (sout.length)
sout += ",";
sout += str.charCodeAt(ix).toString(16);
}
return sout;
}
function decodeStr(str) {
var sout = "", narr, ix;
if (!str) {
return "";
}
narr = str.split(",");
for (ix = 0; ix < narr.length; ++ix) {
sout += String.fromCharCode(parseInt(narr[ix], 16));
}
return sout;
}
// Using encodeStr on "bad|nasty|word" makes this:
var encstr = "62,61,64,7c,6e,61,73,74,79,7c,77,6f,72,64";
var badwords = new RegExp(decodeStr(encstr), "i");

Categories

Resources