How to access inspected element in browser console

Today I would like to share a very useful trick I learned the other day – how to access previously inspected element in browser console.

Web developers do inspection on web pages almost all the time – Find the ID of an element? Inspect it. Find the size of an element? Inspect it. Find the type of an element? INSPECT IT!

1

Once you get what you want, often times, the next step would be to manipulate it with JavaScript, right? Some developers, including myself, like to test the JavaScript in the browser console first before putting it in the code. To find the inspected element, are you still using getElemenetById or using jQuery’s ID selector? These are NOT very productive! You have inspected the element already, so the console should know what element you are looking for, right? Yes, it does! Just type in $0 (dollar sign and zero), and hit Enter. It will get you the element you just inspected:

2

Now you can do all kinds of things with this handle. To demonstrate this, I just used jQuery to hide the element inspected.

3

Hope you find this trick useful!

Fade in and fade out elements with jQuery

As a mostly backend developer, I am shocked at how long it could take to adjust page layout and transition with CSS/jQuery and try to learn the stuff on the go. I have struggled for probably an hour just to get a logo to display the transition effect that when you move the mouse closer, it turns to a menu button.

So I setup a div containing both the logo and the button, using jQuery’s fadeIn and fadeout method to hide the logo and show the menu button when the mouse moves into this div, and show the logo and hide the menu button when it is out.

<div id="toggle">
   <div id="logo"></div>
   <div id="menubutton"></div>
</div>

And I want one to disappear first before the second shows up. So in the Javascript code, I does this, which is causing problems.

$('#toggle').hover(function() {
    // After logo fades out, fade in the menu button
    $('#logo').fadeOut("slow", function(){
    $('#menubutton').fadeIn("slow"); 
    });
}, function() {
    $('#menubutton').fadeOut("slow", function(){
      $('#logo').fadeIn("slow"); 
    })
});

The problem here is that if you move quickly inside the interactive zone and move out quickly, jQuery will have some weird behavior. This is what I think is happening.

  1. Mouse moves in,
  2. Logo fades out, menu button is going to fade in next,
  3. Mouse moves out,
  4. jQuery tries to fade menu button out, but it is not there yet, so jQuery thinks it’s faded out already, and starts to fade in the logo.
  5. menu button now fades in
  6. So both menu button and logo are shown.

A live demo is here.

So I have to give up the ability to hide one first and then show the second because of this. Here is what I come up with.

$('#toggle').hover(function() {
    $('#logo').fadeOut("slow");
    $('#menubutton').fadeIn("slow"); 
}, function() {
    $('#menubutton').fadeOut("slow");
    $('#logo').fadeIn("slow"); 
});

However, this solution is not complete, because jQuery queues up animations. Moving in and out quickly a few times and you will see the queued animations are being executed after you stop.

A live demo is here.

At this point, what we need to do is just to stop jQuery executing queued animation, which is made easy by the stop() method.

So here is a complete solution for this. I also replaced fadeIn and fadeOut with fadeTo. But both work.

A live demo is here.

$('#toggle').hover(function() {
    $('#show').stop().fadeTo("slow", 0);
    $('#hidden').stop().fadeTo("slow", 1); 
}, function() {
        $('#hidden').stop().fadeTo("slow", 0);
    $('#show').stop().fadeTo("slow", 1); 
});
#toggle {
  border-style:solid;
    border-color:black; 
    height: 200px;
    width: 400px;
}

#logo {
    position: relative;
    float:left;
    top: 0;
    left: 0;
    height: 200px;
    width: 200px;
    background: blue;
}

#menubutton {
    display:none;
    position: relative;
    top: 0;
    left: 200px;
    height: 200px;
    width: 200px;
    background: red;
    z-index: -1
}
<div id="toggle">
   <div id="logo"></div>
   <div id="menubutton"></div>
</div>

Note that using CSS to change the opacity of the elements can achieve the same thing with, though not much, a better performance, but I would prefer to just use jQuery to solve a problem as simple as this and it provides a better cross browser support.

RequireJS jump start

It’s surprising how many senior JavaScript developers don’t know anything about JS Modular Programming. But come to think about it, if my code is working, why do I bother to learn all these AMD, CommonJS, RequireJS stuff? But once you understand it, JS modular programming really makes a big difference. Your code becomes much cleaner and it will require less effort to maintain.

There are many documentations regarding AMD and RequireJS out there. Here I just wanted to provide a quick start guide on RequireJS so people can start using it quickly and find out the rest 90% of the information later.

First let’s briefly talk about the problem we are trying to solve – say we have some code in a .js file that is referenced by a script tag in a HTML page and it defines a few variables and functions. All these stuff will be placed into the global variable set, which is very likely to cause naming conflicts when the project size gets bigger.

