Rectangle 27 819

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

@nawfal yes i dont like Atom multiple processes the final 1.0 version isnt released yet and solving memory issue is on their roadmap for 1.0 , lets see !

The problem with these tools is that you never get the full performance out of javascript. Yes, it provides good readability but the compiled code is sometimes very clunky. You rely on a third-party tool to write native javascript, I think this is not the way to go, it's like transforming a language to another language. Wanting to change a language that's not another language to behave like another language you like, that's stupid and silly. ...... (end of part 1)......

@Erwinus: Did you still program with assembler?

@Erwinus The point of TypeScript is to provide compile time type checking. If you don't see the value in that, that's perfectly fine. TypeScript has been refereed to as "your first unit test". There are many resources that discuss whether or not optional type checking has value, and are more detail than what we can do here. I'm not trying to convince you of anything, just correcting a misconception.

What is TypeScript and why would I use it in place of JavaScript? - St...

javascript typescript
Rectangle 27 819

TypeScript is a superset of JavaScript which primarily provides optional static typing, classes and interfaces. One of the big benefits is to enable IDEs to provide a richer environment for spotting common errors as you type the code.

To get an idea of what I mean, watch Microsoft's introductory video on the language.

For a large JavaScript project, adopting TypeScript might result in more robust software, while still being deployable where a regular JavaScript application would run.

It is open source, but you only get the clever Intellisense as you type if you use a supported IDE. Initially, this was only Microsoft's Visual Studio (also noted in blog post from Miguel de Icaza). These days, other IDEs offer TypeScript support too.

There's CoffeeScript, but that really serves a different purpose. IMHO, CoffeeScript provides readability for humans, but TypeScript also provides deep readability for tools through its optional static typing (see this recent blog post for a little more critique). There's also Dart but that's a full on replacement for JavaScript (though it can produce JavaScript code)

As an example, here's some TypeScript (you can play with this in the TypeScript Playground)

class Greeter {
    greeting: string;
    constructor (message: string) {
        this.greeting = message;
    }
    greet() {
        return "Hello, " + this.greeting;
    }
}

And here's the JavaScript it would produce

var Greeter = (function () {
    function Greeter(message) {
        this.greeting = message;
    }
    Greeter.prototype.greet = function () {
        return "Hello, " + this.greeting;
    };
    return Greeter;
})();

Notice how the TypeScript defines the type of member variables and class method parameters. This is removed when translating to JavaScript, but used by the IDE and compiler to spot errors, like passing a numeric type to the constructor.

It's also capable of inferring types which aren't explicitly declared, for example, it would determine the greet() method returns a string.

Many browsers and IDEs offer direct debugging support through sourcemaps. See this Stack Overflow question for more details: Debugging TypeScript code with Visual Studio

@nawfal yes i dont like Atom multiple processes the final 1.0 version isnt released yet and solving memory issue is on their roadmap for 1.0 , lets see !

The problem with these tools is that you never get the full performance out of javascript. Yes, it provides good readability but the compiled code is sometimes very clunky. You rely on a third-party tool to write native javascript, I think this is not the way to go, it's like transforming a language to another language. Wanting to change a language that's not another language to behave like another language you like, that's stupid and silly. ...... (end of part 1)......

@Erwinus: Did you still program with assembler?

@Erwinus The point of TypeScript is to provide compile time type checking. If you don't see the value in that, that's perfectly fine. TypeScript has been refereed to as "your first unit test". There are many resources that discuss whether or not optional type checking has value, and are more detail than what we can do here. I'm not trying to convince you of anything, just correcting a misconception.

What is TypeScript and why would I use it in place of JavaScript? - St...

javascript typescript
Rectangle 27 22

Your reasoning for using mapping plug-in is reasonable and the one that I use. Why type more code than you have to?

In my experience with knockout (all of 4 months), I've found that the less I do manually and let the knockout routines do their thing, the better my apps seem to run. My suggestion is try the simplest approach first. If it doesn't meet your needs, look at how the simple approach is doing it's "thing" and determine what has to change to meet your needs.

javascript - Am I overusing the Knockout mapping plugin by always usin...

