Categories
development Uncategorized

How to Create a Simple “onclick” Event with Javascript & Manipulate the DOM

what_well_cover

In this micro tutorial, we will cover how to take a users data and change the DOM after clicking a button using Javascript.

Creating HTML template

In this part, we will create a simple HTML template without Javascript. It will include “<input>” field, and “<span>” tag with text that we will write later.

Basic HTML

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name"></input>
<button>Submit</button>
<span id="message"></span>
</body>
</html>

HTML Output

For the input and span tag, we set id values to be able to manipulate them in the future.

Creating a Javascript Function & Setting “on-click” Event

For this part we need to create a “<script>” tag with a function inside the HTML file. It should be placed under the HTML template.

HTML with Script Tag

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input id="name"></input>
<button onclick="sayHello()">Submit</button>
<span id="message"></span>
</body>


 function sayHello() {
		//code of the function
 }

</html>

You can see the “onclick” event handler on the button that will run the function “sayHello” after the button has been clicked.

Inserting the Value from Input Field into the Tag

After the we enters any kind of text inside the field, we can access it by using JavaScript. In our example we will enter our name and change it to “Hello, username” and show it inside the “<span>” tag.

Getting the Value

function sayHello() {
		var username = document.getElementById("name").value
 }

This code allows us to get the value of the element with an ID = “name”, that is actually our <input> field.

After we get the value, that we entered, we will append “Hello, ” in front of it.

Function Code

 function sayHello() {
		var username = document.getElementById("name").value
		var greeting = "Hello, " + username;
 }

Final Step

The last step is to place the text we receive inside the “<span>” tag and display it.. Again, we will take the element where ID = “message” and place the “greeting” value inside of it.

  function sayHello() {
		var username = document.getElementById("name").value
		var greeting = "Hello, " + username;
		document.getElementById("message").innerHTML = greeting;
 }

Our Result

Now, after we enter our name inside the <input> field, press the submit button we can see the greeting message.

Full Code

<html>
<head>
</head>
<body>
<input id="name"></input>
<button onclick="sayHello()">Submit</button>
<span id="message"></span>
</body>

 function sayHello() {
		var username = document.getElementById("name").value
		var greeting = "Hello, " + username;
		document.getElementById("message").innerHTML = greeting;
 }

</html>

If you like this post, show your appreciation with a few claps. 🙂

I hope you find these micro tutorials useful, if you have a suggestion that you would like me to cover then please send it using the form below.

Categories
development

Understanding JavaScript Function Scope

I’d Like You to Know


These MicroTuts are meant to inspire further learning around the topics they cover.

My hope is that they can be used as reference to more easily gain additional knowledge. 

If you would like some MicroTut’s created for a subject you are interested in then please use the form at the bottom of this page.


Did you know?

Did you know you can assign a value to a variable without declaring it?

but_dont_do_it

Saving that extra bit of typing and and just assigning some value to a variable without properly declaring it can cause you a hard time by creating side effects like unexpected values.

checkout_quick_example_below
// myUndeclaredVariable will be available here, this may not be what you want

function doSomething(){
  // This will get moved to the top of the file outside the function but will not give any error.
  myUndeclaredVariable = "Some value"
}

This style of coding is allowed in JavaScript but isn’t really the way you want to do things, if you used a variable with the same name in another function then you may begin to get unexpected results.

JavaScript Function Scope

JavaScript like most languages offers function scope, meaning you can declare a variable in one function and the declare another with the same name in another function. To correctly declare your variables in JavaScript, see the example below.

// A global scope variable.
var globalVariable = "Global Data"

function doSomething(){
  // A locally scoped variable.
  var localVariable = "Local Data"
}

The JavaScript Engine

Which ever way you declare and assign your variables the JavaScript engine will break it apart and move the declaration part to the top of the scope, so if you declare a variable with a definition on one line in a function the JavaScript engine will move the declaration to the top of the function the assignment will be left in place.

checkout_quick_example_below
function doSomething(){
  // myPropery declaration will be hoisted to hear.

  console.log(myProperty) // output will be undefined.

  var myProperty = "Some thing"
}

Functions Are Hoisted Too

The way you declare your functions can matter too, you can use function declaration or function expressions when creating a function.

function doSomething() {} //Function declaration.

var myFunction = function() {} // Function expression.

The function declaration begins with the “function” keyword, the whole of this function will be hoisted, meaning we can call the function before we have declared it, so if we do something like below…

doSomething();

function doSomething() {
  console.log("Here is the output.");
} //Function declaration.

var myFunction = function() {}; // Function expression.

The code above will work fine because the JavaScript engine will interpret it like this.

function doSomething() {
  console.log("Here is the output.");
} //Function declaration.

var myFunction

doSomething()

myFunction = function() {}; // Function expression.

Notice the function declaration was moved to the top and the variable declaration for the function expression was also moved.

If you like this post, show your appreciation with a few claps. 🙂

I hope you find these micro tutorials useful, if you have a suggestion that you would like me to cover then please send it using the form below.