That’s why people invented Module Pattern to help encapsulate JS code and reduce the need for creation of global variables. An simple example:

(function (){
   // Now we have a private scope
   var localVar ={};
   function localFunc () {}

   // 'output' a function into global
   this.globalFunc = function(){
       // both localVar and localFunc are available.
   };
}());

In the example, we created a anonymous function block (i.e. anonymous closure) where we can create variables available locally to a global function, globalFunc. However this is still not optimal because it defines a global variable within this block on which the code references it has no control.

Besides this global pollution issue, we also have a dependency issue. Using script tags to load scripts, we have to make sure dependencies are loaded in the correct order. For example, Backbone cannot be loaded before jQuery.

These are the 2 major issues I want to resolve using RequireJS. Now let’s start using RequireJS!

First download Require.js

Create a config file for RequrieJS for easy configuration

/src/requiresjs/config.js

require.config({
  // Set up base path on which the rest of the paths are based
  baseUrl: "../..",
  paths: {
    // This defines where your dependency is.
    // Note that file extension is not needed.
    jquery: "scripts/jquery/jquery",
    // backbone and underscore won't work just like this, but we will get to it later.
    backbone: "scripts/backbone/backbone",
    underscore: "scripts/underscore/underscore"
  }
  // This defines the startup script of your application.
  deps: ["src/main"]
});

Then in your main html page, add just one script tag. Just specify the path of RequireJS and set the path of the config file in the data-main attribute. What this does is to allow RequireJS to find the config file and start your main.js script specified in the config file.

/src/pages/index.html

<script type="text/javascript" src="/scripts/requirejs/require.js" 
data-main="/src/requirejs/config">
</script>

In your main.js file, define a module.

/src/main.js

define(["jquery", "underscore", "backbone"], function($, _, Backbone) {
  // The first array argument includes the path variables defined in the config file.
  // The second argument is a definition function that accepts modules as arguments.
  // It will be called after all the modules in the first argument are loaded.

  // Now you have variable $ for jQuery, _ for underscore, and Backbone for backbone.js
});

The example shows that RequireJS allows us to load a module in js code at the time we need it, and we have full control on what variable name it should be assigned to. Moreover, it automatically loads all the dependencies of the module before it is loaded.

Back to our config file, the setup for backbone and underscore is not complete, because they are non-AMD scripts. Simply put, they didn’t follow AMD standard to define themselves. For these modules, we need to add in the config file a shim configuration.

/src/requiresjs/config.js

require.config({
  baseUrl: "../..",
  paths: {
    jquery: "scripts/jquery/jquery",
    backbone: "scripts/backbone/backbone"
  },
  shim: {
    backbone: {
      exports: "Backbone",
      // Specify the dependencies of backbone
      deps: ["underscore", "jquery"]
    },
    'underscore': {
       exports: '_'
    }
  }
  deps: ["src/main"]
});

Now the configuration and the example are complete.

Note that there is another way to define your module. I prefer this approach just because it looks more straightforward. It is called CommonJS style definition.

/src/main.js

// just pass in a require argument, it will work.
define(function(require) {
  // find modules' paths using the variables defined in the config file
  // and put it in a local variable.
  var $ = require("jquery");
  var _ = require("underscore");
  var Backbone = require("backbone");
});

There is much more about RequireJS and AMD in general that one can dig into. I recommend to read more from RequireJS’s site, but hopefully this gives you a general idea of modular programming and something to start with.

Responsive Web Design: Serving Images Efficiently

Delivering images with the right resolution to different client resolutions is a basic of the responsive design of web applications. There are a few ways to achieve that, one of them being using the Media Query of CSS, but in this blog post I am going to present a different approach – Severing images with JavaScript.

I believe I learned this trick from ASPConf. Forgot the name of the speaker, but he is a talented guy!

First, add to the img DOM a separate attribute for the URL of the image for each resolution.


<img regularSrc="LowResImgURL"  retinaSrc="RetinaImgURL" />

Then in $(document).ready, use the following code to serve the correct images to the client, which sets up the src attribute of img DOM with the correct URL at run-time.


$("img").attr("src", fucntion(i, val){
var $this = $(this);
if(isRetina){
return $this.attr("retinaSrc");
}else{
return $this.attt("regularSrc");
}
});

Easily display loading animation with jQuery

Giving users a proper feedback is one of the most important design items toward a good user experience. Showing the user a loading animation such as a loader or spinner after a request is submitted is something we see quite often. So how to add a loading animation to your own web site? Hopefully the following tutorial can give you a jump start.

