ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Adventures in Learning Javascript

Updated on December 1, 2014

Why: The Final Goal

Obviously, I want to be able to write my own programs. I have plenty of ideas, but the one I most want is a modified version of the HTML/CSS page I use as a client demo when designing websites.

I also want to be able to write my own Greasemonky and XKit extensions. And I have a cool timer app on my iPod which I'd like to have in other places as well (especially since my iPod is old and starting to deteriorate. It's not worth buying a whole new device for one app… but I love this app). I'm focusing on the web design program, but if I notice something useful for one of my other ideas, I'll make sure to take some extra notes.

What: The Nitty-Gritty Things to Learn

For learning JS in general:

  • Basic Javascript terms (the vocabulary of the JS programming language)
  • Basic Javascript syntax (how to write something in Javascript so the computer actually understands it)

The specific things I need to learn for my web design demo program:

  • How to get Javascript running on an HTML/CSS web page
  • How to allow users to input colours which change the appearance of a web page
  • How to use Javascript to alter and/or generate CSS

How: Goals for Learning Javascript More Easily

  • Study every day. Using Codecademy for starts, though i might switch to something else once i've got the basics down if Codecademy starts focusing on details i don't expect to use.
  • Pin Codecademy to the 'new tab' page in my browser to make accessing lessons even faster.
  • Update my in-progress programs as i learn the necessary code, so i can put what i'm learning to immediate practical use.

Let the learning begin…

Day One: Learning Useful Syntax

Javascript
What it does
confirm("Message!");
presents a message with cancel/OK buttons
prompt("Question?");
presents a dialogue box with a text field
if (x) { y(“do a thing”); };
format for a basic if/then statement
if (x) { y(“do a thing”); } else { z(“do a different thing”); };
format for if/then/else statement
var x = y;
declares the variable x and assigns y to it
x = z;
assigns z to the variable x
x === y
boolean test to confirm if y is equal to x (mostly useful in things like 'if (x === y) {"do the thing";};')
Super basic beginner stuff. You can do a surprising amount just messing around with inputting variables and using if/else statements.
Codecademy instructions: write and then expand upon a rock-paper-scissors game. End result: rock-paper-scissors-lizard-Spock.
Codecademy instructions: write and then expand upon a rock-paper-scissors game. End result: rock-paper-scissors-lizard-Spock.

Day Five: The Hazard of Infinite Loops

Codecademy tutorial: Be very careful with your syntax—if you write a loop that can't properly end, it's called an infinite loop. It will crash your browser!
Keelan: Yeah yeah yeah, i know i'm just learning JS but i think i've got basic *syntax* down.
Keelan: *writes code and hits submit button*
Keelan: Wow what is going on with Firefox, i know *my* code is good, why's it crashing when i'm trying to do a coding lesson.
Keelan: *looks at my code*
Keelan: *looks at code i was actually supposed to write*
Codecademy: …
Codecademy: you maybe wanna restart the browser there code boy.

Why are Infinite Loops Bad?

In programming, an infinite loop is a bit of code which will run repeatedly. Never stopping. Never changing.

Or at least, not changing in a way which gets out of the loop.

For example… 'for' loops, repeat a task a certain number of times. But a tiny typo can lead to the loop never stopping.

for (var i=0;i < 6;i++) {console.log("I am counting to " + i);}; // This will count up to five, then stop.

for (var i=0;i < 6;i--) {console.log("I am counting down from " + i);}; // This will count down, as long as the variable i is less than 6… but i starts at 0, and keeps going down, so it's always less than 6. i > -6 would have successfully closed the loop, but this loop will go on infinitely… or at least until you close your browser.

Your browser will have no reason to leave the loop: it only run the loop over and over. The most obvious problem here is, the browser will never reach any code after the loop. The browser will also be too preoccupied with running the loop to bother doing, well, anything else.

And then your browser will crash.

Oops.

Solution: Double-check your loops and always make sure there's a way for them to end.

camelCase will be the death of me. or at least the death of my code.
camelCase will be the death of me. or at least the death of my code.

Day Twelve: Error Messages and Their Uselessness*

*(They also don't exist in most editors. At least not to the extent they exist in Codecademy or similar learning-based editors. But that's an issue for people who already know what they're doing to contend with.)

Oops, try again. Did you create a function called search?

Yes, Codecademy, i did indeed create a function called search. Lemmee try this again…

Oops, try again. Did you create a function called search?

*sigh* *deletes code* *rewrites*

Oops, try again. Did you create a function called search?

*deletes everything but the outer shell of the function*

Oops, try again. It looks like your search function doesn't return contact information for Steve.

Okay, so you acknowledge the function is there… *rewrites code*

Oops, try again. Did you create a function called search?

*adjusts punctuation*

Oops, try again. Did you create a function called search?

Yes! Yes, i created a function called search! You know i created a function called search, because when i show you the function with nothing inside it, you acknowledge it as there! Can i get a useful error message now?

*gives in and clicks 'Hint' button*

…oh. it's [key] not .key.. okay. simple mistake.

*adjusts punctuation*

Oops, try again. There was a problem with your syntax. SyntaxError: missing ) in parenthetical.

Finally! An error message i can actually use!

*adjusts punctuation*

