Rezha Julio

Hi!
My name is Rezha Julio
I am a chemist graduate from Bandung Institute of Technology. Currently working as Data Engineer at Traveloka.
You can reach me by email:

contact@rezhajulio.id

, @ Q Q

Powered by Hugo

filter by tags

JS & Dom - Tips & Tricks #3

time to read 2 min | 376 words

As you might already know, your browser’s developer tools can be used to debug JavaScript by utilizing breakpoints. Breakpoints allow you to pause script execution as well as step into, out of, and over function calls. Breakpoints are added in your developer tools by means of line numbers where you indicate where you want script execution to be paused.

This is fine until you start changing your code. Now a defined breakpoint may no longer be in the place you want it to be. Take the following code as an example:

function doSomething() {
  console.log('first log...');
  console.log('last log...');
}

doSomething();

If I open this code in my browser’s developer tools debugger, I can place a breakpoint before one of the lines inside the doSomething() function. Let’s say I want to pause script execution before the “last log…” message. This would require that I place the breakpoint on that line. In this case, it would be line 3 of my code.

But what if I add the breakpoint, then I add another line of code before that line?

function doSomething() {
  console.log('first log...');
  console.log('second log...');
  console.log('last log...');
}

doSomething();

If I refresh the page, the breakpoint will still be there but now the script will pause execution on the “second log…” message instead of the “last log…” message. Again, this is because the breakpoints are based on line numbers. The debugger is still stopping on line 3, but that’s not what we want.

Enter JavaScript’s debugger statement.

Instead of setting breakpoints directly in the developer tools, I can use the debugger statement to tell the developer tools where to pause execution:

function doSomething() {
  console.log('first log...');
  debugger;
  console.log('last log...');
}

doSomething();

Now I can add as much code as I want prior to the debugger statement and the script will still pause in the right place, without any concerns over changing line numbers.

If you’ve been writing JavaScript for a while, I’m sure this tip is nothing new to you. But those new to debugging will certainly benefit from using this feature, which is part of the official ECMAScript spec. As expected, inserting a debugger statement will have no effect on your code if a debugger is not present (e.g. if the developer tools are not open).

JS & Dom - Tips & Tricks #2

time to read 2 min | 339 words

Last year, David Walsh published an article called 7 Essential JavaScript Functions where he shared some JavaScript utility/helper snippets. One of the interesting techniques used in one of the functions is where he gets the absolute URL for a page. He does this using something like the following:

var getAbsoluteUrl = (function() {
  var a;
  return function(url) {
    if(!a) a = document.createElement('a');
    a.href = url;
    return a.href;
  };
})();

// Usage
getAbsoluteUrl('/something'); // https ://example.com/something

This example reveals a clever little technique. Basically, this function takes advantage of JavaScript’s ability to create elements that don’t actually exist in the DOM. From there, you can get info from that element as you please. In this case, the desired result is the full URL of the page. The browser automatically fills out full URLs in the href value of links, even if they’re written in relative format. So with this we can easily grab the full URL from just a relative page link.

Similarly, someone in the comments posted the following snippet:

function isValidEmail(string) {
  string = string||'';
  var lastseg = (string.split('@')[1]||'').split('.')[1]||'',
      input = document.createElement('input');
      input.type = 'email';

  input.required = true;
  input.value = string;
  return !!(string && (input.validity &&
                       input.validity.valid) && 
                       lastseg.length);
}

console.log(isValidEmail('')); // -> false
console.log(isValidEmail('asda')); // -> false
console.log(isValidEmail('asda@gmail')); // -> false
console.log(isValidEmail('asda@gmail.com')); // -> true

There’s a lot going on there, but the principle is the same. The script creates an email input field, without actually inserting it into the page, and then information is gleaned from the input. The acquired info falls in line with what the browser would do if the email input actually existed and was interacted with on the page. This is along the same lines as what happens with feature detection using a library like Modernizr.

So the basic lesson here is, if you want to find out info on how a browser handles certain HTML elements, remember that those elements don’t actually have to be in the DOM. You can create them yourself and then run some tests and respond accordingly.

JS & Dom - Tips & Tricks #1

time to read 2 min | 320 words

There are many ways to read content from elements and nodes. Here’s another one that allows you to read and write an individual node’s value. It uses the nodeValue property of the Node interface. The nodeValue of an element will always return null, whereas text nodes, CDATA sections, comment nodes, and even attribute nodes will return the text value of the node. To demonstrate its use, I’ll use the following HTML:

<body class="home">
  <p>Example. <span>Example paragraph one.</span></p>
  <p>Example paragraph two.</p>
  <p>Example paragraph three.</p>
  <p>Example paragraph four.</p>
  <!-- comment text -->
</body>

Now I’ll run the following JavaScript to read/write a few of the nodes:

let b = document.body,
    p1 = document.querySelector('p');

// reading node values
console.log(b.nodeValue); // null for all elements
console.log(b.attributes[0].nodeValue); // "home"
console.log(b.childNodes[7].nodeValue); // " comment text "

// changing nodeValue of first node inside first paragraph p1.firstChild.nodeValue = 'inserted text<br>';

Notice the second console.log is displaying the text of an attribute node. This would be the equivalent of using getAttribute(), with the difference being that getAttribute() acts on elements, whereas nodeValue can be applied to any type of node.

Also notice that I’m using nodeValue to read the contents of an HTML comment. This is one of many ways you can do this. This would be the equivalent of reading the textContent property or data property of the comment node. As you can see from the final line in that code example, I’m able to define the nodeValue of one of the text nodes, so this isn’t read-only.

A few other things to note regarding defining the nodeValue property: Setting nodeValue will return the value that was set, and you cannot set the nodeValue when the nodeValue is null (unless of course you change it to null, which is the same as an empty string that’s changeable later).

MDN’s article on nodeValue has a chart that lists the different node types and what their nodeValue will return.

RECENT SERIES

  1. java 101 (13):
    Apr 29, 2017 - Translating Scanner tokens into primitive types
  2. python data structure (5):
    May 03, 2017 - Enhance your tuples
  3. python function (2):
    Apr 16, 2017 - Lambda Functions in Python
  4. python generator (4):
    Apr 26, 2017 - Next, Function or Method ?

Friends of Rezha