Categories
Dev Projects

I made a thing – Score keeper

I’ve been doing a web development course for a few months and today I made my first thing that actually does something. Nothing amazing mind you, but it’s a start.

Do you ever have the need to keep score in a best 2 out of 3 kind of way? Me neither, but here’s a web app that does it regardless  🙂

At some stage, I’ll pop it on a web server and make it live for anyone to use. For now, if you’re interested in the code, take a look at the GitHub repo or you can download it directly.

Update: The app’s now live. Give it a try.

Categories
Dev

Learning from a 579-year-old printing press

Gutenberg is the name of WordPress’ new editor and like its namesake, the Gutenberg printing press, I think it’s going to be a big deal.

Recently I’ve been committing real time to upskill in web development. I wanted to go way outside my comfort zone as an opportunity to grow. So contributing to an open-source project like Gutenberg seemed like a good place to start.

Things I learnt from doing this:

1.  I have no idea what I’m doing, but I can learn anything – Seriously I know nothing! So, when I started looking for something to do to add value I needed something fairly basic. Thankfully Gutenberg is newbie friendly. This presents itself in a number of ways (see point 3) but the first sign of it was the “good first issue” tag on GitHub issues. As the name implies, this shows issue which are good entry points into making a contribution. So after a few days of self-doubt, I picked one and started working on it.

2.  There’s way more to contributing than code – The first thing I needed to do was get my development environment setup. I’d been learning Javascript for a while so I figured I’d be in good shape but in reality, I was miles away. I needed to setup docker, node, NPM and use GitHub with other peoples code. I’d never done any of this before. So before writing a line of code I already had a lot of new learnings. When I did get to coding, I thought I was in for some simple CSS changes. It turns out Gutenburg is using a CSS pre-compiler called Sass. Surprise! I’ve never used that before either, so back to Google University for another lesson.

3.  The community is incredibly supportive – Given the first two points, I needed a lot of advice. When I got stuck or submitted some code there was the community willing to advise and guide on how I could improve. They are also super accessible and transparent, I’d say more so than most work environments I’ve been in. Slack meetings and GitHub issue comments brought genuine insight, and as a result, skill growth. I never would have got any of it without the patience and generosity of the group.

4.  Having your code on millions of websites is a buzz – It’s strange in retrospect, but when I started doing all this it hadn’t occurred to me that if I managed to deliver something it would end up on millions of websites. Now that I have actually done that it does have an addictive feel to it. However minor my contribution is, the scale of the end result is truly massive.

I think at this point it goes without saying I would highly recommend contributing to a project. Regardless of your skill level, there is something to be learned and value to be given and received.

Categories
Geekpulp

Listen to your heart

JavaScript is responsible for the behaviour of your website/app. At the heart of affecting the behaviour of the page is listening for user interaction events. These are things like button clicks, key presses and drags and drops.

To do this, first we select an element then we add an event listener. To add an event listener we use the “addEventListener” function like this:

var button = document.querySelector( "button" );

button.addEventListener( "click", function() {
  console.log( "SOMEONE PLAY SOME ROXETTE!" );
} );

A common pattern is to add event listeners to a set of elements, like each item in a list so each item is clickable. The code for this would look like this:

var listItems = document.querySelectorAll( "li" );
for ( var i = 0; i < listItems.length; i++ ) {
    listItems[ i ].addEventListener( "click", function () {
        this.style.color = "pink";
    } );
}

You can also add multiple event listeners to the same element. So, for example, you can listen for a hover and a click on the same button and take separate actions for each. Listen events are very powerful and a great addition to your JavaScript coding toolbelt.

Categories
Dev

DOM DOM DOM

Playing with the DOM is all about adding interactivity to your page. The DOM (Document Object Model) is the interface between your JavaScript and your HTML+CSS. The browser takes all the elements of your page and turns it into a JavaScript object.

All the elements of the DOM for your page are contained in the object “document”. You can show everything in “document” by using this command in your browser’s console:

console.dir(document);

Working with the DOM is similar to CSS. This is because you select an element then you manipulate it. Here’s an example of what I mean:

var batmanComments = document.querySelectorAll( ".batmanComments" );