javascript mvvm knockout.js knockout-mapping-plugin
Rectangle 27 22

Your reasoning for using mapping plug-in is reasonable and the one that I use. Why type more code than you have to?

In my experience with knockout (all of 4 months), I've found that the less I do manually and let the knockout routines do their thing, the better my apps seem to run. My suggestion is try the simplest approach first. If it doesn't meet your needs, look at how the simple approach is doing it's "thing" and determine what has to change to meet your needs.

javascript - Am I overusing the Knockout mapping plugin by always usin...

javascript mvvm knockout.js knockout-mapping-plugin
Rectangle 27 26

A more modern option for interpreting HTML (text and otherwise) from JavaScript is the HTML support in the DOMParser API (see here in MDN). This allows you to use the browser's native HTML parser to convert a string to an HTML document. It has been supported in new versions of all major browsers since late 2014.

If we just want to decode some text content, we can put it as the sole content in a document body, parse the document, and pull out the its .body.textContent.

var encodedStr = 'hello & world';

var parser = new DOMParser;
var dom = parser.parseFromString(
    '<!doctype html><body>' + encodedStr,
    'text/html');
var decodedString = dom.body.textContent;

console.log(decodedString);

We can see in the draft specification for DOMParser that JavaScript is not enabled for the parsed document, so we can perform this text conversion without security concerns.

parseFromString(str, type)
"text/html"

Parse str with an HTML parser, and return the newly created Document.

script elements get marked unexecutable and the contents of noscript get parsed as markup.

It's beyond the scope of this question, but please note that if you're taking the parsed DOM nodes themselves (not just their text content) and moving them to the live document DOM, it's possible that their scripting would be reenabled, and there could be security concerns. I haven't researched it, so please exercise caution.

html - Decode & back to & in JavaScript - Stack Overflow

javascript html text decode
Rectangle 27 22

Creating a Pseudo-Classical Inheritance Pattern in JavaScript

If you want something similar to classes in JavaScript then there are a lot of libraries out there which provide it to you. For example using augment you could restructure your code as follows:

var augment = require("augment");

var ABC = augment(Object, function () {
    this.constructor = function (key, value) {
        this.key = key;
        this.value = value;
    };

    this.what = function () {
        alert("what");
    };
});

var XYZ = augment(ABC, function (base) {
    this.constructor = function (key, value) {
        base.constructor.call(this, key, value);
    };

    this.that = function () {
        alert("that");
    };
});

I don't know about you but to me this looks a lot like classical inheritance in C++ or Java. If this solves your problem, great! If is doesn't then continue reading.

In a lot of ways prototypes are similar to classes. In fact prototypes and classes are so similar that we can use prototypes to model classes. First let's take a look at how prototypal inheritance really works:

The above picture was taken from the following answer. I suggest you read it carefully. The diagram shows us:

  • Every constructor has a property called prototype which points to the prototype object of the constructor function.
  • Every prototype has a property called constructor which points to the constructor function of the prototype object.
  • We create an instance from a constructor function. However the instance actually inherits from the prototype, not the constructor.

This is very useful information. Traditionally we've always created a constructor function first and then we've set its prototype properties. However this information shows us that we may create a prototype object first and then define the constructor property on it instead.

function ABC(key, value) {
    this.key = key;
    this.value = value;
}

ABC.prototype.what = function() {
    alert("what");
};

However using our newfound knowledge we may write the same thing as:

var ABC = CLASS({
    constructor: function (key, value) {
        this.key = key;
        this.value = value;
    },
    what: function () {
        alert("what");
    }
});

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

As you can see encapsulation is easy to achieve in JavaScript. All you need to do is think sideways. Inheritance however is a different issue. You need to do a little more work to achieve inheritance.