Oops, try again. Did you create a function called search?

*copy-pastes hint code into editor and goes through, line by line, searching for the monstrous error which has plagued me for so long, the Elder God-level error which prevents Codecademy's editor from even acknowledging a function, the… single, improperly capitalised word*

*changes firstname to firstName*

Way to go!

Day 24: On to JQuery

I've finished Coursera's Javascript course, woohoo! I learned plenty, but I still can't write a program which works with user input (at least, not without annoying dialog boxes). I can always edit the code to run with the input I want… but it'd be much more efficient if I could punch the data into my web browser.

So, on to jQuery. With any luck this will put my Javascript knowledge right where I want it to be.

Colour-Coded

Standard Bootstrap screenshot. Clean. Professional. Not everyone's cup of tea.
Standard Bootstrap screenshot. Clean. Professional. Not everyone's cup of tea.
Bright, friendly, and using my old CSS method, took more time to change the CSS than to design the colour scheme.
Bright, friendly, and using my old CSS method, took more time to change the CSS than to design the colour scheme.
Muted, quiet, and using the jQuery method, took all of three minutes – including time spent fine-tuning colours which seemed like a good idea at first but didn't quite work once they were on the site with all the other colours.
Muted, quiet, and using the jQuery method, took all of three minutes – including time spent fine-tuning colours which seemed like a good idea at first but didn't quite work once they were on the site with all the other colours.

Day 27: This is Definitely Worth the Effort

Today's coding discovery: You can use jQuery to create new CSS.

Best of all, you can use jQuery variables in this CSS.

Do y'all have any idea how amazing this is when you're only changing five colours – but on dozens of different elements.

Last week my sad, jQuery-free job included lots of copy-and-paste or muttering hex codes under my breath, finishing a hundred-line sheet of this… and then cursing a bit as I realised one of those hex codes looked a bit too dark but hey, at least now I can just use the find/replace feature.
Many times.
Until I hit just the right colour to look good every place the particular colour goes.

Now?

var col = ['#333','#649400','#c2de5d','#ffc352','#feb752','#fff16e'];
$(document).ready(function(){
// css aka SWEET I ONLY NEED TO TYPE ALL THESE NUMBERS ONCE AND THEY ALL GO IN THE RIGHT PLACE
$('.navbar').css('background-color',col[3]);
$('.navbar').css('border-color',col[4]);
$('.navbar a').css('color',col[5]);

It's glorious. Change the colour site-wide? Change it in one spot. Change the colour of one element? Change one digit, not a whole hex code. I can even use rgb codes instead of hex. Okay, I could have used rgb codes before. I like rgb codes – it's easier for me to make exactly the alterations I want with them. But it's also easier to remember six digits than nine when you need to tinker with those digits in several locations.

I'm sure there's more efficient ways to do it than this. But this. This makes me happy.

Day 29: User Input Variables

A more efficient update to my CSS:

$(document).ready(function(){
// colour variables
var col=['#333'];
var colf='#fff';
$('a.btn').click(function(){
col[1]=$('input[name=colour1]').val();
col[2]=$('input[name=colour2]').val();
col[3]=$('input[name=colour3]').val();
col[4]=$('input[name=colour4]').val();
col[5]=$('input[name=colour5]').val();
// css
$('body').css('background-color',colf);
$('body').css('color',col[0]);
$('h2, a').css('color',col[3]);

I can put the colour codes I want right in my demo site and see them update with the click of a button. No more needing to open up TextWrangler to test new colour variables. I may have started singing "I've Got the Power" when I got this working.

Now if only I can get that CSS out of the jQuery and into a CSS file.

Day 40: Fun with Regex

Disclaimer: I might not be 100% certain how this works yet. But I spent all my coding practice time for a week trying to figure it out, and it does work, and I at least think I know why.

At any rate it's proven useful in several functions. Especially functions in which I need to do something with RGB colour codes.

The technobabble: newRgb=rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)/i);

Translation:

  • rgb.match(); – basic .match(); Searches for the regex gibberish in the defined string.
  • ^rgba? – starts the search with rgb. May or may not include an 'a'.
  • [\s+]? – \s is a whitespace. \s+ is one or more whitespaces. [\s+]? is maybe-there's-a-space, maybe-there-isn't. There's a lot of these and all they do is make it so 'rgb(0,0,0)' and 'rgb (0, 0, 0)' both work.
  • \( – looks for the opening parenthesis of the RGB code. With an escape \ in front, since regex also uses parenthesis. Like the ones used in (\d+)…
  • (\d+) – looks for any number of digits. And, with () instead of [], puts those digits in a nice useful array.
  • , – plain boring normal comma. Just here because RGB codes have commas and it breaks the regex to ignore them.
  • /i – makes the whole thing case-insensitive. Case doesn't matter for the numbers but it does make a difference between RGB(0,0,0) and rgb(0,0,0)

Put all the above in the right order, and the end result: a four-variable array. All the searched-for regex – most of an RGB code – ends up in newRgb[0]. The original RGB code's individual R, G, and B values land in positions 1, 2, and 3. Useful for everything from converting RGB to hex to testing colour contrast, if you stick it in the right function.

Comments

    0 of 8192 characters used
    Post Comment

    No comments yet.