In the above example, we are selecting all elements with the class “batmanComments”. Now to do something with our newly selected elements:

var length = batmanComments.length;
for (var i = 0; i < length; i++) {
    batmanComments[i].textContent = “Ironman sucks”
}

This code replaces the contents of each element in the “batmanComments” array with the string “Ironman sucks”… because maturity isn’t Batman’s strength.

If you want more details on working with the DOM, MDN is a good place to start and an even better reference as you’re learning.

Categories
Geekpulp

GitHub flow

I’ve recently been attempting to contribute to some open-source GitHub projects with varying degrees of success. One thing that’s extremely useful to do before you start contributing is to develop a basic understanding of the standard GitHub workflow.

It’s not especially complicated but it can be a real faff if you don’t do it correctly from the start.

Step 1 – Clone the repo

The first thing you’re going to need is your own copy of the project to work on. You do this by cloning the repo to your local machine where you’ll make your changes.

Step 2 – Create a branch

Now you’ve got a local copy you’ll want to create a separate branch for your specific contribution. For example, if you’re working on issue #3271 and issue #3244 you’ll want to create separate branches for each issue. It’s a good idea to name this something like fix/issue#3271 and fix/issue#3244 so you know which branch to submit for what issue once you’re done.

Step 3 – Make commits

Once you’ve made your changes within the appropriate branches make your commits. Commits tell the story of your changes, be sure to write clear concise comments that communicate your intent to other developers reading them.

Step 4 – Submit a pull request

Once you believe you’ve completed your changes create a pull request to submit them. Create one pull request for each issue and corresponding branch you’ve created. Pull request are a way of notifying the projects “owner” of your proposed changes for consideration.

Step 5 – Discuss and refine

It’s likely upon review there will be some conversation around the code and changes. Others may have ideas on different approaches and/or improvements to the update. You can continue to make changes and improvements to refine your solution as a result of these discussions. Just keep making those commits.

Step 6 – Deploy

This part you’re likely to be less involved with. If and when the “owner” decides to use your code they will likely deploy it into the master branch where it will then be tested along with all the other changes made in that round of updates. This is were things get exciting.

Step 7 – Release

Assuming everything is tickety-boo your code is then included in the next production release leaving you with a sense of satisfaction from having helped to make the world a better place one pull request at a time. Don’t forget to be grateful for all the help along the way. Open-source is all about community coming together, so remember to give high fives all around.

Categories
Dev

Load scripts last

So you’ve got your HTML and CSS sorted and you’ve started to drop in some customs scripts to make things a bit interactive. To keep things in shape it pays to develop some good habits early on.

One such habit is placing your scripts just before the closing body tag like this:

...

<script type="text/javascript">
  var secretWords = prompt( "What are the secret words?" );
  var welcomeMessage = document.querySelector( "h1" );
  function unlockBatCave( secretWords ) {
    if ( secretWords === “Ironman sucks” ) {
      welcomeMessage.textContent = “He sure does, right this way sir”;
    } else {
      welcomeMessage.textContent = “Nice try Joker”;
    }
  }
</script>

</body>

</html>

We do this because it allows the full HTML page load before the script runs. This means the page contents will appear faster for the user and the HTML will be ready for you to manipulate it with the script.

The second thing you should do is split your scripts out into a separate file rather than writing them directly into your HTML files. Loads of online tutorials use inline scripting because it’s easy for demonstration purposes, but it isn’t good practice in reality.

Once you’ve moved your code into a separate file update your script tag like this:

<script type="text/javascript" src="your-javascript-file.js"></script>

Categories
Geekpulp

No Comments

When I was first learning to code, something that came up a lot was to always comment your code. Code comments have value, but despite what my teachers at the time may have thought, you should try not to rely on comments.

This isn’t to say you shouldn’t communicate to the reader what the code is trying to do, you should just do that by writing readable code rather than relying on comments.

You do this through a variety of methods, some of which I’ve already covered in previous posts. Things like writing descriptive functions, not abbreviating your variable names, simplifying the code by keeping variables close to the functions that use them, and limiting arguments passed to functions and methods. Bascially this:

