ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

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.

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)