JavaScript30 - Day 6

| Comments

Day 6 of #javascript30 is an ajax type ahead form. I learned about the fetch API, promises, asynchronicity, and I might finally understand 'const'.

Fetch API

In the past I have used jQuery's ajax(), get(), or getJSON() for requesting stuff or I have gone to Stack Overflow and copied an XMLHttpRequest like the one below because there was no way I'd remember how to do that from time to time.

var xmlHttp = new XMLHttpRequest();
  xmlHttp.onreadystatechange = function() {
    if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
      console.log(xmlHttp.responseText);
  }
  xmlHttp.open("GET", endpoint, true); // true for asynchronous
  xmlHttp.send(null);

It so much easier to use fetch():

let cities = [];

fetch(endpoint)
  .then(blob => blob.json())
  .then(data => cities.push(...data));

Promises

fetch() returns a Promise object and when the data has been fetched at some point, the code in the then()s is executed. It is an asynchronous call, so it will be executed at some point. This is important and I actually ran into some problems with console.loging my results. My cities array was empty, but if I console.loged the data inside the call to then(), I had the array filled? It was a good learning experience to run into because I realized the asynchronousness (is that a word?) of the promises. I went to Stack Overflow and copied a function that would "sleep" for 2 seconds and then I could console.log my array of cities. Slow internet connection made me understand promises better. Thanks, wonky internet connection!

const finally clicked for me

I finally understood what const is in JavaScript. It is not the same as a constant in PHP, where the value cannot change, so they were a little confusing to me. I went and read the documentation and this part sums it up nicely:

The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g. its parameters) can be altered.

So you can change a const, just not reassign it.

RTFM

This lesson taught me a lot and I took my time reading the documentation for the things I was using. It can hardly surprise anybody that reading the manual is a good idea, but I am actually pleasantly surprised at how good and very readable the docs on MDN (Mozilla Developer Network) are. So if you are also trying to learn more JavaScript, I really recommend spending some time just reading about what you are learning instead of what I normally do which is just hunting for something to copy paste.


JavaScript30 - Day 5

| Comments

This lesson from #javascript30 is showcasing some neat stuff you can do in CSS with Flexbox. While I have used that a couple of times, I feel a little bit about flexbox as I do about JS. I'm not going to get better at it unless I practice. I noticed that the Wes Bos has a 20 video course called What The Flexbox?. I'll definitely check that out. I really like this format.

Transitions and transforms

I love how I am learning how these two go together to make cool effects. Again we use the event transitionend to animate stuff a little extra. If you console.log the event.propertyName it will tell you what is transitioning. Because Safari uses 'flex-grow' instead of 'flex' like all the other browsers we just look for the string 'flex' in the propertyName.

if (e.propertyName.includes('flex')) {
   this.classList.toggle('open-active');
 }

The transition uses cubic-bezier(). I am totally fine with not understanding the math of it, and I found this cool tool to help visualize what the arguments to it do.

include()

I really like the includes() method. It is simpler than for instance PHP's strpos(), because all it does is tell you if a substring is in a string and not where. Keep in mind that include() is case sensitive.

There is also an include() for arrays — same concept and nice and simple.


JavaScript30 - Day 4

| Comments

Arrays

Mr. #javascript30, Wes says that he became a much better programmer when he forced himself to get really good at the array methods. I totally agree that this is central to be good at in most programming languages. Today he talked about these methods in particular:

These are all methods that exist in PHP too, so not many surprises for me there. Wes called them "a gateway drug for functional programming" and if you have dabbled a little with that it makes sense.

I saw this tweet explaining some of the methods and I couldn't help love it:

I didn't know about Array.from() that will make an iterable into an old fashioned array, so you can use that to make for instance a NodeList into an array so you can call map(), reduce(), or whatever array method on it. You can also make something into an array with the spread syntax like so:

const arr = [...cat.querySelectorAll('a')];

Logging arrays and objects

I had totally forgotten about console.table() — I should use that more. It formats like this: console.table()


JavaScript30 - Day 3

| Comments