Categories
development

How to Make Your JavaScript Code Run Faster

Did you know?

Did you know that you can make your JavaScript code run faster with one change?

If you aren’t using “use-strict” in your JavaScript files, you probably should be. Running some code side by side with “use-strict” can perform better than not using it.

“use-strict” helps optimise your code so JavaScript engines can perform optimisations better, it also eliminates some silent errors by making them throw an error when they are introduced, it also future proofs your JavaScript by helping it be more compatible with later versions of ECMAScript, it also disables some poorly thought out features.

I’d Like You to Know


These MicroTuts are meant to inspire further learning around the topics they cover.

My hope is that they can be used as reference to more easily gain additional knowledge. 

If you would like some MicroTut’s created for a subject you are interested in then please use the form at the bottom of this page.


Using “use-strict” Mode

If you aren’t using strict mode, it’s probably not a good idea to just start adding it to your files, if your files are being bundled it can cause issues.

“use-strict” can be added to the top of a JavaScript file which will make all functions that follow be in strict mode. Strict mode can also be enabled on a function by function basis.

// Whole script declaration.
"use strict";

const prop = "File level strict mode";
function strictFunction() {
  // Only this function will be in strict mode.
  "use-strict";

  return "Function level strict mode";
}
function strictFunction() {
  // Only this function will be in strict mode.
  "use-strict";

  function strictFunction() {
    return "some other function";
  }

  return "Function level strict mode" + strictFunction();
}

If you like this post, show your appreciation with a few claps. 🙂

I hope you find these micro tutorials useful, if you have a suggestion that you would like me to cover then please send it using the form below.

Categories
development

Understanding JavaScript “Const” Keyword

Did you know?

Did you know that the “const” keyword in JavaScript does not really mean constant?

In JavaScript the “const” keyword is really a one-time assignment, in the examples below we can see that “const” probably works how we would expect.

// Declaring a const variable, 
const myImmutableData = "Some text here" 
  
console.log(myImmutableData) 
  
// Assigning a new value. 
myImmutableData = "Some other text" 
  
console.log(myImmutableData) 

I’d Like You to Know


These MicroTuts are meant to inspire further learning around the topics they cover.

My hope is that they can be used as reference to more easily gain additional knowledge. 

If you would like some MicroTut’s created for a subject you are interested in then please use the form at the bottom of this page.


Try to run the above code and you will get an error like below.

assignmrent_constant_variable

This shows we cannot change the reference to the property we declared.

Trying to re declare the property also produces the error we might expect.

variable_already_declared

So, when is “const” not constant?

Well, would expect to be able to add new values to an array that was declared using the “const” keyword?

// Declaring a const variable, 
const myImmutableData = [1,2,3] 
myImmutableData.push(4) 
myImmutableData.shift() 
  
console.log(myImmutableData) 

Do you expect the above code to error?

Well, it does not, so we added and removed data from our so-called constant declaration. (A bit concerning.)

And what about the example below, do we expect an error from that?

// Declaring a const variable, 
const myImmutableData = { 
    someProperty: "www.bbc.co.uk" 
} 
  
myImmutableData.someProperty = "www.google.com" 
  
console.log(myImmutableData) 

Well…. Did you get it right? No error here either.

So, when you next declare something using the “const” keyword expecting no one else to be able to change it, think twice.

To get a truly immutable property you can use “Object.freeze”, we will discuss that in another micro tutorial.

If you like this post, show your appreciation with a few claps. 🙂

I hope you find these micro tutorials useful, if you have a suggestion that you would like me to cover then please send it using the form below.

Categories
development

How to Create Immutable Objects in JavaScript Using Object.Freeze?

I’d Like You to Know


These MicroTuts are meant to inspire further learning around the topics they cover.

My hope is that they can be used as reference to more easily gain additional knowledge. 

If you would like some MicroTut’s created for a subject you are interested in then please use the form at the bottom of this page.


Did you know?

Did you know you can freeze an object so no one can change it or add to it?

In JavaScript the “const” keyword does not really mean constant or unchangeable, instead there is a method called “freeze” on the “Object” constructor “Object.freeze” that lets you stop any changes being made to your declared variable.

Freeze Punk

So if you really don’t want anyone to be able to change your data without having to return a new instance of it then it’s time to start using “Object.freeze”

object.freeze example
'use strict'

//Notice the 'use strict' above, if this is not used you will not see an error.

//Declare our immutable object using the "const" keyword.
const myImmutableObject = {
    property1: 42
  };

  const myReallyImmutableObject = Object.freeze(myImmutableObject);

  myReallyImmutableObject.property1 = 33;
  // Throws an error in strict mode

  console.log(myReallyImmutableObject.property1);
  // expected output: 42

It Works Without It

“Object.freeze” works without specifying “use-strict” but it will not throw an error.

If you like this post, show your appreciation with a few claps. 🙂

I hope you find these micro tutorials useful, if you have a suggestion that you would like me to cover then please send it using the form below.