augment
function augment(body) {
    var base = typeof this === "function" ? this.prototype : this;
    var prototype = Object.create(base);
    body.apply(prototype, arrayFrom(arguments, 1).concat(base));
    if (!ownPropertyOf(prototype, "constructor")) return prototype;
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

Notice that the last three lines are the same as that of CLASS from the previous section:

function CLASS(prototype) {
    var constructor = prototype.constructor;
    constructor.prototype = prototype;
    return constructor;
}

This tells us that once we have a prototype object all we need to do is get its constructor property and return it.

The first three lines of augment are used to:

  • Get the base class prototype.
  • Create a derived class prototype using Object.create.
  • Populate the derived class prototype with the specified properties.

That's all that there is to inheritance in JavaScript. If you want to create your own classical inheritance pattern then you should be thinking along the same lines.

Every JavaScript programmer worth their salt will tell you that prototypal inheritance is better than classical inheritance. Nevertheless newbies who come from a language with classical inheritance always try to implement classical inheritance on top of prototypal inheritance, and they usually fail.

They fail not because it's not possible to implement classical inheritance on top of prototypal inheritance but because to implement classical inheritance on top of prototypal inheritance you first need to understand how true prototypal inheritance works.

However once you understand true prototypal inheritance you'll never want to go back to classical inheritance. I too tried to implement classical inheritance on top of prototypal inheritance as a newbie. Now that I understand how true prototypal inheritance works however I write code like this:

function extend(self, body) {
    var base = typeof self === "function" ? self.prototype : self;
    var prototype = Object.create(base, {new: {value: create}});
    return body.call(prototype, base), prototype;

    function create() {
        var self = Object.create(prototype);
        return prototype.hasOwnProperty("constructor") &&
            prototype.constructor.apply(self, arguments), self;
    }
}

The above extend function is very similar to augment. However instead of returning the constructor function it returns the prototype object. This is actually a very neat trick which allows static properties to be inherited. You can create a class using extend as follows:

var Abc = extend(Object, function () {
    this.constructor = function (key, value) {
        this.value = 333 + Number(value);
        this.key = key;
    };

    this.what = function () {
        alert("what");
    };
});

Inheritance is just as simple:

Remember however that extend does not return the constructor function. It returns the prototype object. This means that you can't use the new keyword to create an instance of the class. Instead you need to use new as a method, as follows:

var x = Xyz.new("x", "123");
var y = Xyz.new("y", "456");
var it = Abc.new("it", "789");

This is actually a good thing. The new keyword is considered harmful and I strongly recommend you to stop using it. For example it's not possible to use apply with the new keyword. However it is possible to use apply with the new method as follows:

var it = Abc.new.apply(null, ["it", "789"]);

Since Abc and Xyz are not constructor functions we can't use instanceof to test whether an object is an instance of Abc or Xyz. However that's not a problem because JavaScript has a method called isPrototypeOf which tests whether an object is a prototype of another object:

alert(x.key + ": " + x.value + "; isAbc: " + Abc.isPrototypeOf(x));
alert(y.key + ": " + y.value + "; isAbc: " + Abc.isPrototypeOf(y));

alert(it.key + ": " + it.value + "; isAbc: " + Abc.isPrototypeOf(it));
alert(it.key + ": " + it.value + "; isXyz: " + Xyz.isPrototypeOf(it));
isPrototypeOf
instanceof
alert(Abc.isPrototypeOf(Xyz)); // true

Besides this minor change everything else works just like it did before:

x.what();
y.that();

it.what();
it.that(); // will throw; it is not Xyz and does not have that method

What else does true prototypal inheritance offer? One of the biggest advantages of true prototypal inheritance is that there's no distinction between normal properties and static properties allowing you to write code like this:

var Xyz = extend(Abc, function (base) {
    this.empty = this.new();

    this.constructor = function (key, value) {
        base.constructor.call(this, key, value);
    };

    this.that = function () {
        alert("that");
    };
});

Notice that we can create instances of the class from within the class itself by calling this.new. If this.constructor is not yet defined then it returns a new uninitialized instance. Otherwise it returns a new initialized instance.

In addition because Xyz is the prototype object we can access Xyz.empty directly (i.e. empty is a static property of Xyz). This also means that static properties are automatically inherited and are no different from normal properties.

Finally, because the class is accessible from within the class definition as this, you can created nested classes which inherit from the class which they are nested within by using extend as follows:

var ClassA = extend(Object, function () {
    var ClassB = extend(this, function () {
        // class definition
    });

    // rest of the class definition

    alert(this.isPrototypeOf(ClassB)); // true
});

There's a known issue that the properties like instance.What in fact are not inherited from the prototype and each instance has its own property, which can be solved by adding an argument and passing the prototype to the initialize function such as function (instance, prototype, _super); but that approach doesn't work with a closure captures the arguments of the constructor. I'm still reading your answer, and sorry for giving you migraines ..

augment seems a good solution but I'm wondering how to declare an instance of type which is being declared, such as declaring Xyz.Empty=new Xyz(); inside while Xyz is not yet declared, using this.constructor to do that may reduce the readability ..

Another problem with augment that I cannot see a solution is to declare nesting classes which derive from the declaring class.

extend

@AaditMShah: Thanks for the update, but I cannot upvote twice :-). However, I don't really like your static properties, which are just prototype properties (and accessing them on the instances might trap some people into trying to assign them on the instances). I had more thought of something like in this answer of mine where there are two separate (cross-linked) prototype chains for the Class objects and the instances.

