$('#result h1', 'img.batman').show();
$('#result h1').show();
$('#result').show();
<div id="result">
<h1> Cyberconrz, yeah boi!!</h1>
<img src="images/batman.jpg" alt="batman on a unicorn with dolphins" class="batman" />
<img src="images/wtf.jpg" alt="on drugs" class="wtf" />
</div>
Wednesday, May 25, 2011
Class Notes
Selectors (chap 5)
If I wanted to select all the paragraph tags in a document that had the class of special:
$('p.special')
All the header tags:
$('h1, h2, h3, h4, h5, h6') // this is called a group selector
$('h1 h2 h3') // this is a descendant selector
Filters (chap 5)
:hidden
:visible
Look this stuff up:
remove
replace
clone
append
Automatic Loops
$('p').hide();
In jQuery it has automatic looping, the jQuery Selectors have automatic loops built in. So you don't to loop through all the p tags to hide each one. It does that automatically.
We can chain functions:
$('p').width(300).height(300);
Instead of:
$('p').width(300);
$('p').height(300);
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Selectors:
addClass() / removeClass() / toggleClass()
great for in response of a mouse over, you might want to add or subtract something
$('a[href^=http://]')
selects every link that points to an outside page
this grabs all hrefs that start with http://
$('a[href^=http://]').addClass('extLink');
<a href="http://www.google.com" class="extLink">Google</a>
$('a[href^=http://]').removeClass('extLink');
$('a[href^=http://]').toggleClass('extLink');
---------------------------------------------------------------------
css()
(this is a function)
1. We can find out what a particular css property is for an element.
Then maybe we might want to add some conditionals.
2. Set CSS property on element
3. Set multiple CSS properties at once
We have to pass in some arguments to make it do something.
To do this:
For 1. When you trying to find out something you will have to be very specific, like if you want to know the border you will have to say border top instead of border. (when setting the property you can use the short hand of just border)
For 2. This is how you set 1 property. (you don't use the colon, it only looks for 2 arguments cause you don't have the curly brackets)
For3. We have to use curly braces, to indicate that you are sending in a list.
You could use the above for rollovers.
-------------------------------------------------------------------
Read, Set, Remove
attr()
HTML Attributes
You could check all the img for alt tags and if there are none you could add alt tags.
1. Getting the attribute:
2. Replacing:
for example: You set the above to a mouse event
<img src="lolcat.jpg" />
becomes <img src="newImage.jpg" />
----------------------------------------------------------
each()
$('img').fadeOut();
If we something custom that looks for only certain images:
each()
is a special kind of argument
anonymous function (it doesn't have a name)
because they don't have a name you can't call them
$('img').each( function() {
//do some stuff
alert('Hi, there, I'm an image');
}
);
----------------------------------------------------
this and this()
This is used to go through the code and point out that you want to effect this piece.
$(this)
often times when you use each() and you are making your own function
you will have to use $(this)
---------------------------------------------
Event
Now we want to take the selectors and have them trigger.
Any action that the user takes on the page is called and event.
Javascript is an event driven language.
We write scripts that respond to events.
An event represent the precise moment when something happens.
http://files.sawmac.com/js1e/chapter06/events.html
Attaching Events to Elements
1. Select one or more elements (selectors)
2. Assign an event
3. Pass a function to the event
4. Add necessary action to the function (our code)
Example of toggle:
$('#idname').click( function () {
//now add the thing that you want to have effected
$("p").toggle("fast") //you can set the speed at which it toggles
});
$("#02 p").toggle("slow");
});
---------------------
Document Ready
Javascript runs as it is loaded into the page. The problem is that say for example you add jQuery that effects images and that script is in the head of the page, but the images are down below in the body and they have not loaded yet. So you get an error because the it is trying to apply the script to images that aren't there yet.
This says wait for the html to load before you load all the javascript
If I wanted to select all the paragraph tags in a document that had the class of special:
$('p.special')
All the header tags:
$('h1, h2, h3, h4, h5, h6') // this is called a group selector
$('h1 h2 h3') // this is a descendant selector
Filters (chap 5)
:hidden
:visible
Look this stuff up:
remove
replace
clone
append
Automatic Loops
$('p').hide();
In jQuery it has automatic looping, the jQuery Selectors have automatic loops built in. So you don't to loop through all the p tags to hide each one. It does that automatically.
We can chain functions:
$('p').width(300).height(300);
Instead of:
$('p').width(300);
$('p').height(300);
--------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------
Selectors:
addClass() / removeClass() / toggleClass()
great for in response of a mouse over, you might want to add or subtract something
$('a[href^=http://]')
selects every link that points to an outside page
this grabs all hrefs that start with http://
$('a[href^=http://]').addClass('extLink');
<a href="http://www.google.com" class="extLink">Google</a>
$('a[href^=http://]').removeClass('extLink');
$('a[href^=http://]').toggleClass('extLink');
---------------------------------------------------------------------
css()
(this is a function)
1. We can find out what a particular css property is for an element.
Then maybe we might want to add some conditionals.
2. Set CSS property on element
3. Set multiple CSS properties at once
We have to pass in some arguments to make it do something.
To do this:
var bgColor = $('#header').css('background-color');
For 1. When you trying to find out something you will have to be very specific, like if you want to know the border you will have to say border top instead of border. (when setting the property you can use the short hand of just border)
For 2. This is how you set 1 property. (you don't use the colon, it only looks for 2 arguments cause you don't have the curly brackets)
$('#header').css('background-color', 'red');
For3. We have to use curly braces, to indicate that you are sending in a list.
$('#header').css({
'background-color': '#FF0000',
'border': '2 px solid #000000'
});
You could use the above for rollovers.
-------------------------------------------------------------------
Read, Set, Remove
attr()
HTML Attributes
You could check all the img for alt tags and if there are none you could add alt tags.
1. Getting the attribute:
var imageFile=$('#header img').attr('src');
2. Replacing:
var imageFile=$('#header img').attr('src', 'newImage.jpg');
for example: You set the above to a mouse event
<img src="lolcat.jpg" />
becomes <img src="newImage.jpg" />
----------------------------------------------------------
each()
$('img').fadeOut();
If we something custom that looks for only certain images:
each()
is a special kind of argument
anonymous function (it doesn't have a name)
because they don't have a name you can't call them
$('img').each( function() {
//do some stuff
alert('Hi, there, I'm an image');
}
);
----------------------------------------------------
this and this()
This is used to go through the code and point out that you want to effect this piece.
$(this)
often times when you use each() and you are making your own function
you will have to use $(this)
---------------------------------------------
Event
Now we want to take the selectors and have them trigger.
Any action that the user takes on the page is called and event.
Javascript is an event driven language.
We write scripts that respond to events.
An event represent the precise moment when something happens.
http://files.sawmac.com/js1e/chapter06/events.html
Attaching Events to Elements
1. Select one or more elements (selectors)
2. Assign an event
3. Pass a function to the event
4. Add necessary action to the function (our code)
Example of toggle:
//first have to select the thing that you want to toggle
//add the event to the thing
//pass in an anonymous function inside the click parenthesis $('#idname').click( function () {
//now add the thing that you want to have effected
$("p").toggle("fast") //you can set the speed at which it toggles
});
//now have another type of toggle
$("$toggle02").click (function () {$("#02 p").toggle("slow");
});
---------------------
Document Ready
Javascript runs as it is loaded into the page. The problem is that say for example you add jQuery that effects images and that script is in the head of the page, but the images are down below in the body and they have not loaded yet. So you get an error because the it is trying to apply the script to images that aren't there yet.
$(document).ready(function () {
// all of your code
//99% of the time you are going to use this document ready
}); This says wait for the html to load before you load all the javascript
---------------------------------------------------
mouseOver()
http://api.jquery.com/mouseover/$('#header').mouseover( function () {
});
---------------------
hover: show and hide
$('#menu').hover (
function() {
$('#submenu').show();
},
function() {
$('#submenu).hide();
}
});
Labels:
Week 8
Wednesday, May 18, 2011
Reading Notes - Ch. 6
Events
Each of the things that happen in a web page are Events.Functions and Events
Inline EventsThe simplest way to run a function when an event fires is called inline event registration.
Assign an event handler.
<a href="page.html" onmouseover="alert('this is a link');">A link</a>
You can even use the inline technique to call a previously created function, like this:
<body onload="startSlideShow()">
**You can add the event handler directly to the HTML but then it gets messy when trying to update the site in the future. It is a best practice to have a separate the Javascript.
Traditional Model
Assign (inside the head) an event handler to a page element.If you have a function and call it usually it looks like:
window.onload=message( );
When you have parenthesis you are telling it to run immediatly
If you remove the parenthesis you are letting the onload handler know what to do when the time comes.
window.onload=message; // the message loads after the page is finished loading
as
Labels:
Week 7
Wednesday, May 11, 2011
Class Notes
Picking out days of week using Regular Expressions
Regular Expressions
For picking out the days of the week.
For picking out the weekend we can look for the days that start with S, because the only days that start with S are weekend days.
/\b[S]/i
/ = open
\b = boundary character
[S] = what to look for
i = ignore the case (Sunday, sunday)
/^[S]/i;
this also works
function dayMessage(){
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var now = new Date ();
var dayOfWeek = days[now.getDay()]; //on the now object we created we assign the string to dayOfWeek
document.write(dayOfWeek);
//everything abov eis just to get the day, we had to convert the number to a string
var dayMatch = /^[S]/i;
if (dayOfWeek == dayMatch) {
document.write('Yay it is a weekend');
}else {
document.write('Boo hoo it is a weekday');
}
}
dayMessage();
------------------------------------
Document Object Model
"the DOM"
The browser has a idea/model of how all the pieces relate and fit to each other
This is important for CSS in terms of descendants and inheritance.
Can be thought of in terms of family tree.
The DOM is a W3C standard, it is separate from Javascript.
Each browser interprets the DOM differently.
Each tag or piece is called a "NODE"
In order for Javascript to manipulate the page it has to communicate with the nodes.
<body>
<div id="content">
<p>hello!</p>
<p>yeah, you.</p>
</div>
</body>
getElementById()
If you have div id="content"
document.getElementById("content");
To select the paragraph tag: (this is not selecting the string/text inside the paragraph)
getElementsByTagName('p');
var myParas=document.getElementsByTagName('p'); //in this example myParas will be an array cause it will hold multiple pieces of info
In the example hello! is the descendant of <p>
This grabs hello! :
var myVarKids = myVar.childNodes;
var myVarText = myVarKids[0].nodeValue;
other ways to grab:
.parentNode
.nextSibling
.previousSibling
Javascript Libraries
Drop Down Menus
We don't have to use the crazy ol' Dom now-a-days.
You can use:
MooTools
prototype + scriptaculous
jQuery
These are "middle-ware" that allow us to talk to the DOM more easily, it figures out all the child node craps.
jQuery
piggybacks on CSS
example:
CSS : #content p
jQuery: $(#content p)
---------------------------
jQuery Selector Test Bed
http://files.sawmac.com/js1e/chapter05/selectors.html
----
Selecting in jQuery
<p id="msg"> A message! </p>
in the DOM: boooo
var msPara = document.getElementById('msg');
in jQuery: yaaaay
var myPara = $('#msg');
Element/tag - $('p')
Class - $('.p')
Descendant - $('p em') //all em tags that are children of the p tag
Child - $('p >em')
Adjacent - $('h1+p') //grabs only the paragraph next to the h1
Attribute Selectors //the stuff in quotes in html like height width src alt - $('img[alt]'), $('a[href]'), $('img[height=42]') //this grabs images that have height="42" in the html attribute
^ = value starts
$ = value ends
* = value contains
$('img[alt*=happy]') // selects alt tags that contains the value happy
---------------------------------------
2 Big Concepts
inner HTML
a way to scoop up all the stuff inside the html (not as simple as jQuery)
When we are writing jQuery you are not writing javascript and vice versa, in other words you can intermix.
You have to use the jQuery versions of ceil and floor, not the javascript versions.
The differences between DOM based and jQuery
1. Automatic Loops: in jQuery your selector automatically loops for you.
$('p').hide(); //goes through all the p puts them into an array then hides all the pieces of the array
in jQ it automatically loops through everything and does what you want it to do
2. Chaining Functions: with jQ we can chain functions together and have it all in one line.
$('#popup').width(300).height(500).text("howdy!").fadeIn(1000);
---------------------------------
Content Functions Test Bed
http://files.sawmac.com/js1e/chapter05/content_functions.html
Regular Expressions
For picking out the days of the week.
For picking out the weekend we can look for the days that start with S, because the only days that start with S are weekend days.
/\b[S]/i
/ = open
\b = boundary character
[S] = what to look for
i = ignore the case (Sunday, sunday)
/^[S]/i;
this also works
function dayMessage(){
var days = ['Sunday','Monday','Tuesday','Wednesday',
'Thursday','Friday','Saturday'];
var now = new Date ();
var dayOfWeek = days[now.getDay()]; //on the now object we created we assign the string to dayOfWeek
document.write(dayOfWeek);
//everything abov eis just to get the day, we had to convert the number to a string
var dayMatch = /^[S]/i;
if (dayOfWeek == dayMatch) {
document.write('Yay it is a weekend');
}else {
document.write('Boo hoo it is a weekday');
}
}
dayMessage();
------------------------------------
Document Object Model
"the DOM"
The browser has a idea/model of how all the pieces relate and fit to each other
This is important for CSS in terms of descendants and inheritance.
Can be thought of in terms of family tree.
The DOM is a W3C standard, it is separate from Javascript.
Each browser interprets the DOM differently.
Each tag or piece is called a "NODE"
In order for Javascript to manipulate the page it has to communicate with the nodes.
example:
html
head body
div
p
<body>
<div id="content">
<p>hello!</p>
<p>yeah, you.</p>
</div>
</body>
getElementById()
If you have div id="content"
document.getElementById("content");
To select the paragraph tag: (this is not selecting the string/text inside the paragraph)
getElementsByTagName('p');
var myParas=document.getElementsByTagName('p'); //in this example myParas will be an array cause it will hold multiple pieces of info
In the example hello! is the descendant of <p>
This grabs hello! :
var myVarKids = myVar.childNodes;
var myVarText = myVarKids[0].nodeValue;
other ways to grab:
.parentNode
.nextSibling
.previousSibling
Javascript Libraries
Drop Down Menus
We don't have to use the crazy ol' Dom now-a-days.
You can use:
MooTools
prototype + scriptaculous
jQuery
These are "middle-ware" that allow us to talk to the DOM more easily, it figures out all the child node craps.
jQuery
piggybacks on CSS
example:
CSS : #content p
jQuery: $(#content p)
---------------------------
jQuery Selector Test Bed
http://files.sawmac.com/js1e/chapter05/selectors.html
----
Selecting in jQuery
<p id="msg"> A message! </p>
in the DOM: boooo
var msPara = document.getElementById('msg');
in jQuery: yaaaay
var myPara = $('#msg');
We can grab:
ID - $('#stuff')Element/tag - $('p')
Class - $('.p')
Descendant - $('p em') //all em tags that are children of the p tag
Child - $('p >em')
Adjacent - $('h1+p') //grabs only the paragraph next to the h1
Attribute Selectors //the stuff in quotes in html like height width src alt - $('img[alt]'), $('a[href]'), $('img[height=42]') //this grabs images that have height="42" in the html attribute
^ = value starts
$ = value ends
* = value contains
$('img[alt*=happy]') // selects alt tags that contains the value happy
---------------------------------------
2 Big Concepts
inner HTML
a way to scoop up all the stuff inside the html (not as simple as jQuery)
When we are writing jQuery you are not writing javascript and vice versa, in other words you can intermix.
You have to use the jQuery versions of ceil and floor, not the javascript versions.
The differences between DOM based and jQuery
1. Automatic Loops: in jQuery your selector automatically loops for you.
$('p').hide(); //goes through all the p puts them into an array then hides all the pieces of the array
in jQ it automatically loops through everything and does what you want it to do
2. Chaining Functions: with jQ we can chain functions together and have it all in one line.
$('#popup').width(300).height(500).text("howdy!").fadeIn(1000);
---------------------------------
Content Functions Test Bed
http://files.sawmac.com/js1e/chapter05/content_functions.html
Labels:
Week 6
Wednesday, April 27, 2011
Class Notes
Functions
1. Way to reuse code
2. Set up series of steps @ start of page
3. "call" the steps later
There are tons of built in functions:
calculateTax();
alert();
Number();
There is a difference between parameters and arguments, although the book doesn't say this.
The simplest way to call a function: call its name
functionName();
If you make a function that is called printMessage, you need to get the information it is to use inside the parenthesis. This is called passing the argument.
printMessage('Hello!'); // Hello! is the argument
TO MAKE A FUNCTION
1. Define/Declare Function
2. Call Function (to run it)
function myFunction() { //defining
//do this
}
myFunction(); //calling the function
A better way:
When we define a function it is called a parameter.
function printMessage(myMessage) {
document.write(myMessage + "<br/>");
}
var myMessage = "Greetings!";
printMessage(myMessage);
var myOtherMessage ="Boo hoo.";
printMessage(myOtherMessage); //it doesn't have to match what is in the function above
You can pass multiple things into the function.
function printHolidayMessage(userName, holidayMessage) {
document.write("Hello" + userName + ", " + holidayMessage + "<br/>");
}
var name = prompt('Please enter your name');
var myHolidayMessage = "Happy August";
printHolidayMessage(
-----------------------------
Scope
Where the variable is visible and usable.
Where that thing is created determines which one is used.
function myFunction (a, b) {
answer = a*b;
return answer; //this keyword sends the value back out of the function
}
var answer = 0;
document.write("<p>The value of answer before myFunction called: " + answer + "</p>");
myFunction(2, 2);
document.write("<p>The new value of myAnswer after function is:" + answer + "</p>");
Global vs. Local Scope
Variables created inside the function are different, they are local.
Variables born outside can go anywhere.
Local variables are visible only inside the function
Global scope are created outside, and can be seen everywhere.
If you want the variable to only be accessible to the code inside the function then you use var keyword inside the function.
Local:
var message = 'Outside the function';
function warning() {
var message = 'Inside the function';
alert(message); //'Inside the function'
}
warning();
alert(message); //'Outside the function'
Global:
var message = 'Outside the function';
function warning() {
message = 'Inside the function';
alert(message); //'Outside the function'
}
warning();
alert(message); //'Inside the function'
--------------------
Objects
Objects:
Properties - parts like nouns or adjective
Methods - things it does like verbs
Methods are functions that are specific to an object, they use a dot syntax
Like document.write
document is an object and it has a thing that it can do, write.
Each object has its own list or properties and methods.
An array has a length property.
Instance - you can have multiple version of a same kind of object.
-------------------
It generates a random number between 0 and whatever you set (num).
But it doesn't give you a new number unless you use:
Math.floor - gives you the number below (4.898 will be 4)
Math.ceil - gives you the number up (4.898 will be 5)
Math.round - rounds like regular
function chooseRandomNum(num) {
var randomNum = Math.floor(Math.random) * num );
}
1. Way to reuse code
2. Set up series of steps @ start of page
3. "call" the steps later
There are tons of built in functions:
calculateTax();
alert();
Number();
There is a difference between parameters and arguments, although the book doesn't say this.
The simplest way to call a function: call its name
functionName();
If you make a function that is called printMessage, you need to get the information it is to use inside the parenthesis. This is called passing the argument.
printMessage('Hello!'); // Hello! is the argument
TO MAKE A FUNCTION
1. Define/Declare Function
2. Call Function (to run it)
function myFunction() { //defining
//do this
}
myFunction(); //calling the function
A better way:
When we define a function it is called a parameter.
function printMessage(myMessage) {
document.write(myMessage + "<br/>");
}
var myMessage = "Greetings!";
printMessage(myMessage);
var myOtherMessage ="Boo hoo.";
printMessage(myOtherMessage); //it doesn't have to match what is in the function above
This would return two separate lines:
Greetings!
Boo hoo. You can pass multiple things into the function.
function printHolidayMessage(userName, holidayMessage) {
document.write("Hello" + userName + ", " + holidayMessage + "<br/>");
}
var name = prompt('Please enter your name');
var myHolidayMessage = "Happy August";
printHolidayMessage(
-----------------------------
Scope
Where the variable is visible and usable.
Where that thing is created determines which one is used.
function myFunction (a, b) {
answer = a*b;
return answer; //this keyword sends the value back out of the function
}
var answer = 0;
document.write("<p>The value of answer before myFunction called: " + answer + "</p>");
myFunction(2, 2);
document.write("<p>The new value of myAnswer after function is:" + answer + "</p>");
Global vs. Local Scope
Variables created inside the function are different, they are local.
Variables born outside can go anywhere.
Local variables are visible only inside the function
Global scope are created outside, and can be seen everywhere.
If you want the variable to only be accessible to the code inside the function then you use var keyword inside the function.
Local:
var message = 'Outside the function';
function warning() {
var message = 'Inside the function';
alert(message); //'Inside the function'
}
warning();
alert(message); //'Outside the function'
Global:
var message = 'Outside the function';
function warning() {
message = 'Inside the function';
alert(message); //'Outside the function'
}
warning();
alert(message); //'Inside the function'
--------------------
Objects
Objects:
Properties - parts like nouns or adjective
Methods - things it does like verbs
Methods are functions that are specific to an object, they use a dot syntax
Like document.write
document is an object and it has a thing that it can do, write.
Each object has its own list or properties and methods.
An array has a length property.
Instance - you can have multiple version of a same kind of object.
-------------------
Math
to generate a random number - this is useful for giving you a number to use for an arrayIt generates a random number between 0 and whatever you set (num).
But it doesn't give you a new number unless you use:
Math.floor - gives you the number below (4.898 will be 4)
Math.ceil - gives you the number up (4.898 will be 5)
Math.round - rounds like regular
function chooseRandomNum(num) {
var randomNum = Math.floor(Math.random) * num );
}
Labels:
Week 4
Chapter 4 - Notes
Words, Numbers, and Dates
JavaScript made up of Objects.
Properties - parts of the object.
Methods - actions and object perform.
Object - array
Properties - length
Method - push()
Object - document
Method - write
Whenever you create a new variable and store a value into it, you are creating an instance.
Strings
Length
to determine the length of a string:
name.length
var password = 'sesame';
if (password.length <= 6) {
alert('That password is too short.');
} else if (password.length > 15) {
alert('That password is too long.');
}
Chang the Case of a String
name.toUpperCase
name.toLowerCase
The correct answer to a quiz is LeCuyer, but the person types Lecuyer so they get it wrong.
To correct you can covert both the response and the correct answer to uppercase
if (response.toUpperCase() == correctAnswer.toUpperCase()) {
//correct
} else {
//incorrect
}
Covert to lowercase:
var answer= 'LeCuyer';
alert(answer.toLowerCase());
returns : lecuyer
In both cases the original string is not altered, it is still LeCuyer.
Searching a String: indexOf()
To find out which browser the viewer is using:
Navigator is an object of the web browser, userAgent is the property
<script type="text/javascript">
alert(navigator.userAgent);
</script>
indexOf()
if the search string isn't found the method returns: -1
var browser = navigator.userAgent; // this is a string
if (browser.indexOf('MSIE') != -1) {
// this is Internet Explorer
}
if the searched string is found it returns the position number.
(spaces count as a position: poop face has 0-8
var myString = "Poop Face";
var firstPosition = myString.indexOf('Poo'); // returns 0
var lastPosition = myString.lastIndexOf('Face'); // returns 5
------
Slice
myString.slice(7);
This picks the 6th position of the string.
myString.slice(start,end);
The end is actually the last position +1.
so (0,5) selects the first five letters/positions 0-6
you can also use negative numbers
Regular Expressions
var myMatch = /hello/;
this matches the word hello
How to search using the search() Method
var myRegEx = /To be/;
var quote = 'To be or not to be.';
var foundPosition = quote.search(myRegEx); //returns 0, it returns the first position in the match
JavaScript made up of Objects.
Properties - parts of the object.
Methods - actions and object perform.
Object - array
Properties - length
Method - push()
Object - document
Method - write
Whenever you create a new variable and store a value into it, you are creating an instance.
Strings
Length
to determine the length of a string:
name.length
var password = 'sesame';
if (password.length <= 6) {
alert('That password is too short.');
} else if (password.length > 15) {
alert('That password is too long.');
}
Chang the Case of a String
name.toUpperCase
name.toLowerCase
The correct answer to a quiz is LeCuyer, but the person types Lecuyer so they get it wrong.
To correct you can covert both the response and the correct answer to uppercase
if (response.toUpperCase() == correctAnswer.toUpperCase()) {
//correct
} else {
//incorrect
}
Covert to lowercase:
var answer= 'LeCuyer';
alert(answer.toLowerCase());
returns : lecuyer
In both cases the original string is not altered, it is still LeCuyer.
Searching a String: indexOf()
To find out which browser the viewer is using:
Navigator is an object of the web browser, userAgent is the property
<script type="text/javascript">
alert(navigator.userAgent);
</script>
indexOf()
if the search string isn't found the method returns: -1
var browser = navigator.userAgent; // this is a string
if (browser.indexOf('MSIE') != -1) {
// this is Internet Explorer
}
if the searched string is found it returns the position number.
(spaces count as a position: poop face has 0-8
var myString = "Poop Face";
var firstPosition = myString.indexOf('Poo'); // returns 0
var lastPosition = myString.lastIndexOf('Face'); // returns 5
------
Slice
myString.slice(7);
This picks the 6th position of the string.
myString.slice(start,end);
The end is actually the last position +1.
so (0,5) selects the first five letters/positions 0-6
you can also use negative numbers
Regular Expressions
var myMatch = /hello/;
this matches the word hello
How to search using the search() Method
var myRegEx = /To be/;
var quote = 'To be or not to be.';
var foundPosition = quote.search(myRegEx); //returns 0, it returns the first position in the match
Labels:
Reading Notes
Tuesday, April 26, 2011
Read “Chapter 4 – Working With Words, Numbers and Dates” from “Javascript: The Missing Manual”.
Tutorial – Page 146 (name your file “yourlastname_ch4_tutorial.html” and any associated files) o It would be a great idea to try out some of the other code that the author talks about in this chapter.
EXTRA CREDIT if you turn in a file that shows how you used some of the examples (or created some of your own). Name this file “yourlastname_ch4_extracredit.html”.
4. Work on your project website: o Create a sitemap/flow chart of the entire site. o Select your color palette. Be sure to include the RGB and Hex values of the colors. (You should turn this in
in JPG or PDF format. No Illustrator or Photoshop files!) o Select the basic fonts you will use for each element/level of information hierarchy on your site. (Turn this in
in JPG or PDF format. No Illustrator or Photoshop files!) o Create a comp for the homepage of the site. (JPG or PDF format only. No Illustrator or Photoshop files!) o Start gathering content – both text and images. Be sure to have at least the content complete for one page
by next week, since you will use it in the labs.
Tutorial – Page 146 (name your file “yourlastname_ch4_tutorial.html” and any associated files) o It would be a great idea to try out some of the other code that the author talks about in this chapter.
EXTRA CREDIT if you turn in a file that shows how you used some of the examples (or created some of your own). Name this file “yourlastname_ch4_extracredit.html”.
4. Work on your project website: o Create a sitemap/flow chart of the entire site. o Select your color palette. Be sure to include the RGB and Hex values of the colors. (You should turn this in
in JPG or PDF format. No Illustrator or Photoshop files!) o Select the basic fonts you will use for each element/level of information hierarchy on your site. (Turn this in
in JPG or PDF format. No Illustrator or Photoshop files!) o Create a comp for the homepage of the site. (JPG or PDF format only. No Illustrator or Photoshop files!) o Start gathering content – both text and images. Be sure to have at least the content complete for one page
by next week, since you will use it in the labs.
Labels:
Homework Assignments
Wednesday, April 20, 2011
Class Notes
Logical Operators
Negation !
Tests if something is NOT TRUE.
"Is it true that something is not...."
var loggedIn = false;
if (!loggedIn) {
document.write("Log in Please");
}
Nesting
if (condition) {
//do this
if (condition B) {
//do that
}
}
Arrays
<script type="text/javascript">
var myMagicalList = ['Narnicorns', 'Chupacabra', 'Gelfling'];
//another method - use the Array () function with keyword new
var myMagicalListB = new Array ('Donkey Lips McGee', 'Azreal', 'Orko');
document.write(myMagicalList);
//determine the number of items in an array
document.write('<p>Length of my list is: ' + myMagicalList.length + '</p>');
myMagicalList[myMagicalList.length] = 'Fart Burger';
document.write('<p>Length of my list is: ' + myMagicalList.length + '</p>');
</script>
//pop - remove off the end
//push - add to the end
//shift - take something off the top
//unshift - add to the top
-----------------
Loop
For repetitious task
You have to do these 3 things:
1. Set a counter (how many times am I going to repeat this task
2. Test a condition
3. Change the counter
while
var myCounter = 1;
while (myCounter <= 10) {
document.write("The number is " + myCounter + "<br>");
myCounter++;
for
while + arrays
for + arrays
--------------------------
http://960.gs
http://www.thegridsystem.org
Negation !
Tests if something is NOT TRUE.
"Is it true that something is not...."
var loggedIn = false;
if (!loggedIn) {
document.write("Log in Please");
}
Nesting
if (condition) {
//do this
if (condition B) {
//do that
}
}
Arrays
// Arrays are zero indexed.
<script type="text/javascript">
var myMagicalList = ['Narnicorns', 'Chupacabra', 'Gelfling'];
//another method - use the Array () function with keyword new
var myMagicalListB = new Array ('Donkey Lips McGee', 'Azreal', 'Orko');
document.write(myMagicalList);
//determine the number of items in an array
document.write('<p>Length of my list is: ' + myMagicalList.length + '</p>');
myMagicalList[myMagicalList.length] = 'Fart Burger';
document.write('<p>Length of my list is: ' + myMagicalList.length + '</p>');
</script>
//pop - remove off the end
//push - add to the end
//shift - take something off the top
//unshift - add to the top
-----------------
Loop
For repetitious task
You have to do these 3 things:
1. Set a counter (how many times am I going to repeat this task
2. Test a condition
3. Change the counter
while
var myCounter = 1;
while (myCounter <= 10) {
document.write("The number is " + myCounter + "<br>");
myCounter++;
for
while + arrays
for + arrays
--------------------------
http://960.gs
http://www.thegridsystem.org
Labels:
Week 3
Wednesday, April 13, 2011
Homeworks
Read “Chapter 3 – Adding Logic and Control to Your Programs” from “Javascript: The Missing
Manual”. A PDF of this chapter is located on the class website (listed above).
• Take notes on the reading.
• Do the following tutorials from Chapter 3. For each tutorial, create a separate file , named
as indicated below. (You may create your own file, or you can use the UNFINISHED versions
of the files that you can download from the book website.)
NOTE: Please type out the code yourself. You need the practice! DO NOT simply cut and
paste the code from the download site into your files. You will learn nothing, not understand
the concepts, and will probably fail the class. DO THE WORK, and you’ll learn it!
o Using Conditional Statements – pg 86 (lastname_conditional.html + js files as
needed)
o Do/While – revise earlier tutorial – pg 96 (lastname_do.html + js files as needed))
o Mini‐Tutorial (on Functions) – pg 99 (lastname_minitut.html + js files as needed))
o A Simple Quiz – pg 106 (lastname_quiz.html + js files as needed))
-----------
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
Manual”. A PDF of this chapter is located on the class website (listed above).
• Take notes on the reading.
• Do the following tutorials from Chapter 3. For each tutorial, create a separate file , named
as indicated below. (You may create your own file, or you can use the UNFINISHED versions
of the files that you can download from the book website.)
NOTE: Please type out the code yourself. You need the practice! DO NOT simply cut and
paste the code from the download site into your files. You will learn nothing, not understand
the concepts, and will probably fail the class. DO THE WORK, and you’ll learn it!
o Using Conditional Statements – pg 86 (lastname_conditional.html + js files as
needed)
o Do/While – revise earlier tutorial – pg 96 (lastname_do.html + js files as needed))
o Mini‐Tutorial (on Functions) – pg 99 (lastname_minitut.html + js files as needed))
o A Simple Quiz – pg 106 (lastname_quiz.html + js files as needed))
-----------
Finish the LAB
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
Labels:
Homework Assignments,
Week 2
Chapter 3 / Reading Notes
Adding Logic And Control
Conditional Statements
Used for:
Form Validation : make sure they input information correctly, make sure the field is not empty
Drag and Drop: if the user drags and image somewhere, you can make something happen
Evaluating Input: if you have a popup that asks a question you will want to react accordingly
How to Make a Conditional Statement
There are 3 parts:
1. if
2. ( a true or false question)
3. { if true what should happen}
Comparison Operators
== this is for Equality
<=
<
>= greater than equal to
> greater than
!= not equal
example:
This shows that you can have multiple lines inside the curly brackets.
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
}
If they get the answer correct 1 is added to their score (numCorrect).
Finish-off the statement with else:
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
} else {
alert("Wrong! That's not how many moons Saturn has, you LOOSER.");
}
Logical Operations
&& AND
|| OR (this is the pipes key which is the key above enter, the same key as \ )
! NEGATION
Multiple Conditions
Example from My Lab Work
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("Get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
var cats == prompt('How many cats do you own?');
if (cats <=3 && cats >=1) {
alert('You are good person');}
else (cats >=4) {
alert('You have too many cats, your house must smell');}
}
Conditionals Tutorial
parseInt( variable,10)
This command takes a value and tries to convert it to an integer.
It is different from Number(), because it will convert a string with numbers as well.
20 years >> 20
If it cannot it returns NaN.
var age = '08 years';
age = parseInt(age,10);
(you have to add the 10 so that it gives you 8, instead of 0. Octal vs Decimal Numbers.)
var luckyNumber = prompt('What is your lucky number?', '');
luckyNumber = parseInt(luckyNumber, 10);
if (isNaN(luckyNumber)) {
luckyNumber = prompt('Please, tell me your lucky number.', '');
}
LOOPS
While Loops
While the condition is true it repeats the chunk of code.
while (condition) {
// javascript to repeat
}
This code writes out the numbers 1-5:
var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num = num + 1; }
LOOP and ARRAYS
var animals = ['dogs', 'cats', 'chupacabras', 'bees', 'narnicorns'};
var counter = 0; //sets up a variable counter that will store index number
while (counter < animals.length) { // whileloop. when the index number is less than the total number of items in the array. (animals.length give the total number of items in the array, in this case 5)
document.write(animals[counter] + ', '); //writes that animal
counter++; //adds 1 to the counter
}
For Loops
An easy way to repeat a series of steps
This is a way to re-write the whileLoops example (writing the numbers 1-100), using a forLoop.
for (var num=1; num<=100; num++) { //counter variable; test the condition; add 1 to the number
document.write('Number ' + num + '<br>');
}
Conditional Statements
Used for:
Form Validation : make sure they input information correctly, make sure the field is not empty
Drag and Drop: if the user drags and image somewhere, you can make something happen
Evaluating Input: if you have a popup that asks a question you will want to react accordingly
How to Make a Conditional Statement
There are 3 parts:
1. if
2. ( a true or false question)
3. { if true what should happen}
Comparison Operators
== this is for Equality
<=
<
>= greater than equal to
> greater than
!= not equal
example:
This shows that you can have multiple lines inside the curly brackets.
How many moons does Saturn have?
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
}
If they get the answer correct 1 is added to their score (numCorrect).
Finish-off the statement with else:
if (answer == 31) {
alert('Correct. Saturn has 31 moons.');
numCorrect = numCorrect + 1;
} else {
alert("Wrong! That's not how many moons Saturn has, you LOOSER.");
}
Logical Operations
&& AND
|| OR (this is the pipes key which is the key above enter, the same key as \ )
! NEGATION
Multiple Conditions
Example from My Lab Work
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("Get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
Negating a Condition
! NOT
This is like Bizarro Superman, it completely reverses the results of a condition.
if (! valid) {
//print errors and don't submit form
}
! valid can be translated as “if not valid”
if valid is false, then the condition is true
Nesting Conditional Statements
if (pets == 'youHaveCats') { var cats == prompt('How many cats do you own?');
if (cats <=3 && cats >=1) {
alert('You are good person');}
else (cats >=4) {
alert('You have too many cats, your house must smell');}
}
Conditionals Tutorial
parseInt( variable,10)
This command takes a value and tries to convert it to an integer.
It is different from Number(), because it will convert a string with numbers as well.
20 years >> 20
If it cannot it returns NaN.
var age = '08 years';
age = parseInt(age,10);
(you have to add the 10 so that it gives you 8, instead of 0. Octal vs Decimal Numbers.)
var luckyNumber = prompt('What is your lucky number?', '');
luckyNumber = parseInt(luckyNumber, 10);
if (isNaN(luckyNumber)) {
luckyNumber = prompt('Please, tell me your lucky number.', '');
}
LOOPS
While Loops
While the condition is true it repeats the chunk of code.
while (condition) {
// javascript to repeat
}
This code writes out the numbers 1-5:
var num = 1;
while (num <= 5) {
document.write('Number ' + num + '<br>');
num = num + 1; }
LOOP and ARRAYS
var animals = ['dogs', 'cats', 'chupacabras', 'bees', 'narnicorns'};
var counter = 0; //sets up a variable counter that will store index number
while (counter < animals.length) { // whileloop. when the index number is less than the total number of items in the array. (animals.length give the total number of items in the array, in this case 5)
document.write(animals[counter] + ', '); //writes that animal
counter++; //adds 1 to the counter
}
For Loops
An easy way to repeat a series of steps
This is a way to re-write the whileLoops example (writing the numbers 1-100), using a forLoop.
for (var num=1; num<=100; num++) { //counter variable; test the condition; add 1 to the number
document.write('Number ' + num + '<br>');
}
num<= 100; this part is applied at the beginning of the statement and before each time through the loop
Labels:
Reading Notes,
Week 2
Class Lab / Notes
We will be writing code that makes decisions and comparisons.
The tendency of new programmers is to dive immediately into the syntax vs. outlining a process or approach.
Pseudo Code is your friend.
Making Decisions
Conditional Statements : If Statements
if(the condition to be met is true) {
then do this }
else {
do this instead}
To test multiple conditions: if/else if/else statement
if(the condition to be met is true) {
then do this }
else if (condition to be met){
or do this instead}
else {
or if not that then do this}
Comparison Operators
== this is for Equality
<=
<
>= greater than equal to
> greater than
!= not equal
Logical Operations
&& AND
|| OR (this is the pipes key which is the key above enter, the same key as \ )
! NEGATION
if (conditionA && conditionB) {
//do this stuff
}
This means that both parts have to be true for the whole thing to be true.
If you are using && put the condition that is most likely false first, this stream lines the code because if the first part of the && is not true then it doesn't bother reading the rest.
---------------------
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
The tendency of new programmers is to dive immediately into the syntax vs. outlining a process or approach.
Pseudo Code is your friend.
Making Decisions
Conditional Statements : If Statements
if(the condition to be met is true) {
then do this }
else {
do this instead}
To test multiple conditions: if/else if/else statement
if(the condition to be met is true) {
then do this }
else if (condition to be met){
or do this instead}
else {
or if not that then do this}
Comparison Operators
== this is for Equality
<=
<
>= greater than equal to
> greater than
!= not equal
Logical Operations
&& AND
|| OR (this is the pipes key which is the key above enter, the same key as \ )
! NEGATION
if (conditionA && conditionB) {
//do this stuff
}
This means that both parts have to be true for the whole thing to be true.
If you are using && put the condition that is most likely false first, this stream lines the code because if the first part of the && is not true then it doesn't bother reading the rest.
---------------------
var input = prompt('How much money do you have to spend on lunch at Disneyland?');
var cash = Number(input);
if (cash == 2 && cash < 3 ) {
document.write("Vending Machine Soda") }
else if (cash >= 3 && cash < 5 ) {
document.write("You can get a Churro") }
else if (cash >=5 && cash < 10) {
document.write("Kids Hamburger from Tomorrowland Terrace") }
else if (cash >=10 && cash < 20) {
document.write("Chicken Basket from Frontierland")}
else if (cash >=20) {
document.write("Goofy's Kitchen")}
else if (cash <2) {
document.write ("get more money")}
else {
document.write ('<p>You entered ' + input + ' You did not enter the dollar amount correctly.</p><p>For example: If you have $5.22, please simply enter 5.22')}
Labels:
Week 2
In Class Notes // Review
Attaching an External Script
The advantage is that you have 1 file that effects multiple pages, this makes editing easier.
1. The extension has to be .js
2. you add src:
<script type="text/javascript" src="myExternal.js"></script>
3. make sure there is nothing between the <script> tags
The order that you attach scripts is important.
---------------------------------------------------
Trouble Shooting
Unfortunately the browsers interpret the scripts differently. The different browsers have tools to help you figure out errors.
Firefox:
Tools >> Error Console
Usually the information presented by the console is useless, but it gives you an idea of the area that is probably causing problems.
Firebug:
More usefull
Webdeveloper: (just for Firefox)
A toolbar extension that is really helpful, in particular with jQuery.
Safari:
Develop >>> Show Error Console
--------------------------REVIEW of the READING ASSIGNMENT-------------------------
The advantage is that you have 1 file that effects multiple pages, this makes editing easier.
1. The extension has to be .js
2. you add src:
<script type="text/javascript" src="myExternal.js"></script>
3. make sure there is nothing between the <script> tags
The order that you attach scripts is important.
---------------------------------------------------
Trouble Shooting
Unfortunately the browsers interpret the scripts differently. The different browsers have tools to help you figure out errors.
Firefox:
Tools >> Error Console
Usually the information presented by the console is useless, but it gives you an idea of the area that is probably causing problems.
Firebug:
More usefull
Webdeveloper: (just for Firefox)
A toolbar extension that is really helpful, in particular with jQuery.
Safari:
Develop >>> Show Error Console
--------------------------REVIEW of the READING ASSIGNMENT-------------------------
Operators
Operators are Symbols that allow us to manipulate/modify data.
= assignment operator
(set to the value of)
Math Operators
+ - * /
Order of operations:
PEMDAS aka Please Excuse My Dear Aunt Sally
Parenthesis
Exponents
Multiplication
Division
Addition
Subtraction
M and D have the same weight
A and S have the same weight
so these are performed left to right
(PEMDAS will be on the test)
--------------
Combining Strings
Concatenation
+ the operator use to concatenate
(this is not the same as the mathematical operator + )
var lastName = "Fartyfatkins";
var firstName = "Hugo";
var theName = firstName + ' ' + lastName;
document.write(theName);
The Point this is to show that you should not have the ' ' (space) in the variable declaration.
var lastName = "Fartyfatkins "; BAD
Fixing - Automatic Type Conversion
Number(variable) +Number(variable2)
-------------------------------------
Order of operations:
PEMDAS aka Please Excuse My Dear Aunt Sally
Parenthesis
Exponents
Multiplication
Division
Addition
Subtraction
M and D have the same weight
A and S have the same weight
so these are performed left to right
(PEMDAS will be on the test)
--------------
Combining Strings
Concatenation
+ the operator use to concatenate
(this is not the same as the mathematical operator + )
var lastName = "Fartyfatkins";
var firstName = "Hugo";
var theName = firstName + ' ' + lastName;
document.write(theName);
The Point this is to show that you should not have the ' ' (space) in the variable declaration.
var lastName = "Fartyfatkins "; BAD
Fixing - Automatic Type Conversion
Number(variable) +Number(variable2)
Changing the Values in Variables
score = 0;
score = score + 3;
The point is that everything that happens on the right, gets dumped into the left.
-------------------------------------
Labels:
Week 2
My Homework - Final Project
I'm not really sure of the scope of the assignment so I am submitting two final project ideas.
Project 1
MikannoCon
A group of friends of mine are seeking to create a Orange County Anime Convention and have approached me to create a simple website that would outline the scope of the convention and supply information for potential sponsors and affiliates. At present the website does not exist, so this is not a redo but a from scratch website. I have been given a Word document with several pages of content that is to be divided into main and sub categories.
MikannoCon
A group of friends of mine are seeking to create a Orange County Anime Convention and have approached me to create a simple website that would outline the scope of the convention and supply information for potential sponsors and affiliates. At present the website does not exist, so this is not a redo but a from scratch website. I have been given a Word document with several pages of content that is to be divided into main and sub categories.
I have broken the information into these categories:
Home (Welcome, News)
Registration (Attendees, Volunteers)
Advertising Sales (Advertisements, Sponsorship Program)
Programming (Events: Cosplay, AMV Contest, Fan Video Contest. Guests)
Travel (Hotels, Restaurants)
Contact
The purpose of this site would be to present information to potential attendees and affiliates. Parts of the site such as Registration will have information but will not be fully interactive.
Project 2
Shaffer Sealing
http://www.shaffersealing.com/index.html
This site would be a redo. I would use the current content and reorganize it in a way that is better, specifically easier to read and superior in design. In addition I might include some more images that I would supplied to me by the client.
About the website:
Shaffer Sealing is an asphalt sealing company located in Truckee, California. The website is for potential and current customers to understand more about the company, what they do and how. The site will be divided into 4 sections:
Welcome (basic pitch)
How (what happens when you hire Shaffer Sealin)
Questions/FAQ
Contact
In addition a portion of the website explains another aspect of the business which is snow removal. I will also be incorporating this information into the Shaffer Sealing website.
Labels:
My Homework
Thursday, April 7, 2011
Chapter 2 Notes
Commands
You can recognize commands because they have parenthesis
Web Specific
alert()
document.write()
Universal to Javascript
isNaN() - checks to see if a particular value is a number or not
Types of Data
Numbers
document.write(5 + 15);
whole numbers, decimals, negative
String
can be in double or single quotes
"This isn’t fair" (us double quotes to enclose a string with a single quote inside it)
'He said, "Hello."' is a valid string (how to include quotes in a string)
"He said, "Hello.\ "" (use the \ - an escape character - to tell it to include that quote in the string)
'He said, "This isn\'t fair."' (you have to use the escape character to make that phrase work)
Boolean
you can use boolean value to check if a user did something or not, such as did they supply an email address - true or false
Variables
Stores information for later use
Contain alphanumeric characters and $ and _ (No spaces)
Case-sensitive
Don't use special keywords like alert, break, catch, for, new, this, void.
You can create multiple variables at once like this:
var playerScore, gameRound, playerName;
And you can declare and store multiple pieces of information inside like this:
var playerScore=52, gameRound=1, playerName='Bob';
Basic Math
+ - / *
var price= 5, itemsOrdered=2, totalCost=price*itemsOrdered;
make sure to use parenthesis when having multiple mathematical operations, for example:
(4 + 5) * 10 (this returns 90)
4 + 5 * 10 (this returns 54)
what ever in in the parenthesis happens first.
Combining Strings
Combining strings is called concatenation
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + lastName;
This gives you BobMcPoopface
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + ' ' + lastName;
This gives you Bob McPoopface (with a space)
Combing Numbers and Strings
Automatic Type Conversion
Whenever you use the + operator with a string value and a number it concatenates it to a string
var numOfPoops = 900;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 900 poops today.
Sometimes converting is bad.
For example:
var numOfCatPoops = 25;
var numOfDogPoops = 5;
var numOfPoops = numOfCatPoops + numOfDogPoops;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 255 poops today. (instead of 30)
To prevent this:
(Two ways to convert)
1. Add + to the beginning of the string with the number:
var numTotal = +numStuff
2. Number(variable)
var numTotal = Number(numStuff) + numMoreStuff
You can recognize commands because they have parenthesis
Web Specific
alert()
document.write()
Universal to Javascript
isNaN() - checks to see if a particular value is a number or not
Types of Data
Numbers
document.write(5 + 15);
whole numbers, decimals, negative
String
can be in double or single quotes
"This isn’t fair" (us double quotes to enclose a string with a single quote inside it)
'He said, "Hello."' is a valid string (how to include quotes in a string)
"He said, "Hello.\ "" (use the \ - an escape character - to tell it to include that quote in the string)
'He said, "This isn\'t fair."' (you have to use the escape character to make that phrase work)
Boolean
you can use boolean value to check if a user did something or not, such as did they supply an email address - true or false
Variables
Stores information for later use
Naming Convention for Variables
Starts with a letter, $, _Contain alphanumeric characters and $ and _ (No spaces)
Case-sensitive
Don't use special keywords like alert, break, catch, for, new, this, void.
You can create multiple variables at once like this:
var playerScore, gameRound, playerName;
And you can declare and store multiple pieces of information inside like this:
var playerScore=52, gameRound=1, playerName='Bob';
Basic Math
+ - / *
var price= 5, itemsOrdered=2, totalCost=price*itemsOrdered;
make sure to use parenthesis when having multiple mathematical operations, for example:
(4 + 5) * 10 (this returns 90)
4 + 5 * 10 (this returns 54)
what ever in in the parenthesis happens first.
Combining Strings
Combining strings is called concatenation
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + lastName;
This gives you BobMcPoopface
var firstName = 'Bob';
var lastName = 'McPoopface';
var fullName = firstName + ' ' + lastName;
This gives you Bob McPoopface (with a space)
Combing Numbers and Strings
Automatic Type Conversion
Whenever you use the + operator with a string value and a number it concatenates it to a string
var numOfPoops = 900;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 900 poops today.
Sometimes converting is bad.
For example:
var numOfCatPoops = 25;
var numOfDogPoops = 5;
var numOfPoops = numOfCatPoops + numOfDogPoops;
var message='Your dog ate ' + 'numOfPoops' + 'poops today.';
returns: Your dog ate 255 poops today. (instead of 30)
To prevent this:
(Two ways to convert)
1. Add + to the beginning of the string with the number:
var numTotal = +numStuff
2. Number(variable)
var numTotal = Number(numStuff) + numMoreStuff
Changing the Values in Variables
var score = 0;
score = 100;
var score = 0;
score = score + 100;
Add 100 to what ever value is currently store in "score".
You are preforming a mathematical operation on the value of a variable and then storing that value back into the variable.
Shortcuts:
score += 10;
score = score + 10;
score -= 10;
score = score - 10;
+= -= *= /=
You can also use += for strings:
Adds or subtracts 1
score++
score--
++ --
Arrays
You can store more than one value in a single place, so you don't have to keep creating tons of variables.
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
var listOfStuff = [];
an empty array that can be supplied with information later ( [] two brackets)
Inside of an Array you can store:
Numbers
Strings
Boolean
Arrays
Other Objects
(you can store any combination of from this list)
Getting Items Out of the Array
same as ActionScript, the items have position numbers/index numbers
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July'];
alert(months[2]);
this would return Mar
Change the Value of an Item
months[0] = 'January';
now Jan is changed to January
Get the Last Position of the Array
months[months.length-1];
gets the total number of positions and subtracts 1
so, for months this would be 6 (since I have only listed 7 months)
When working with loops you might want:
var i = 0;
alert(months[i]);
Adding Items to the End of an Array
var properties = ['red', '14px', 'Arial'];
Three ways:
properties[3] = 'bold';
properties[properties.length] = 'bold';
properties.push('bold');
Adding Items to the Beginning of an Array
var properties = ['red', '14px', 'Arial'];
properties.unshift('bold');
you can push and unshift multiple values like this:
properties.push('bold', 'italic', 'underlined');
properties.unshift('bold', 'italic', 'underlined');
push() and unshift() are methods
they return a value, the total items in the array
for example:
var p = [0,1,2,3];
var totalItems = p.push(4,5);
totalItems is 6
Deleting Items from an Array
Similar to Action Script
pop();
shift();
var cats = [Mr.Whiskers, Ugly Cat, Snowball];
var catDeath = cats.pop();
the value catDeath is Snowball
and cats now has [Mr.Whiskers, Ugly Cat]
Adding and Deleting with splice()
this adds and deletes item from the interior positions of the array
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
cats.splice (1,2);
The 1 is the index number
The 2 is the number of positions to delete
var cats = [Mr.Whiskers,Ugly Cat, Snowball];
Only Mr.Whiskers and Prof.Muffintop remains!
var catsAlive = cats.splice (1,0, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
0 indicate you are deleting 0 items
3 new cats are born, now catsAlive has 5 cats!
The Circle of Life, it moves us all.
Replacing Items with splice();
add and delete at the same time
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
var catsAlive = cats.splice (1,2, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
---------------------------------------------------------------------------------------------------------------------------
TUTORIALS
document.write(' <p>');
you can write html into the page
prompt('Tell me your name or I'll doing a flying kick to your face');
this produces a dialogue box similar to alert, but you retrieve an answer
Add 100 to what ever value is currently store in "score".
You are preforming a mathematical operation on the value of a variable and then storing that value back into the variable.
Shortcuts:
score += 10;
score = score + 10;
score -= 10;
score = score - 10;
+= -= *= /=
You can also use += for strings:
var name = 'Bilbo';
var message = 'Hello';
message = message + ' ' + name; >>becomes>> message += ' ' + name;
Adds or subtracts 1
score++
score--
++ --
Arrays
You can store more than one value in a single place, so you don't have to keep creating tons of variables.
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'];
var listOfStuff = [];
an empty array that can be supplied with information later ( [] two brackets)
Inside of an Array you can store:
Numbers
Strings
Boolean
Arrays
Other Objects
(you can store any combination of from this list)
Getting Items Out of the Array
same as ActionScript, the items have position numbers/index numbers
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'July'];
alert(months[2]);
this would return Mar
Change the Value of an Item
months[0] = 'January';
now Jan is changed to January
Get the Last Position of the Array
months[months.length-1];
gets the total number of positions and subtracts 1
so, for months this would be 6 (since I have only listed 7 months)
When working with loops you might want:
var i = 0;
alert(months[i]);
Adding Items to the End of an Array
var properties = ['red', '14px', 'Arial'];
Three ways:
properties[3] = 'bold';
properties[properties.length] = 'bold';
properties.push('bold');
Adding Items to the Beginning of an Array
var properties = ['red', '14px', 'Arial'];
properties.unshift('bold');
properties.push('bold', 'italic', 'underlined');
properties.unshift('bold', 'italic', 'underlined');
push() and unshift() are methods
they return a value, the total items in the array
for example:
var p = [0,1,2,3];
var totalItems = p.push(4,5);
totalItems is 6
Creating a Queue / FIFO
playlist.push('Dumb Song');
nowPlaying = playlist.shift();
This cycles through, you add a song to the end of the list.
Then you play the first song on the list, by removing it and storing it inside nowPlaying. Deleting Items from an Array
Similar to Action Script
pop();
shift();
var cats = [Mr.Whiskers, Ugly Cat, Snowball];
var catDeath = cats.pop();
the value catDeath is Snowball
and cats now has [Mr.Whiskers, Ugly Cat]
Adding and Deleting with splice()
this adds and deletes item from the interior positions of the array
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
cats.splice (1,2);
The 1 is the index number
The 2 is the number of positions to delete
var cats = [Mr.Whiskers,
Only Mr.Whiskers and Prof.Muffintop remains!
var catsAlive = cats.splice (1,0, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
0 indicate you are deleting 0 items
3 new cats are born, now catsAlive has 5 cats!
The Circle of Life, it moves us all.
Replacing Items with splice();
add and delete at the same time
var cats = [Mr.Whiskers, Ugly Cat, Snowball, Prof.Muffintop];
var catsAlive = cats.splice (1,2, 'Snowball Jr., Son of Ugly Cat', "Lil' Kitty Winkins");
var cats = [Mr.Whiskers, Snowball Jr., Son of Ugly Cat, Lil' Kitty Winkins, Prof. Muffintop];
---------------------------------------------------------------------------------------------------------------------------
TUTORIALS
document.write(' <p>');
you can write html into the page
prompt('Tell me your name or I'll doing a flying kick to your face');
this produces a dialogue box similar to alert, but you retrieve an answer
Labels:
Reading Notes,
Week 1
Subscribe to:
Posts (Atom)