First, find a loading animation that suits your need. This Ajax loading GIF generator is a good option to find a decent GIF image. Or you could go for a pure JS and CSS loading animation like the ones in the Collection by Tim Holman.

Then put the animation on the same page where you want to show it and hide it.

Lastly, use the following codes that show the animation whenever an ajax call has been initiated and hide it when finished.


$(document).ajaxStart(function () {
 $YourLoadingAnimation.show();
 }).ajaxStop(function () {
 $YourLoadingAnimation.hide();
 });

References:

jQuery API – ajaxStop

jQuery API – ajaxStart

Use Reflection in C# to dynamically retrieve properties

One good thing about JavaScript is the simplicity of working on object property. For example,  to traverse all properties of an object:

for(var propNamein myObject){
// Access the property value like this -
// myObject[propName] or myObject.propName
}

You may want to use hasOwnProperty () and isPropertyEnumerable to further filter the properties but it is simple enough.

Also to add or delete a property is just as simple as

Delete myObject.propName; // Delete property
myObject.propName = propValue;  //Add property

The best part is that you can retrieve a property just using a string variable to match its name.

var propName = "color";

var rabbit = {};
rabbit.color = "white";
console.log(rabbit[propName]); // it prints "white"

Of course, a well-developed language such as C# must also have a way to dynamically work on properties – Reflection.

Reflection can achieve many things but here we are only going to talk about property manipulation.

To get a list of properties of an object –

PropertyInfo[] propObjects = myObject.GetType().GetProperties();
// This returns an array of PropertyInfo objects,
// which is basically your property.

To traverse an object’s properties and work with them –

foreach(PropertyInfo prop in propObjects)
{
// access the property's name - prop.Name
// access the property's value - prop.GetValue(myObject)
// to set a property's value - prop.SetValue(myObject, propValue);
}

It is worth mentioning that when retrieving a certain property with name, ignoring case may be needed. To achieve that –

var value =
  myObject
   .GetType()
   .GetProperty(
    propName,
    BindingFlags.IgnoreCase|BindingFlags.Public|BindingFlags.Instance
    )
   .GetValue(myObject);

Note that all three binding flags are necessary, otherwise it won’t work.

Reference:

C# Reflection

Technical Recluse from Eloquent JavaScript

I have been reading a book named Eloquent JavaScript  (license). The author is Marijn Haverbeke. The book is great as an introduction to JavaScript as well as an introduction to programming. Besides, the author included a number of humorous stories and analogies to describe some concepts and they worked pretty well.

Below is an excerpt about a recluse who wants to write a technical book from chapter 6. Marijn has even provided several paragraphs of the book the recluse wrote. I have to say there are some philosophies in the book! (Partly because he cited some stories from programmer Fu-Tzu who does not even use 286-computer or MS DOS anymore.)


There once was, living in the deep mountain forests of Transylvania, a recluse. Most of the time, he just wandered around his mountain, talking to trees and laughing with birds. But now and then, when the pouring rain trapped him in his little hut, and the howling wind made him feel unbearably small, the recluse felt an urge to write something, wanted to pour some thoughts out onto paper, where they could maybe grow bigger than he himself was.

After failing miserably at poetry, fiction, and philosophy, the recluse finally decided to write a technical book. In his youth, he had done some computer programming, and he figured that if he could just write a good book about that, fame and recognition would surely follow.

So he wrote. At first he used fragments of tree bark, but that turned out not to be very practical. He went down to the nearest village and bought himself a laptop computer. After a few chapters, he realized he wanted to put the book in HTML format, in order to put it on his web-page…

(Here goes some introductions to basic HTML. The Marijn talked about encoding <, >, and &  into &lt;, &gt;, and &amp;)

So, picking up the story again, the recluse wanted to have his book in HTML format. At first he just wrote all the tags directly into his manuscript, but typing all those less-than and greater-than signs made his fingers hurt, and he constantly forgot to write &amp; when he needed an &. This gave him a headache. Next, he tried to write the book in Microsoft Word, and then save it as HTML. But the HTML that came out of that was fifteen times bigger and more complicated than it had to be. And besides, Microsoft Word gave him a headache.

The solution that he eventually came up with was this: He would write the book as plain text, following some simple rules about the way paragraphs were separated and the way headings looked. Then, he would write a program to convert this text into precisely the HTML that he wanted.

The rules are this:

  1. Paragraphs are separated by blank lines.
  2. A paragraph that starts with a ‘%’ symbol is a header. The more ‘%’ symbols, the smaller the header.
  3. Inside paragraphs, pieces of text can be emphasized by putting them between asterisks.
  4. Footnotes are written between braces.