javascript - How to achieve pseudo-classical inheritance right on the ...

javascript inheritance types prototype
Rectangle 27 22

A more modern option for interpreting HTML (text and otherwise) from JavaScript is the HTML support in the DOMParser API (see here in MDN). This allows you to use the browser's native HTML parser to convert a string to an HTML document. It has been supported in new versions of all major browsers since late 2014.

If we just want to decode some text content, we can put it as the sole content in a document body, parse the document, and pull out the its .body.textContent.

var encodedStr = 'hello &amp; world';

var parser = new DOMParser;
var dom = parser.parseFromString(
    '<!doctype html><body>' + encodedStr,
    'text/html');
var decodedString = dom.body.textContent;

console.log(decodedString);

We can see in the draft specification for DOMParser that JavaScript is not enabled for the parsed document, so we can perform this text conversion without security concerns.

parseFromString(str, type)
"text/html"

Parse str with an HTML parser, and return the newly created Document.

script elements get marked unexecutable and the contents of noscript get parsed as markup.

It's beyond the scope of this question, but please note that if you're taking the parsed DOM nodes themselves (not just their text content) and moving them to the live document DOM, it's possible that their scripting would be reenabled, and there could be security concerns. I haven't researched it, so please exercise caution.

html - Decode & back to & in JavaScript - Stack Overflow

javascript html text decode
Rectangle 27 32

Using a button to login:

If you use a type="button" with an onclick handler to login using ajax, then the browser won't offer to save the password.

<form id="loginform">
 <input name="username" type="text" />
 <input name="password" type="password" />
 <input name="doLogin"  type="button" value="Login" onclick="login(this.form);" />
</form>

Since this form does not have a submit button and has no action field, the browser will not offer to save the password.

However, if you change the button to type="submit" and handle the submit, then the browser will offer to save the password.

<form id="loginform" action="login.php" onSubmit="return login(this);">
 <input name="username" type="text" />
 <input name="password" type="password" />
 <input name="doLogin"  type="submit" value="Login" />
</form>

Using this method, the browser should offer to save the password.

Here's the Javascript used in both methods:

function login(f){
    var username = f.username.value;
    var password = f.password.value;

    /* Make your validation and ajax magic here. */

    return false; //or the form will post your data to login.php
}

Works for me in IE as well. I could kiss you now!

@Bigood It works in firefox

ajax - How can I get browser to prompt to save password? - Stack Overf...

ajax firefox browser login
Rectangle 27 32

Using a button to login:

If you use a type="button" with an onclick handler to login using ajax, then the browser won't offer to save the password.

<form id="loginform">
 <input name="username" type="text" />
 <input name="password" type="password" />
 <input name="doLogin"  type="button" value="Login" onclick="login(this.form);" />
</form>

Since this form does not have a submit button and has no action field, the browser will not offer to save the password.

However, if you change the button to type="submit" and handle the submit, then the browser will offer to save the password.

<form id="loginform" action="login.php" onSubmit="return login(this);">
 <input name="username" type="text" />
 <input name="password" type="password" />
 <input name="doLogin"  type="submit" value="Login" />
</form>

Using this method, the browser should offer to save the password.

