Mouse , cursor and touch detection with Flash CS5

Here is my click, touch and cursor movement practice. This contains some good code examples for detecting whether the user has touched or clicked with a mouse, including mouseover hover.There is even code that lets the touch user drag the object, but not the mouse user. I created this code during my Flash CS5 course winter 2011 at skagit valley college.

Here is a touch detection example with animation on press.

Gathering form variables with asp, trim white space from them, replace sql special characters, Removing Harmful Characters from User Input.

Here is a quick way to display the form elements, best for debugging. While this is a very easy way to get all of the elements displayed, they will not be in the order you might expect.

For each x in Request.Form
Response.Write(“<span class=’highlight’>” & x & “</span> = <span class=’myspan’>” & Request.Form(x) & “</span><br />”)
next

This next way first will check if the form has been submitted, and then  preserves the original order of the form elements, and is best for coding the form elements into variables or displaying them

If request.form <> “” Then

for x = 1 to Request.Form.count()
Response.Write(Request.Form.key(x) & ” = “)
Response.Write(Request.Form.item(x) & “<br>”)
next

End If

 

 

What if you are getting errors when trying to use a varaible that was submitted. There is a good chance that there is whitespace before or after the var. In classic asp you can just use the Trim()

myvar=” ddenney@hotmail.com   ” <– those pesky white spaces at the end will mess up the  sendEmail function.

MycleanVar=Trim(myvar)  — MyCleanVar should now pass through the send email function with out any problems..(assuming you have validated the address).

What if the user has entered their data in “quotes”. Suppose Dan “the man” Rodriques wants to register for sports. The quotes around the name could mess up the sql server insert statement.  We just escape the characters with script.