Day 3 of #javascript30 is using CSS variables and manipulating them with JS. I got my mind blown and I learned about the :root pseudo-element.

CSS variables

The browser support for CSS variables is not great yet. They also have a little bit of a funky syntax with the --:

element {
  --spacing: 10px;
}

That said, I got pretty excited about the cool stuff you can do with them together with JavaScript. I can't wait for better adoption for them but there are hopefully also some polyfills for them out there.

Here is what blew my mind. You can manipulate the variables from JavaScript and the browser updates the CSS. Like this for instance:

var spacing = 12;
document.documentElement.style.setProperty('--spacing', `${spacing}px`);

Boom! I can potentially update hundreds of CSS properties with that line of JavaScript. Nice!

:root pseudo-element

I also learned about the :root pseudo-element. CSS variables declared there are global but you can override variabels on any element on the page like you are used to. CSS still cascades.


JavaScript30 - Day 2

| Comments

Day 2 of #javascript30 is using CSS transform to rotate the hands on a clock.

Manipulating CSS

A HTMLElement has a style property that can be accessed and manipulated like this for instance:

document.querySelector('.second-hand').style.transform = `rotate(${secondsDegrees}deg)`;

Vanilla JS has a toggle() that works just like jQuery's toggleClass(). In fact the classList has a couple of very handy functions that are a lot like stuff jQuery will give you.

Template Literals

The string in back-ticks in the code above is using a Template Literal and I love them. They make it so much easier to write some HTML in JS and to get variable in strings without concatenating them. To use a variable in the string, use the ${yourVar} notation. You can even do stuff like this:

var firstVar = 2;
var secondVar = 2;
console.log(`${firstVar} plus ${secondVar} is ${firstVar + secondVar}`);

and that will output "2 plus 2 is 4". There is also Tagged Template Literals - that will let you apply a function to the variables you "pass in" to the template literal. Pretty neat.


JavaScript30 - Day 1

| Comments

Day 1. I can do this. First of all I would like to thank Wes Bos for the awesome learning material. I haven't really played around with all the cooler visual stuff JS can do and the daily assignments look really visually pleasing. It is going to feel good making them work. Go check out JavaScript30 if you wanna learn JavaScript.

I'm not going to describe what the assignments for the JavaScript30 lessons are, but just pull out the interesting stuff I learned or got refreshed. I am writing this for my own reference too.

Selectors

I had heard about the vanilla JS selectors, but I only used them a couple of times. jQuery has always been my goto.

document.querySelector('.class-name li .last');

Will return an Element if one is found or null if there was no such thing.

And for more than one element:

document.querySelectorAll('.class-name');

Will return a NodeList that can be iterated over using for instance for or NodeList.forEach().

Audio

I had no idea that the <audio> tag was so easy to interact with. Just call .play() on it and it plays! I like it.

Event listeners

CSS transitions are a thing I never even thought about listening for events for, but it exists! I went and found the list of all events and that is really long.


I am bad at JavaScript

| Comments

My name is Camilla and I am bad at JavaScript. I feel ashamed to write this blog post.

I am a backend developer

I consider myself an experienced Drupal and PHP developer. I have a masters in computer science and before I started working with web I was doing enterprise Java for a couple of years. I have a good grasp on object-oriented programming and design patterns as well as a love for writing clean and simple code — something that can only be done by understanding the programming language and the task at hand well.

Changing my mind about JavaScript

Long ago I simply considered JavaScript the enemy. I wanted to stay as far away from it as possible. In all fairness, that was in the beginning of the 2000s, so I might not have been that wrong back then. Later, as more cool things became possible, I thought "hmm, that's kinda neat", but I don't want to write JavaScript - it is just "programming light" and I can do most of those things with backend code and maybe a couple of lines of JS.

Then about 4-5 years ago I started realizing that maybe I was missing out. I got more interested in playing around with JS and I dabbled with some smaller stuff on sites I was working on. I started using Gulp and by now I thought of JS as a super neat thing both in the browser and in other contexts. I got into Elm and thought that was super cool. Probably mostly because then I didn't actually have to write JS. No, seriously - Elm is pretty awesome, but that is another post sometime. I've also played around with backbone.js a couple of years ago and more recently vue.js.