Here's the Javascript used in both methods:

function login(f){
    var username = f.username.value;
    var password = f.password.value;

    /* Make your validation and ajax magic here. */

    return false; //or the form will post your data to login.php
}

Works for me in IE as well. I could kiss you now!

@Bigood It works in firefox

ajax - How can I get browser to prompt to save password? - Stack Overf...

ajax firefox browser login
Rectangle 27 552

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 552

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 548

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 548

JSON in JavaScript

JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging.

An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight

You can find a lot more info on the official JSON web site.

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

Here is an example of JSON data:

{
     "firstName": "John",
     "lastName": "Smith",
     "address": {
         "streetAddress": "21 2nd Street",
         "city": "New York",
         "state": "NY",
         "postalCode": 10021
     },
     "phoneNumbers": [
         "212 555-1234",
         "646 555-4567"
     ]
 }

When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).

Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.

Example on how to use the JSON Parser (with the json from the above code snippet):

//The callback function that will be executed once data is received from the server
var callback = function (result) {
    var johnny = JSON.parse(result);
    //Now, the variable 'johnny' is an object that contains all of the properties 
    //from the above code snippet (the json example)
    alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};

The JSON Parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:

var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}

The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)

Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.

Regardless of the way information is serialized, you're going to have a parser, right? Therefore, who cares what format you use to transmit data if its implementation details are going to be abstracted away.

Well actually, if you're transmitting data to and fro the client and server, I think it's pretty important to be careful of your response sizes.

For the pedantic, there are a couple of characters that JSON handles differently than JavaScript, preventing it from being a strict subset: timelessrepo.com/json-isnt-a-javascript-subset

Liked the graph very much!

So would you replace XML with JSON? Is that what your saying? If so...Great, xml is a nightmare.

What is JSON and why would I use it? - Stack Overflow

json
Rectangle 27 201

  • Newcomers will already be familiar with double quotes from their language. In English, we must use double quotes " to identify a passage of quoted text. If we were to use a single quote ', the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the ' indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.
"I'm going to the mall"
'I\'m going to the mall'

Double quotes mean a string in many other languages

Nonetheless, as others have stated, it is most important to remain consistent.

Your first point about English language is not always true and can change depending on the locality/house convention. Printed materials typically use single-quotes for speech and use other formatting for large blocks of quoted text. Your 'colloquial' meaning is not a useful definition of quotes for emphasis. Plus English users are in general very poor with quotation marks and apostrophes.

@JohnFerguson, for that reason alone, it may be desirable to use double-quotes so as to make that differentiation (between apostrophes and quoted passages).

I've been favouring single quotes before and this might just have convinced me to use double quotes for my next project... Thanks

I'm all about pragmatism. Due to the fact that 1 in 100 strings that I type or uses has double quotes, and many, many more have apostrophes, I use doubles. At the end of the day, though, you should use the quote type that's 1) already in use in the project if you're a new developer to the project, or 2) use the one that you think makes more sense.

string - When to use double or single quotes in JavaScript? - Stack Ov...

javascript string conventions
Rectangle 27 199

  • Newcomers will already be familiar with double quotes from their language. In English, we must use double quotes " to identify a passage of quoted text. If we were to use a single quote ', the reader may misinterpret it as a contraction. The other meaning of a passage of text surrounded by the ' indicates the 'colloquial' meaning. It makes sense to stay consistent with pre-existing languages, and this may likely ease the learning and interpretation of code.
"I'm going to the mall"
'I\'m going to the mall'

Double quotes mean a string in many other languages

Nonetheless, as others have stated, it is most important to remain consistent.

Your first point about English language is not always true and can change depending on the locality/house convention. Printed materials typically use single-quotes for speech and use other formatting for large blocks of quoted text. Your 'colloquial' meaning is not a useful definition of quotes for emphasis. Plus English users are in general very poor with quotation marks and apostrophes.

@JohnFerguson, for that reason alone, it may be desirable to use double-quotes so as to make that differentiation (between apostrophes and quoted passages).

I've been favouring single quotes before and this might just have convinced me to use double quotes for my next project... Thanks