FUNCTION remChars(inString)
tempString = Replace(inString,"""","""""")
tempString = Replace(tempString,"'","''")
remChars = tempString
END FUNCTION

 

Counting Form Submit Variables and using them if they exist.

Now I need to count how many variables received for additional transcripts. They will be passed to me using the following pattern… Other Transcripts1, Other Transcripts2, Other Transcripts3, Other Transcripts4, etc.

After some pondering, I have decided to use a While loop…

amount = 1
While Request.Form("Other Transcripts" & amount) <> "" 
       Response.Write("We have other transcripts (" & amount & "), lets put it into the table." & otherSQL)
       amount = amount + 1
Wend

This will continue to loop through the variables until it finds them empty.

 

 

Removing Harmful Characters from User Input

To protect against vulnerabilities such as script injection and cross-site scripting, user input can be verified and rejected, or an application can simply remove harmful characters and continue processing. This is a summary from the microsoft article

The regular expression, [^A-Za-z0-9_ ], matches any character that is not any of the following:

  • An alphabetic character
  • A number
  • An underscore (_)
  • A space

 

 function RemoveBadCharacters(strTemp) { strTemp = strTemp.replace(/[^A-Za-z0-9_ ]/g,""); return strTemp; } 

Search for a string using Javascript

if (str.indexOf("Yes") >= 0)

 

This is a powerful tool. The variable str contains the text you want to search. “Yes” is an example of what you could search for. It will be >=0 if the string is found in the search.

 

Here is a good example for how to see if its a negative number.

var isnegative=number.indexOf("-")>=0? true : false ;

 

If string passed in is like  number= 10 will return true
If number = -10 then will return false.

 

While enjoying some reading of the Mozilla Developer Network docs, I have stumbled on to a bit of “best practice” techniques:

Note that ‘0’ doesn’t evaluate to true and ‘-1’ doesn’t evaluate to false. Therefore, when checking if a specific string exists within another string the correct way to check would be:

"Blue Whale".indexOf("Blue") != -1; // true
 "Blue Whale".indexOf("Bloe") != -1; // false

So my final snippet for checking if a string is in another string is as follows.

var mystring - "Yes I want to respond."; If (mystring.indexOf("Yes") != -1){console.log("They want to respond");)} 

Dynamic arrays and array techniques with vbscript classic asp

The standard vbscript array is created as so…

Dim degrees(4)
degrees(0) = “Associate in Applied Science Transfer”
degrees(1) = “Associate in Arts, University and College Transfer”
degrees(2) = “Associate in Arts, General Studies”
degrees(3) = “Associate in Science”
degrees(4) = “Associate in Technical Arts”

 

These arrays are not dynamic and need some work to add data to them. You can also create arrays by splitting strings as seen in my post about asp string manipulation techniques.

 

count = 23 ‘ set from database pull

Dim myarray()
ReDim Preserve myarray(count)

For x = 1 to count
myarray(x) =  mydynamicitemhere

Next

 

 

Dump the contents of an array to the screen for debug:

For Each item In myFixedArray
	Response.Write(item & "<br />")
Next

A two dimensional array would be achieved as so…

Dim listofslides()

ReDim preserve listofslides(4,4) ‘ sequence, filename, description, enabled
listofslides(0,0)=1
listofslides(0,1)=”image1.jpg”
listofslides(0,2)=”Description of image 1″
listofslides(0,3)=1

 

 

But if you are getting the array from an information storage system, then its super easy.

sub grabdata
        SQL_query = "SELECT * FROM MSAccess_table"
        Set rsData = conn.Execute(SQL_query)
        If Not rsData.EOF Then aData = rsData.GetRows()         
    end sub

and you use the array like this


If IsArray(aData) Then
    For x = lBound(aData,2) to uBound(aData,2) 'loops through the rows
        Col1 = aData(0,x)
        Col2 = aData(1,x)
        Col3 = aData(2,x)
        Response.Write "Row #" & x+1 & "
" Response.Write "This is the data in Column1: " & Col1 & "
" Response.Write "This is the data in Column2: " & Col2 & "
" Response.Write "This is the data in Column3: " & Col3 & "
" Next End If

Formatting currency fields using javascript

This actually uses jquery, but yo could replace the jquery with doc.getelem….

Here is a sick way to get rid of $ signs, commas and anything after decimal point.

for example: $45,000.45 becomes a clean number 45000 ready for calculations.

No, it doesnt round. just removes the change.

// strip out any $$ .00 and anything else
function stripper(who){
dirtynumber = $( who ).val();
cleannumber = parseInt(dirtynumber.replace(/[^d.]/g, “”));
$( who ).val(cleannumber);
}

Handling Events With J Query

jQuery event.target always refers to the element that triggered the event, where 'event' is the parameter passes to the function. http://docs.jquery.com/Events_(Guide)

$(document).ready(function() {     $("a").click(function(event) {         alert(event.target.id);     }); });
If the  <a> that is clicked were a game element, such as an ace card, the card could tell you "I am an ace of spades" for your code to do what ever.
$( "p" )
.html( newText )
.find( "span" )
.hover(function() {
$( this ).addClass( "hilite" );
}, function() {
$( this ).removeClass( "hilite" );
})
.end()
.find( ":contains('t')" )
.css({
"font-style": "italic",
"font-weight": "bolder"
});

Setting an event handler is not too difficult, but what about removing the event. I don’t want the user to be able to hit the button more than once and still fire the function. the only way that was working was to disable the button or hide it.  I finally found the technique that really works for me. The prop() is a powerful function with untold uses. Dealing with checkboxes seems to be something that would merit its own post. http://api.jquery.com/prop/

Here is a great way to remove a click event that you put inline:

<A href=”#” onclick=”mycoolfunk()” id=”thisbut”>my button or link</a>

$(‘#thisbut’).prop(“onclick”, null);

 

Update: I have been fighting with finding the best way to remove a click event from the button so the user cant hammer on it repeatedly. None of my solutions were working effectively in all situations: like actions on  a submit button are harder to remove than ones on a link.I couldn’t get the submit to submit to my will. I wanted to hide it onclick, not happenin. remove click event, not workin either. What the hell should I do?

Well, enter the .one()  — thats right. http://api.jquery.com/one/ The jquery docs have a function to only put one click event onto an object. This is perfect for a submit where we don’t want the user to be able to repeatedly press the figgin button cause they think everything should be so instantaneous. LOL.

 

But what about handling multiple events.  I have been looking for this for years… We have the  $( document ).on( "click", "#demo-page", function( e ) {alert(e.type)}); alerts(‘click’)

Well here’s how to handle multiple events with one on call:

 $( document ).on( "click press swipeleft swiperight", "#demo-page", function( e ){
alert(e.type); 
if ( e.type === "swipeleft"  ) {// do something only on swipeleft}
});// end doc.on funk

 

I will write up a demo page with this script so I can test it out and do stuff with events.

 

Using delegated events to allow dynamic elements to have the event handler.

Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. This element could be the container element of a view in a Model-View-Controller design, for example, or document if the event handler wants to monitor all bubbling events in the document. The document element is available in the head of the document before loading any other HTML, so it is safe to attach events there without waiting for the document to be ready.

Lets take for example the diploma application I am working on. I have some buttons that have styles and actions that need to be called, but the buttons are not in the dom until and unless the user accesses that particular step of the application. How do I assign the events and styles to non-existing buttons. I had tried a few various solutions before I read about this. Now lets go for this approach. I will delegate the event to the form element. That way, any dynamically added elements will still get the mouseover and mouseout effects.

$(“#diplomappform”).on(“mouseover mouseout”, “[name=’stepUpButton’]”, function(e){
if(e.type==”mouseover”){
$(this).removeClass(“blackouterstrokesmall”).addClass(“boldfont blackouterstrokemedium insetborder whitetextglowtight”);
}
if(e.type==”mouseout”){
$(this).removeClass(“boldfont blackouterstrokemedium insetborder whitetextglowtight”).addClass(“blackouterstrokesmall”);
}
});

 

Sometimes if  you have a mouse over event, the mouse out event will trigger accidently too early. Peter has worked out a fix for this: make a function to call the mouse over function instead of putting an anonymous function directly into the event.
var qlinkTrigger = function() {
$(“#qlink-box”).slideDown(“slow”, function() {
$(this).clearQueue();
});
}

$(“a#qlink-trigger”).hover(qlinkTrigger).click(qlinkTrigger);

$(“#qlink-box”).mouseleave(function() {
$(this).slideUp(“slow”);
});

$(“a.close-qlinkbox”).click(function() {
$(“#qlink-box”).slideUp(“slow”);
return false;
});

ASP and VBSCRIPT string manipulation techniques

To compare two strings that should be identical match:

mystringa=”deedubs”
mystringb=”Dee Dubs”

TestComp = StrComp(mystringa, mystringb)

If TestComp <> 0 Then
Response.Write("The strings don't match")
End If

 

ASP Classic and VBScript tips, tuts links and snips  This seems to be a sick way to code arrays in asp from a string
Here is a vbscript reference pdf.

Are you trying to break a string up into smaller pieces? ASP provides an easy to use split function which lets you dice and slice a string.

Let’s say you take in a sentence and want to put each word into a different variable. So you take in

NameStr = “Mr. John Smith”

Set up the array to hold the results with

Dim WordArray

then do the split, using a space as the split indicator

WordArray = Split(NameStr, ” “)

Now WordArray(0) is equal to “Mr.”, WordArray(1) is equal to “John” and WordArray(2) is equal to “Smith”! You can use various array functions and other string functions to work with these results.

ASP String Functions

 

Best practices  Redirect a user to a location.

While I could response.write a javascript relocation, this is not best practice for security and performance, we would want to execute this code on the server side, so that it can’t be manipulated in any way by a malicious user.

<script>document.location=”myfile.asp”</script> — this is handled on the client machine after they have recieved the page. This could be messed with by a hacker, and I am not even going to give you any reasons why or how.

newUri = “http://www.mysite.com/myspecialpage.html”

 Response.Redirect(newUri) 

The only drawback is that this can’t be used after any content has been written to the page. Here is a great article from microsoft about the variables and how to use them.

 

Check if a string has letters in it.

A basic validation to see if a string doesnt have letters in it:

Set re =New RegExp
re.Pattern ="[a-z]"
re.IgnoreCase =True
re.Global =True
hasMatches = re.Test("12345abc")
If hasMatches =True
'it has letters in it.
End If

 

basic Javascript email validation

This function will check for very basic user mistakes such as @ sign and .com and stuff.

// function to validate email address
function validateEmail(elementValue){
var emailPattern = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+.[a-zA-Z]{2,4}$/;
return emailPattern.test(elementValue);
}
// end email address validator

Use it like this in your code where ever you need it….

if (validateEmail(student_class_instructor_email) == false) {alert(“Error, please check the instructor email address for proper syntax.”); return false;}

 

a really bad ass way to display the error alert , especially in foundation, is to change the alert() to a prepend of the form or even the element that had the error…

alert(“Error…)
$(‘#foundationform’).prepend(“Error, please check the  email address for proper syntax.”);

if you have foundation you can use the error box built in with a close button .. just wrap it around the error message

<div class=’alert-box alert’>Error, please check the  email address for proper syntax.<a href=” class=’close’>&times;</a></div>