Oh, the shame

By now I should be pretty good at JavaScript.

But I'm not.

I feel like I am always looking stuff up or just stopping because I have to go to Stack Overflow to find answers for the simplest things. I am not in the jQuery hater camp, but I think I blame jQuery a little. I started to dabble without understanding what I was doing. I was using jQuery and I found a lot of example code that I would copy and modify to my needs.

I never actually took the time to understand the basics of the JS language before I started doing cool shit with it, using libraries or frameworks for all kinds of things. Over time I got things done, but got more and more embarrassed over my lack of basic understanding.

In some areas, what makes JS different from most other languages I know, is that apart from being a programming language, it is also an interface to another piece of software: the browser. I feel like that is an important point. Learning to understand that interaction is super important and I don't have that good of a grasp on it.

So what am I going to do about it?

I might want to have the site I work on run with a decoupled frontend someday, or I want to write a plugin (are they called that? Package?) for Webpack or whatever flavour of package manager is in fashion these days. I need to be better at JavaScript before taking any of this on.

I hereby promise the internet that I will learn JavaScript. As in really learn it before I start using libraries or frameworks. I'll do the #JavaScript30 Challenge, I will read up more on ES6, and I will practice and build smaller things just for the sake of learning.

I also think I'll try to blog about what I learn a little. By now I have completely outed myself as a retro-js-noob, so I feel a lot safer blogging about stuff that I am sure a lot of people are wondering about.

Why am I writing this?

That brings me to my final point of this blog post. I am convinced that there are a lot of people out there that feel like me. They have used JS in some capacity for long enough that they should be a lot better at it than they are, and now it is just getting embarrassing that they have so many shortcomings. So if you are out there feeling like that, know that you are not alone.

If you have any tips or resources that you think would be useful to someone like me, please share them!


New Job

| Comments

I am switching to go work for Dagbladet Information (again) from April.

It's been a really hard decision. I had to choose between two different kinds of Drupal awesome. I know—really a first world problem.

Reload has amazing people and great clients that are willing to work agile. I have been super happy with the projects I have been working on and I have worked with a lot of the best Drupal developers in Denmark there. Also, if you would like to work with Reload, check out this job posting!

At Information I will have freedom to travel with work and in the end the freedom won. I am looking forward to working together with Morten Wulff every day no matter where I am in the world. Luxury!


naxoc.net is now on Sculpin

| Comments

I have changed the blogging engine for this blog once again. This blog was on Drupal for a while, then on Octopress (Jekyll), and now on Sculpin. I was never unhappy with either of them—I just enjoy playing around with new stuff every once in a while.

This blog is now a custom Sculpin thing. There is a blog skeleton available to get you started, but I thought I would roll my very own with some heavy inspiration from the skeleton. I also wanted my "theming" to be custom so I could play with new shiny things like Gulp.

I probably spent the most time monkeying around with Gulp. I hadn't used Gulp before and I only had a weak grasp of Grunt, so there was some learning to be done there. I got it working great with Browsersync, Bourbon and sourcemaps. All sweet stuff that I will write more blog posts about.

Using Sculpin is really easy. I never really touched any PHP code other than pasting a little code into SculpinKernel.php to enable redirects via mavimo's Sculpin Redirect Bundle. So all I had to do was create some .html files with Twig syntax to render my markdown files. I could migrate the .md files from Jekyll format pretty easily—I just had to remove the Octopress-specific image tags I had in my markdown.

As a PHP developer I feel much more at home with Sculpin than I did with Octopress and Jekyll. Neither are that hard to use, but I really like how Sculpin is simple and doesn't do too many things I don't need.

The only downside to Sculpin over Jekyll is that hosting the site on Github Pages is a little harder. It is still totally doable, but you have to commit the generated content for Github to be able to serve the pages. I simply chose to just push the generated files to my VPS.