I'm all about pragmatism. Due to the fact that 1 in 100 strings that I type or uses has double quotes, and many, many more have apostrophes, I use doubles. At the end of the day, though, you should use the quote type that's 1) already in use in the project if you're a new developer to the project, or 2) use the one that you think makes more sense.

string - When to use double or single quotes in JavaScript? - Stack Ov...

javascript string conventions
Rectangle 27 73

If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.

<style type="text/css">
    .jsAction {
        cursor: pointer;
        color: #00f;
        text-decoration: underline;
    }
</style>

<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>

This approach restricts the 'link' to a mouse only operation. An anchor can be visited via the keyboard and its 'onclick' event is fired when the enter key is pressed.

Hardcoding colors in your CSS would prevent the browser from using custom colors the user may define, which can be a problem with accessibility.

<span>s are not meant to do anything. <A>nchors and <buttons> are used for that!

Using buttons is a better choice here while using a span is not.

I think a span is better than an anchor tag. Anchor tag exists to direct you to its mandatory href attribute. If you're not going to use the href, don't use an anchor. It doesn't restrict the link to mouse only because it isn't a link. It doesn't have a href. It's more like a button but it doesn't post. The span not being meant to do anything is completely invalid. Consider a dropdown menu that activates when you hover. It's probably a combination of spans and divs, performing the function of a button that expands an area on the screen.

html - Which "href" value should I use for JavaScript links, "#" or "j...

javascript html performance optimization href
Rectangle 27 73

If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.

<style type="text/css">
    .jsAction {
        cursor: pointer;
        color: #00f;
        text-decoration: underline;
    }
</style>

<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>

This approach restricts the 'link' to a mouse only operation. An anchor can be visited via the keyboard and its 'onclick' event is fired when the enter key is pressed.

Hardcoding colors in your CSS would prevent the browser from using custom colors the user may define, which can be a problem with accessibility.

<span>s are not meant to do anything. <A>nchors and <buttons> are used for that!

Using buttons is a better choice here while using a span is not.

I think a span is better than an anchor tag. Anchor tag exists to direct you to its mandatory href attribute. If you're not going to use the href, don't use an anchor. It doesn't restrict the link to mouse only because it isn't a link. It doesn't have a href. It's more like a button but it doesn't post. The span not being meant to do anything is completely invalid. Consider a dropdown menu that activates when you hover. It's probably a combination of spans and divs, performing the function of a button that expands an area on the screen.

html - Which "href" value should I use for JavaScript links, "#" or "j...

javascript html performance optimization href
Rectangle 27 73

If your "link" has the sole purpose of running some JavaScript code it doesn't qualify as a link; rather a piece of text with a JavaScript function coupled to it. I would recommend to use a <span> tag with an onclick handler attached to it and some basic CSS to immitate a link. Links are made for navigation, and if your JavaScript code isn't for navigation it should not be an <a> tag.

<style type="text/css">
    .jsAction {
        cursor: pointer;
        color: #00f;
        text-decoration: underline;
    }
</style>

<p>I want to call a JavaScript function <span class="jsAction" onclick="callFunction();">here</span>.</p>

This approach restricts the 'link' to a mouse only operation. An anchor can be visited via the keyboard and its 'onclick' event is fired when the enter key is pressed.

Hardcoding colors in your CSS would prevent the browser from using custom colors the user may define, which can be a problem with accessibility.

<span>s are not meant to do anything. <A>nchors and <buttons> are used for that!

Using buttons is a better choice here while using a span is not.

I think a span is better than an anchor tag. Anchor tag exists to direct you to its mandatory href attribute. If you're not going to use the href, don't use an anchor. It doesn't restrict the link to mouse only because it isn't a link. It doesn't have a href. It's more like a button but it doesn't post. The span not being meant to do anything is completely invalid. Consider a dropdown menu that activates when you hover. It's probably a combination of spans and divs, performing the function of a button that expands an area on the screen.

html - Which "href" value should I use for JavaScript links, "#" or "j...

javascript html performance optimization href
Rectangle 27 4

Solution with JavaScript

I know this is not a CSS-only solution a I use JavaScript, but it could help as a temporary solution while we look for a CSS thing.