var scandal = {
  title: "Moon landing a hoax",
  peopleInvolved: [ "Niel Armstrong", "Buzz Aldrin" ],
  evidenceAvailable: [ "back-stage.mp4", "set-photo.jpg", "confession.pdf" ],
  mediaCoverage [ "www.crackpots.com", "www.flateathers.org" ],
  securityStatus: "TOP SECRECT"
}

function coverUpScandal( scandal ) {
  promotePerson( scandal.peopleInvolved[0] );
  destroy( scandal.evidenceAvailable );
  discredit( scandal.mediaCoverage );
  scandal.securityStatus = "Super duper ultra secret";
}

Is better than this:

//Create a scandal object
var scan = {
  // scandel title
  t: "Moon landing a hoax",
  // names of the people involed in the scandel
  pplIn: [ "Niel Armstrong", "Buzz Aldrin" ],
  // evidence avalible
  ea: [ "back-stage.mp4", "set-photo.jpg", "confession.pdf" ],
  // media outlets covering the scanal
  mc [ "www.crackpots.com", "www.flateathers.org" ],
  // security status of the scandal
  ss: "TOP SECRECT"
}

function cus( scan ) {
  // promote Niel Armstrong
  prmtPrsn( scan.pplIn[0] );
  // destory the scandel evidence
  des( scan.es ); 
  // discredit the media coverage
  dis( scan.mc );
  //change the security status of the scandal
  scan.ss = "Super duper ultra secret";
}

Categories
Geekpulp

DRY variables

The concept of DRY code is simple, Don’t Repeat Yourself. So if you look at some code you’ve just written and notice it’s looking a bit moist, AKA the same stuff repeating over and over, there’s a good chance it’s an opportunity to refactor.

This is also true with variable declaration. Take the this example:

var umbrella = "open";
var raincoat = "on";
var gumboots = "on";
var music = "Singing in the rain";
var action = "Jumping in puddles like a man";
var danceMoves = "The Swim";

Notice how when declaring loads of variables we tend to repeat var a lot? Not very DRY now is it? Let’s put a towel over it:

var umbrella = "Closed",
raincoat = "off",
gumboots = "off",
music = "Walking on sunshine",
action = "slip, slop, slap",
danceMoves = "The twist";

Small difference’s like this add up over the course of a project so it’s best to make these your default habits when you’re a beginner.

Categories
Dev

Equals vs equals

In JavaScript not all comparisons are created equal… see what I did there. Let’s say we’re comparing two values like this:

if ( 42 == “42” ) {
 return “The meaning of life is 42”; 
}

The use of “==“ will compare two values regardless of their type, so in this example, it will return “The meaning of life is 42”. Used correctly this can be fine of course, but it can leave you open to issues like this:

var meaingOfLife = “41”;

if (meaningOfLife == 41) {
  meaningOfLife += 1;
}
return meaingOfLife; 

In this example, we’ve done the same comparison but then tried to add to the meaningOfLife variable which we can’t do because it’s a string, not a number. This is why as a general rule it’s best practice to use “===” for comparison as it will compare both value and type. Here’s an updated example:

var meaingOfLife = “41”;

if (meaningOfLife === 41) {
  meaningOfLife += 1;
}
return meaingOfLife; 

This version will correctly return “41” due to the fact the if statement will return false because the items match in value but not type. Do yourself a favour and default to “===“, it’s the comparison you’re likely to want the majority of the time.

Categories
Geekpulp

Zombie code

Part of developing (and certainly learning to develop) is creating code, commenting it out, and creating a better version. As you get into a flow state with coding it’s really easy to get into he habit of doing this and not going back and clearing out the undead code comments.

Here’s an example of what I’m talking about.

function thriller() {
  return “Something evil\'s lurking from the dark”;
}

//function funkyTown() {
//  chargeKeytar();
//  dressInPastels();
//  return “Gotta make a move to a town that\'s right for me”;
//}
//funkyTown();

thriller();

The trouble with code like this is it’s not clear why the commented out code is there. Is the intention to reworking and use it? Can we remove this because the code was old? Was it commented out accidentally?

Zombie code is ambiguous code, and that’s not helpful for anyone. It’s fine in your own dev environment in the short term, but don’t leave it in too long and never let the zombie out in public. It will only eat everyone’s brains.