If you are curious about Sculpin and how this blog is created, you can check out my Github repository for naxoc.net.


Switching back to Firefox

| Comments

I have been using Firefox since it came out. I used it back when it was called Firebird and Phoenix. I went to the release party when 1.0 came out and I have advocated using Firefox to anybody that wanted to listen -- and a few that didn't.

2-3 years ago I switched to Chrome along with a lot of other people. Firefox was getting bloated and Chrome had all kinds of shiny tools. But I am back to using Firefox now, and I thought I would explain what lured me back in this post.

I didn't switch because I was tired of, or unhappy with Chrome. I still use both so that I can be logged in to work stuff in one and my own stuff in the other. But I mainly use Firefox for web development now. It should be said that I use the Firefox Beta version and I have had no problems with that. The reason I use the beta is that I really like a couple of the developer tool features, but version 29 also has nice developer tools.

These are some of the features and tools that have impressed me:

Developer Toolbar

Of all the shiny things this one was the one that made me switch. Firefox now has a developer toolbar that sits at the bottom of the page for as long as you want it around. Toggle it with Tools > Web Developer > Developer Toolbar. I just keep it around at all times. To change focus and go to it use shift+F2. You can run commands from text in the toolbar and it also shows a little red badge if there are javascript errors on the page.

So what does it do?

Well, it's a browser command line for web developers. Try typing help and get a list of commands. I use the cookie and inspect [element] most, but the resize toggle is pretty sweet too. Just like CLI it has completion and arrow up gets your history of commands. Another really cool one is media emulate print -- it will show you the page with the print style sheet (or whatever media you put after emulate).

All these things can be done with the mouse too I'm sure, but I like it that I can access these tools really fast with a browser CLI.

Firefox cookies The screenshot shows output from the command cookie list. You can find more info on the toolbar in the mozilla.org docs.

Scratchpad

The scratchpad is a 'js-editor' that lives in its own window. Invoke it from the Tools > Web Developer menu or by going shift+F4. You can write js and execute it with one of the three buttons. The code you write will be in the scope of the browser window you were in when you invoked the scratchpad so you can test your jQuery snippets or whatever does it for you. There are instructions on how to use the buttons in the comment that is displayed at the top of the file. One thing that is left out that is super helpful though is cmd+shift+r. That will reload the browser window, but keep your js code in the scratchpad.

The keyboard shortcuts are the same as for the style editor and the debugger. There are even key bindings for emacs and vim! To set key bindings, go to about:config in Firefox's location bar and set devtools.editor.keymap to "vim" or "emacs".

Pretty inspector

This one is very subjective, but I think that the inspector and the whole developer tools is really pretty. I use the light color scheme, and it just looks better than Chrome's dev tools. I know, but I had to get that one of my chest. There is a dark color scheme setting in the options (click the gear).

There is a font preview tab in the right box on the inspector tab. It's nice to have a clue about the font. I am not a designer, so most the time I don't have a clue. This helps:

Fonts

Another cool thing about the inspector is the "guides" it shows when it highlights an element. It is best illustrated with an image. I am talking about the dotted lines that helps you see if you are aligned with what you want to be aligned with.

Firefox inspector

Network tab

Like with the inspector -- I just think it's pretty. And there are some useful things too! The filtering in the right hand box is really good. There is also a view with pie charts showing the page loaded twice: once with an empty browser cache and once with a primed browser cache. It is quite interesting to compare the two when you are slimming your page weight down. To get to it click the button on the lower right hand when on the network tab: Firefox inspector

You then get this:

Primed cache

See more about the network tab at the developer docs on mozilla.org

Mobile version

I have an Android phone whose factory default browser is Chrome. Firefox can sync between desktop and phone just like Chrome and I think it is as fast. Plus I also just like how it looks.

So what?

I don't have a strong enough opinion to start a browser war. I like both Chrome and Firefox and I will continue to use both. This blog post is just to describe the new cool stuff in Firefox and once again -- whether you want to listen or not -- I encourage you to try Firefox and play around with the new dev tools.