The HTML would be the same as you posted:

<div id="hungry">
    <div class="col-xs-offset-6 col-xl-offset-6 col-xs-6 col-xl-6">
        <p>Hungry doesn't always happen in the kitchen</p>
    </div>
</div>

The CSS for the div with id "hungry" would look like this:

And finally, with JavaScript (I used jQuery to make it easier), you resize the height of #hungry depending on the screen width:

// you know the size for your image
imageWidth = 1919;
imageHeight = 761;
imageProportion = imageHeight/imageWidth;

function resizeJumbo() {
    $("#hungry").css({ height: $(window).width() * imageProportion });
}

$(window).on("resize", function() {
    resizeJumbo();
});

$(document).ready(function() {
    resizeJumbo();
});

Just update the CSS for the hungry div a little:

#hungry {
    background:url('http://i.stack.imgur.com/7xasp.jpg') no-repeat center center ;
    background-size:cover;
    width:100%;
    padding-top:20%;
    padding-bottom:20%;
}
padding-top:20%
padding-bottom:20%

Those values have to do with the size of the picture, and the proportion between them. In your case: width = 1919 and height = 761, so the proportion between width and height is (761 / 1919) * 100 = 39.65%. Just add half that value on top, and half that value at the bottom, then the text will remain always in the middle, and the picture will always be proportional.

I know it's a bit "hacky" and plays with knowing some data, but it seems to be working fairly well.

And now, off to look for a CSS-only solution :P

cool... I'd love a CSS only solution. I think I tried this one and failed to succeed - but maybe it will direct you in the right direction stackoverflow.com/a/22211990/429249

@Boaz I just updated the solution with a CSS-only option. It's a bit "cheecky", but it seems to work fine

awesome - and if you can explain why it solves the problem (so I'll learn something) - I'll be grateful. Thanks!

I'll put it on the response as an edit, because it plays a bit with knowing the size of the picture

css - html text on responsive background image - Stack Overflow

html css twitter-bootstrap
Rectangle 27 4

Solution with JavaScript

I know this is not a CSS-only solution a I use JavaScript, but it could help as a temporary solution while we look for a CSS thing.

The HTML would be the same as you posted:

<div id="hungry">
    <div class="col-xs-offset-6 col-xl-offset-6 col-xs-6 col-xl-6">
        <p>Hungry doesn't always happen in the kitchen</p>
    </div>
</div>

The CSS for the div with id "hungry" would look like this:

And finally, with JavaScript (I used jQuery to make it easier), you resize the height of #hungry depending on the screen width:

// you know the size for your image
imageWidth = 1919;
imageHeight = 761;
imageProportion = imageHeight/imageWidth;

function resizeJumbo() {
    $("#hungry").css({ height: $(window).width() * imageProportion });
}

$(window).on("resize", function() {
    resizeJumbo();
});

$(document).ready(function() {
    resizeJumbo();
});

Just update the CSS for the hungry div a little:

#hungry {
    background:url('http://i.stack.imgur.com/7xasp.jpg') no-repeat center center ;
    background-size:cover;
    width:100%;
    padding-top:20%;
    padding-bottom:20%;
}
padding-top:20%
padding-bottom:20%

Those values have to do with the size of the picture, and the proportion between them. In your case: width = 1919 and height = 761, so the proportion between width and height is (761 / 1919) * 100 = 39.65%. Just add half that value on top, and half that value at the bottom, then the text will remain always in the middle, and the picture will always be proportional.

I know it's a bit "hacky" and plays with knowing some data, but it seems to be working fairly well.

And now, off to look for a CSS-only solution :P

cool... I'd love a CSS only solution. I think I tried this one and failed to succeed - but maybe it will direct you in the right direction stackoverflow.com/a/22211990/429249

@Boaz I just updated the solution with a CSS-only option. It's a bit "cheecky", but it seems to work fine

awesome - and if you can explain why it solves the problem (so I'll learn something) - I'll be grateful. Thanks!

I'll put it on the response as an edit, because it plays a bit with knowing the size of the picture

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

css - html text on responsive background image - Stack Overflow

html css twitter-bootstrap