Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts
Logical Conditional Operators Javascript

Javascript supports equality checking (==) and identity checking (===). Equality checks for equality regardless of type. Therefore 25 and 25 will evaluate as true. Identity checking checks not only for equality but type equality as well so 25 and 25 will evaluate as false because, while both are 25, one is a string and the other a number. Note that a single equal sign is an assignment statement! x=5 will assign 5 to x, while x==5 will see if x is equal to 5, and x===5 will check to see if x is identical to 5.
In addition to == and ===, you can check for not equal (!=) and not identical (!==).
| Operators | Description |
|---|---|
| = | Assignment x=5; // assigns 5 to x |
| == | Equality, is x==5? |
| === | Identity, is x 5 and a number as well? |
| != | Not equal, is x unequal to 5? |
| !== | Not identical, is x unequal to the Number 5? |
| ! | Not, if not(false) is true. |
| || | OR, is (x==5) OR (y==5) |
| && | And, is (x==5) AND (y==5) |
| < | Less than. is x less than 5? |
| <= | Less than or equal. is x less than or equal to 5? |
| > | Greater than. is x greater than 5? |
| >= | Greater than or equal. is x greater than or equal to 5? |
CONDITIONAL STATEMENTS
- IF
The if statement lets you execute a block of code if some test is passed.
var x=5;
if (x==5) {
alert(x is equal to 5!);
}
You can also use an else clause to execute code if the test fails.
var x=5;
if (x==5) {
alert(x is equal to 5!);
} else {
alert(x is not equal to 5!);
}
An elseif statement also exists which allows for better formatting of long conditional tests.
var x=5;
if (x==1) {
alert(x is equal to 1!);
} else if (x==2) {
alert(x is equal to 2!);
} else if (x==5) {
alert(x is equal to 5!);
} else {
alert(x isnt 1, 2 or 5!);
}
- SWITCH
If youre going to be doing a large number of tests, it makes sense to use a switch statement instead of nested ifs. Switches in javascript are quite powerful, allowing evaluations on both the switch and the case.
var x=5;
switch (x) {
case 1: alert(x is equal to 1!; break;
case 2: alert(x is equal to 2!; break;
case 5: alert(x is equal to 5!; break;
default: alert("x isnt 1, 2 or 5!");
}
Note that if you omit the break statement that ALL of the code to the end of the switch statement will be executed. So if x is actually equal to 5 and there is no break statement, an alert for "x is equal to 5" will appear as well as an alert for "x isnt 1,2, or 5!".
Sometimes it makes more sense to do the evaluation in the case statement itself. In this case youd use true, false, or an expression which evaluates to true or false in the switch statement.
var x=5;
switch (true) {
case (x==1): alert(x is equal to 1!; break;
case (x==2): alert(x is equal to 2!; break;
case (x==5): alert(x is equal to 5!; break;
default: alert("x isnt 1, 2 or 5!");
}
- Shorthand Assignment
Javascript supports more advanced constructs. Often you will see code like the following
function doAddition(firstVar, secondVar) {
var first = firstVar || 5;
var second= secondVar || 10;
return first+second;
}
doAddition(12);
Here Javascript uses a logical OR (||) to determine if the passed variables actually have a value. In the example we call doAddition with a value of 12 but we neglect to pass a second argument. When we create the first variable firstVar is a non-falsey value (IE its actually defined) so Javascript assigns firstVar to first. secondVar was never passed a value so it is undefined which evaluates to false so here the variable second will be assigned a default value of 10.
You should note that zero evaluates as false so if you pass zero as either firstVar or secondVar the default values will be assigned and NOT zero. In our example above it is impossible for first or second to be assigned a zero.
In psuedo code...
var someVariable = (assign if this is truthy) || (assign this if first test evaluates false)
- Ternary Operators
Ternary operators are a shorthand if/else block whos syntax can be a bit confusing when youre dealing with OPC (Other Peoples Code). The syntax boils down to this.
var userName = Bob;
var hello = (userName==Bob) ? Hello Bob! : Hello Not Bob!;
In this example the statement to be evaluated is (userName==Bob). The question marks ends the statement and begins the conditionals. If UserName is, indeed, Bob then the first block Hello Bob! will be returned and assigned to our hello variable. If userName isnt Bob then the second block (Hello Not Bob!) is returned and assigned to our hello variable.
In psudeo code
var someVariable = (condition to test) ? (condition true) : (condition false);
The question mark (?) and colon (:) tend to get lost in complex expressions as you can see in this example taken from wikipedia (but which will also work in Javascript if the various variables are assigned...)
for (i = 0; i < MAX_PATTERNS; i++)
c_patterns[i].ShowWindow(m_data.fOn[i] ? SW_SHOW : SW_HIDE);
So while quick and efficient, they do tend to reduce the maintainability/readability of the code.
LOOP LOGICS
- FOR
The for loop follows basic C syntax, consisting of an initialization, an evaluation, and an increment.
for (var i=0; (i<5); i++) {
document.writeln(I is equal to +i+<br>);
}
// outputs:
// I is equal to 0
// I is equal to 1
// I is equal to 2
// I is equal to 3
// I is equal to 4
This is actually an extreme simplification of what a for statement can do. On the other end of the spectrum, consider this shuffle prototype which will randomly shuffle the contents of an array. Here, everything is defined, and executed within the context of the for statement itself, needing no additional block to handle the code.
Array.prototype.shuffle = function (){
for(var rnd, tmp, i=this.length; i; rnd=parseInt(Math.random()*i), tmp=this[--
i], this[i]=this[rnd], this[rnd]=tmp);
};
- FOR/IN
Javascript has a variant of the for loop when dealing with Javascript objects.
Consider the following object
var myObject = { animal : dog,
growls : true,
hasFleas: true,
loyal : true }
We can loop through these values with the following construct.
var myObject = { animal : dog,
growls : true,
hasFleas: true,
loyal : true }
for (var property in myObject) {
document.writeln(property + contains + myObject[property]+<br>);
}
// Outputs:
// animal contains dog
// growls contains true
// hasFleas contains true
// loyal contains true
What this essentially does is assign the property name to the variable property. We can then access myObject through an associative array style syntax. For instance the first itteration of the loop assigns animal to property and myObject["animal"] will return dog.
There is a big caveat here in that properties and methods added by prototyping will also show up in these types of loops. Therefore its best to always check to make sure you are dealing with data and not a function as such
for (var property in myObject) {
if (typeof(myObject[property]) != function) {
document.writeln(property + contains + myObject[property]+<br>);
}
}
The type of check to screen out functions will ensure that your for/in loops will extract only data and not methods that may be added by popular javascript libraries like Prototype.
- WHILE
WHILE loops in Javascript also follow basic C syntax and are easy to understand and use. The while loop will continue to execute until its test condition evaluates to false or the loop encounters a break statement.
var x = 1;
while (x<5) {
x = x +1;
}
var x = 1;
while (true) {
x = x + 1;
if (x>=5) {
break;
}
}
Sometimes it makes more sense to evaluate the test condition at the end of the loop instead of the beginning. So for this Javascript supports a do/while structure.
var x=1;
do {
x = x + 1;
} while (x < 5);
Input On Click User Input in Javascript
.jpg)
Input (On-Click To Rule Them All)
Input, of course, is a little more complicated. For now well just reduce it to a bare click of the mouse.
Input, of course, is a little more complicated. For now well just reduce it to a bare click of the mouse.
If everything in HTML is a box and every box can be given a name, then every box can be given an event as well and one of those events we can look for is "onClick". Lets revisit our last example...
<html>
<head>
</head>
<body>
<div id=feedback onClick=goodbye()>Users without Javascript see
this.</div>
<script type=text/javascript>
document.getElementById(feedback).innerHTML=Hello World!;
function goodbye() {
document.getElementById(feedback).innerHTML=Goodbye World!;
}
</script>
</body>
</html>
Here we did two things to the example, first we added an "onClick" event to our feedback division which tells it to execute a function called goodbye() when the user clicks on the division. A function is nothing more than a named block of code. In this example goodbye does the exact same thing as our first hello world example, its just named and inserts Goodbye World! instead of Hello World!.
Another new concept in this example is that we provided some text for people without Javascript to see. As the page loads it will place "Users without Javascript will see this." in the division. If the browser has Javascript, and its enabled then that text will be immediately overwritten by the first line in the script which looks up the division and inserts "Hello World!", overwriting our initial message. This happens so fast that the process is invisible to the user, they see only the result, not the process. The goodbye() function is not executed until its explicitly called and that only happens when the user clicks on the division.
While Javascript is nearly universal there are people who surf with it deliberately turned off and the search bots (googlebot, yahoos slurp, etc) also dont process your Javascript, so you may want to make allowances for what people and machines are-not seeing.
Input (User Input)
Clicks are powerful and easy and you can add an onClick event to pretty much any HTML element, but sometimes you need to be able to ask for input from the user and process it. For that youll need a basic form element and a button
Clicks are powerful and easy and you can add an onClick event to pretty much any HTML element, but sometimes you need to be able to ask for input from the user and process it. For that youll need a basic form element and a button
<input id=userInput size=60> <button onClick=userSubmit()>Submit</button><BR>
<P><div id=result></div>
Here we create an input field and give it a name of userInput. Then we create a HTML button with an onClick event that will call the function userSubmit(). These are all standard HTML form elements but theyre not bound by a <form> tag since were not going to be submitting this information to a server. Instead, when the user clicks the submit button, the onClick event will call the userSubmit() function
<script type=text/javascript>
function userSubmit() {
var UI=document.getElementById(userInput).value;
document.getElementById(result).innerHTML=You typed: +UI;
}
</script>
Here we create a variable called UI which looks up the input field userInput. This lookup is exactly the same as when we looked up our feedback division in the previous example. Since the input field has data, we ask for its value and place that value in our UI variable. The next line looks up the result division and puts our output there. In this case the output will be "You Typed: "followed by whatever the user had typed into the input field.
We dont actually need to have a submit button. If youd like to process the user input as the user types then simply attach an onKeyup event to the input field as such
<input id=userInput onKeyUp="userSubmit()" size=60><BR>
<P><div id=result></div>
Theres no need to modify the userSubmit() function. Now whenever a user presses a key while the userInput box has the focus, for each keypress, userSubmit() will be called, the value of the input box retrieved, and the result division updated.
Secrets Special Javascript Tricks

- Refresh the Page
Create an action like this:
On: Mouse Click
Action: Modify Variable
Target: temp (Dummy Variable)
Value: Javascript: window.location.reload()
- Close Button
In some cases a button with the Exit course / close window action does not work. If that happens to you, try this:
Add another action to the Exit button with:
On: Mouse Click
Action: Go To
Target: Web Address
Value: Javascript: top.window.close()
A recent tip from the Lectora forum by Tecocat was to "make sure that in your Publish options, you check the option that says Published Content will be Presented in a Separate window than
the LMS. This will enable you to use the Exit Title action in Lectora when publishing to SCORM."
- Get Current URL for Bookmarking
On: Show
Action: Modify Variable
Target: _bookmark (a retained variable)
Value: Javascript: location.href
Then, on returning to the course, the first page checks the variable _bookmark for not equal to zero and runs a Go To Web Address action using Var(_bookmark) as the target. Make sure this action does not run on the first page, otherwise it will overwrite your bookmark with the address of the first page.
- Change the Browser Bar
To change the ½ inch bar at the top of the window which normally contains the page name, create an HTML object with this code. Remember you must have an action on the page that references the CurrentTitleName somehow.
<script>
x = VarCurrentTitleName.value;
x = x + " Course"+ unescape("%A0%A0%A0%A0%A0%A0%A0%A0%A0%A0%A0");
// the above inserts spaces to move the browser name to the right
document.title = x; </script>
- How to Reverse the Student Name from an LMS
The name you get from an LMS is in the form of last, first middle. To reverse them code this action with the below JavaScript function.
Action: Modify Variable
Target: _studentName
Value: Javascript: reverseName()
Condition: AICC_Student_Name Is Not Empty
And in an HTML object enter this JavaScript:
<script language = "JavaScript">
function reverseName(){
var temp = AICC_Student_Name.getValue().split(",");
return temp[1] + " " + temp[0];
}
</script>
Optimizing a Website with Critical Components
- How to Disable the Browser Back Button
When someone clicks the IE back button, this code prevents the page from showing and returns immediately to the page where the back button was clicked.
- Click the "Add External HTML" button on the toolbar.
- From the Object Type dropdown menu, select "Meta tags".
- In the Custom HTML box type the following code:
<script>history.forward();</script>
- Dynamically Change the Which Object is on Top (Layering)
Use it like this:
On: Click
Action: Modify Variable
Target: any variable
Value: Javascript: HTMLname.objLyr.styObj.zIndex=1
where HTML name is the HTML name of your object from the General tab of the object properties. You may have to turn this on in File menu > Preferences. A high number brings it to the front, a low number pushes it to the back.
Windows 8 & 8.1 Tips & Tricks
- Trim Leading and Trailing Spaces
This function is useful to apply before evaluating a fill-in-the-blank question.
<script>
function trim(ans) {
var s=ans.getValue()
while (s.substring(0,1) == ) {
s = s.substring(1,s.length); }
while (s.substring(s.length-1,s.length) == ) {
s = s.substring(0,s.length-1); }
return s; }
</script>
Use it like this:
On: Click
Action: Modify Variable
Target: Question_0001 (or whatever your question variable is)
Value: Javascript: trim(VarQuestion_0001)
- How to Set the Focus on a Specific Entry Box
When you want to make it so that the cursor is in a specific entry box, you need to make it have the current focus. To do that, first open the properties of the entry box and get the HTML name and the entry name.
Then create an action that looks generally like this:
On: show
Acton: Modify variable
Target: temp
Value: Javascript: document.entry17624form.Entry_1.focus()
For example, if the HTMLname = entry37 and the Entry name was Entry_1, then the value property would look like this:
Javascript: document.entry37form.Entry_1.focus()
- How to Change the Background Color in a Table of Contents
Sometimes you may want to change the highlight color in a TOC, especially when you have selected a dark background with light text. In this case a light highlight color washes out the text.
Here is the action you need to change the highlight color to burgundy.
On: show
Acton: Modify variable
Target: temp
Value: Javascript: tocXXX.selNode.navObj.style.backgroundColor = #6A0010
Or
Value: Javascript: tocXXX.selNode.navObj.style.backgroundColor =
rgb(106,0,16)
Where tocXXX is the HTML name of your table of contents.
- Change Cookie Retention
Try this as it seems to do the trick.
Note: This changes a Trivantis Javascript file. Do so at your own risk. I suggest you make a copy of this file before making the changes. Once modified, Trivantis no longer supports the file.
1. Open trivantis-cookies.js in C:Program FilesTrivantisLectora Professional Publishing SuiteSupport Files.
Insert
if( typeof Var_expireDays != "undefined") days = Var_expireDays.getValue() ;
right after line 8: if (days) {
2. In your Lectora title, create retained variable _expireDays and add a title level action that modifies _expireDays and sets it to either 30 or 90. This action needs to be on ALL pages (not popups).
Visit here to view the trivantis cookie = your computer user name+@~~local~~...
- Display All Named Objects
function displayNames (){
// list all object ids and names
//alert("in")
var text = "";
var y = "";
for(x=0;x<document.all.length;x++){
txt = "(";
if (document.all[x].id ){ txt = txt + "id="+document.all[x].id ;}
txt = txt + ",";
if (document.all[x].name){ txt = txt + " name=" + document.all[x].name;}
txt = txt + ")";
if (txt == "(,)") {txt = ""}
else {
text = text + txt + " ";
y = y + txt + "</br>";
}
}
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(y);
inputObject.visibility = "hidden"
alert (text);
}
A Range of META TAGS
- Display an Objects Properties
function displayProperties(inputObj, inputObjectName){
//function displayProperties(inputObjectName){
// Javascript: displayProperties(inputObj,"qu449")
//var result = new Array (0);
//alert("in")
var inputObject = inputObj
//varinputObject = document.getElementById(inputObjectName)
var properties = new Array (0);
var objects = new Array(0);
var counter=1
for (var i in inputObject) {
// if (typeof inputObject[i] == "object") objects.push ("<br>
>>"+inputObjectName + "." + i + " = " + inputObject[i] );
// else properties.push ("<br> >>"+inputObjectName + "." + i + " = " +
inputObject[i] );
if (typeof inputObject[i] == "object") objects.push ("<br>
>>"+inputObjectName + "." + i + " = " + inputObject[i] );
else properties.push ("<br> >>"+inputObjectName + "." + i + " = " +
inputObject[i] );
}
properties = properties.sort();
objects = objects.sort()x= properties.join() +
"<br>===============================<br>"+objects.join()
//alert(x.indexOf("0001"))
//alert(x)
//document.writeln(x)
newwindow=window.open();
newdocument=newwindow.document;
newdocument.write(x);
inputObject.visibility = "hidden"
}
- Entering JavaScript Commands in the Browser Address Field
Instead of entering code within your module, during debugging you can enter JavaScript commands in the address bar. You dont always get the same results as entering them inline in the code. This is particularly useful with the above two functions. Enter them like this:
Javascript: displayNames()
Javascript: displayProperties(HTMLname of an object)
- How to Keep a Window on Top
Enter this into an HTML object.
<body onBlur="window.focus();">
See Stylish Table Design with CSS
- How to Change Size and Location of Debug Window
I do not like the default location and size of the debug window so I figured out a way to change them.
In Windows, navigate to the trivantis.js file which resides in "C:Program FilesTrivantis...Support Files".
Output getElementById in Javascript
.jpg)
Output (getElementById)
The last method is the most powerful and the most complex (but dont worry, its really easy!).
Everything on a web page resides in a box. A paragraph () is a box. When you mark something as bold you create a little box around that text that will contain bold text. You can give each and every box in HTML a unique identifier (an ID), and Javascript can find boxes you have labeled and let you manipulate them. Well enough verbiage, check out the code!
<html>
<head>
</head>
<body>
<div id=feedback></div>
<script type=text/javascript>
document.getElementById(feedback).innerHTML=Hello World!;
</script>
</body>
</html>
The page is a little bigger now but its a lot more powerful and scalable than the other two. Here we defined a division and named it "feedback". That HTML has a name now, it is unique and that means we can use Javascript to find that block, and modify it. We do exactly this in the script below the division! The left part of the statement says on this web page (document) find a block weve named "feedback" (getElementById(feedback)), and change its HTML (innerHTML) to be Hello World!.
We can change the contents of feedback at any time, even after the page has finished loading
(which document.writeln cant do), and without annoying the user with a bunch of pop-up alert boxes (which alert cant do!).
(which document.writeln cant do), and without annoying the user with a bunch of pop-up alert boxes (which alert cant do!).
It should be mentioned that innerHTML is not a published standard. The standards provide ways to do exactly what we did in our example above. That mentioned, innerHTML is supported by every major Browser and in addition innerHTML works faster, and is easier to use and maintain. Its, therefore, not surprising that the vast majority of web pages use innerHTML over the official standards.
While we used "Hello World!" as our first example, its important to note that, with the exception
of <script> and <style>, you can use full-blown HTML. Which means instead of just "Hello World" we could do something like this
<html>
<head>
</head>
<body>
<div id=feedback></div>
<script type=text/javascript>
document.getElementById(feedback).innerHTML=<P><font color=red>Hello
World!</font>;
</script>
</body>
</html>
In this example, innerHTML will process your string and basically redraw the web page with thenew content. This is a VERY powerful and easy to use concept. It means you can basically take an empty HTML element (which our feedback division is) and suddenly expand it out with as much HTML content as youd like.
Subscribe to:
Posts (Atom)