After he had struggled painfully with his book for six months, the recluse had still only finished a few paragraphs. At this point, his hut was struck by lightning, killing him, and forever putting his writing ambitions to rest. From the charred remains of his laptop, I could recover the following file:

% The Book of Programming

%% The Two Aspects

Below the surface of the machine, the program moves. Without effort,
it expands and contracts. In great harmony, electrons scatter and
regroup. The forms on the monitor are but ripples on the water. The
essence stays invisibly below.

When the creators built the machine, they put in the processor and the
memory. From these arise the two aspects of the program.

The aspect of the processor is the active substance. It is called
Control. The aspect of the memory is the passive substance. It is
called Data.

Data is made of merely bits, yet it takes complex forms. Control
consists only of simple instructions, yet it performs difficult
tasks. From the small and trivial, the large and complex arise.

The program source is Data. Control arises from it. The Control
proceeds to create new Data. The one is born from the other, the
other is useless without the one. This is the harmonious cycle of
Data and Control.

Of themselves, Data and Control are without structure. The programmers
of old moulded their programs out of this raw substance. Over time,
the amorphous Data has crystallized into data types, and the chaotic
Control was restricted into control structures and functions.

%% Short Sayings

When a student asked Fu-Tzu about the nature of the cycle of Data and
Control, Fu-Tzu replied 'Think of a compiler, compiling itself.'

A student asked 'The programmers of old used only simple machines and
no programming languages, yet they made beautiful programs. Why do we
use complicated machines and programming languages?'. Fu-Tzu replied
'The builders of old used only sticks and clay, yet they made
beautiful huts.'

A hermit spent ten years writing a program. 'My program can compute
the motion of the stars on a 286-computer running MS DOS', he proudly
announced. 'Nobody owns a 286-computer or uses MS DOS anymore.',
Fu-Tzu responded.

Fu-Tzu had written a small program that was full of global state and
dubious shortcuts. Reading it, a student asked 'You warned us against
these techniques, yet I find them in your program. How can this be?'
Fu-Tzu said 'There is no need to fetch a water hose when the house is
not on fire.'{This is not to be read as an encouragement of sloppy
programming, but rather as a warning against neurotic adherence to
rules of thumb.}

%% Wisdom

A student was complaining about digital numbers. 'When I take the root
of two and then square it again, the result is already inaccurate!'.
Overhearing him, Fu-Tzu laughed. 'Here is a sheet of paper. Write down
the precise value of the square root of two for me.'

Fu-Tzu said 'When you cut against the grain of the wood, much strength
is needed. When you program against the grain of a problem, much code
is needed.'

Tzu-li and Tzu-ssu were boasting about the size of their latest
programs. 'Two-hundred thousand lines', said Tzu-li, 'not counting
comments!'. 'Psah', said Tzu-ssu, 'mine is almost a *million* lines
already.' Fu-Tzu said 'My best program has five hundred lines.'
Hearing this, Tzu-li and Tzu-ssu were enlightened.

A student had been sitting motionless behind his computer for hours,
frowning darkly. He was trying to write a beautiful solution to a
difficult problem, but could not find the right approach. Fu-Tzu hit
him on the back of his head and shouted '*Type something!*' The student
started writing an ugly solution. After he had finished, he suddenly
understood the beautiful solution.

%% Progression

A beginning programmer writes his programs like an ant builds her
hill, one piece at a time, without thought for the bigger structure.
His programs will be like loose sand. They may stand for a while, but
growing too big they fall apart{Referring to the danger of internal
inconsistency and duplicated structure in unorganized code.}.

Realizing this problem, the programmer will start to spend a lot of
time thinking about structure. His programs will be rigidly
structured, like rock sculptures. They are solid, but when they must
change, violence must be done to them{Referring to the fact that
structure tends to put restrictions on the evolution of a program.}.

The master programmer knows when to apply structure and when to leave
things in their simple form. His programs are like clay, solid yet
malleable.

%% Language

When a programming language is created, it is given syntax and
semantics. The syntax describes the form of the program, the semantics
describe the function. When the syntax is beautiful and the semantics
are clear, the program will be like a stately tree. When the syntax is
clumsy and the semantics confusing, the program will be like a bramble
bush.

Tzu-ssu was asked to write a program in the language called Java,
which takes a very primitive approach to functions. Every morning, as
he sat down in front of his computer, he started complaining. All day
he cursed, blaming the language for all that went wrong. Fu-Tzu
listened for a while, and then reproached him, saying 'Every language
has its own way. Follow its form, do not try to program as if you
were using another language.'