Categories
JavaScript Basics

Highlights of JavaScript — Objects and Constructors

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Objects

We need objects to store values other than primitive values like numbers, strings, booleans, etc.

It servers as a container for all the items we want to store.

For example, we can define an object by writing:

const plan = {
  name: "Basic",
  price: 3,
  space: 100,
  transfer: 1000,
  pages: 10
};

We created the plan object with various properties.

name , price , space , transfer , and pages are property names.

The expressions after the colon are their values.

Properties are separated by a comma.

To access a property, we can write:

plan.name

plan.name ‘s value should be 'Basic' .

We can assign properties with different values.

For example, we can write:

plan.name = 'Deluxe';

Then name property’s new value is 'Deluxe' .

We can assign values with any data type with the assignment operator.

To check if a property is in an object, we can use the in operator.

For example, if we have:

'name' in plan

then that should return true since name is a property of plan .

But if we have:

'foo' in plan

then that returns false since foo isn’t a property of plan .

We need the property name in quotes since the left operand is a string.

Object Methods

Objects can have methods.

For example, we can write:

const plan = {
  name: "Basic",
  price: 3,
  space: 100,
  transfer: 1000,
  pages: 10,
  calcAnnualPrice() {
    return this.price * 12;
  }
};

to add the calcAnnualPrice method into the plan object.

this is the object itself, so this.price * 12 returns the value of the price property multiplied by 12.

Constructors

We can create objects with the same structure with constructors.

They’re the templates for objects.

To create a constructor, we can write:

function Plan(name, price, space, pages) {
  this.name = name;
  this.price = price;
  this.space = space;
  this.pages = pages;
}

We created the Plan constructor that takes the name , price , space , and pages parameters.

Then we assign them to properties of this with the same name.

When we invoke the constructor, this will be returned with all the properties we assigned.

To invoke it, we can write:

const plan = new Plan('basic', 3, 100, 10)

We use the new keyword to call the constructor and create the object.

The value of plan is:

{
  name: "basic"
  pages: 10
  price: 3
  space: 100
}

A better way to write the constructor is to use the class syntax.

For example, we can write:

class Plan {
  constructor(name, price, space, pages) {
    this.name = name;
    this.price = price;
    this.space = space;
    this.pages = pages;
  }
}

The constructor method is the same as the constructor function we have before.

It just looks different. This is the preferred way to create constructors since it’s consistent with other popular object-oriented languages.

Conclusion

We can create objects to store more than one piece of data in a container.

To create objects with the same structure, we can create constructors.

Categories
JavaScript Basics

Highlights of JavaScript — Selecting Elements and the DOM

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Target All Elements by Tag Name with querySelectorAll

The document.querySelectorAll method lets us get all the elements with the given selector.

So to get all the elements with the given tag name, we can write the following HTML:

<p>foo.</p>
<p>bar.</p>
<p>baz.</p>

Then we can get all of them and style them by writing:

const pars = document.querySelectorAll('p')
for (const p of pars) {
  p.style.fontFamily = "Verdana, Geneva, sans-serif";
}

We get all the p elements with document.querySelectorAll .

Then we loop through each item with the for-of loop and set the style.fontFamily property to set the font family.

Target Some Elements by Tag Name

We can target some elements by tag name with the document.querySelectorAll method since it takes any selector string as an argument.

For example, if we have the following HTML table:

<table>
  <tr>
    <td>foo</td>
    <td>bar</td>
    <td>baz</td>
  </tr>
</table>

and we want to get all the td elements in the table, we can write:

const tds = document.querySelectorAll('table td')
for (const t of tds) {
  t.style.backgroundColor = "pink";
}

We get the td elements within the table element with the table td selector.

Then we loop through the td elements and set the backgroundColor to 'pink' .

The DOM

The DOM stands for Document Object Model. It’s the way that browsers represent the HTML elements with JavaScript.

HTML elements are organized in a tree structure in the DOM.

Each level is indicated by the indentation.

For example, if we have:

<html>

  <head>
    <title>
      Simple document
    </title>
  </head>

  <body>
    <p>
      hello world
    </p>
  </body>

</html>

Then the html element is the root of the tree.

The head and body are at the 2nd level.

The title and p elements are at the 3rd level.

The topmost element is the document object.

Therefore html element is the parent of the head and body elements.

The title element is the child of the head element.

And the p element is the child of the body element.

We can find child elements with the DOM methods that we used before like querySelector , querySelectorAll , getElementById and getElementByTagName .

For example, if we have the following HTML:

<html>

<head>
    <title>
      Simple document
    </title>
  </head>

  <body>
    <div id="weather">
      <p>Today is sunny.</p>
      <p>Yesterday is rainy.</p>
    </div>
    <div id="density">
      <p>City is crowded.</p>
      <p>Desert is sparse.</p>
    </div>
  </body>
</html>

Then if we want to get the ‘Today is sunny’ text, we can write:

const sunny = document.querySelector('#weather p');
console.log(sunny.innerHTML)

We use the #weather p selector with the querySelector method to get the first p element from the div with the ID weather .

Then we get its content with the innerHTML property.

Conclusion

We can get the elements with the document methods.

HTML elements are modeled in the browser with the DOM.

Categories
JavaScript Basics

Highlights of JavaScript — Class Names, Getting Multiple Elements, and Styling

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Adding Class Names

We can add a class name to an HTML element with the JavaScript class names API.

For example, we can write the following HTML:

<img src="https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo" id="image" onClick="expand();">

Then we can write the following CSS:

.big {
  width: 500px;
}

Then we can add the expand function by writing:

const expand = () => {
  document.getElementById("image").classList.add('big');
}

The big class has the width set to 500px.

In the expand function, we call the class:ist.add method to add the 'big' class to the element with the ID image .

And we set the onClick attribute with expand() to call the expand function when we click the image.

The image will then be expanded when we click on the image.

Swapping Images

We can swap an image for another when we hover over the image.

For example, we can write the following HTML:

<img src="https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo" id="image" onMouseover="swap(1);" onMouseout="swap(0)">

And the following JavaScript code:

const swap = (index) => {
  const images = [
    'https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo',
    'https://i.picsum.photos/id/25/200/300.jpg?hmac=ScdLbPfGd_kI3MUHvJUb12Fsg1meDQEaHY_mM613BVM'
  ]
  const image = document.querySelector('#image');
  image.src = images[index];
}

When we hover over the image, the swap(1) expression is run.

It’s set as the value of the onMouseover attribute, so it’ll run when we hover over the image element.

If we move our mouse out of the image, then swap(0) is run to show the original image.

This is because swap(0) is set as the value of the onMouseout attribute.

Setting Styles

We can set styles with the className or style property.

For example, we can write the following HTML:

<p>
  hello world
</p>

And write the following CSS:

.big {
  font-size: 2em
}

Then write the following to make the text big with JavaScript:

document.querySelector("p").classList.add("big");

We get the p element with the document.querySelector method.

Then we add the big class to the p element with the classList.add method.

Alternatively, we can set the style property to the value we want:

document.querySelector("p").style.fontSize = '2em'

The style.fontSize property is the same as the font-size CSS property.

However, it’s better to use CSS and class names since it’s faster than setting styles with JavaScript.

Also, CSS code is more reusable.

Other style properties we can set include:

document.querySelector("p").style.cssFloat = "left";

to set the CSSfloat property to left .

We can set the visibility CSS property by writing:

document.querySelector("p").style.visibility = "hidden";

And the margin can be set by writing”:

document.querySelector("p").style.margin = "0 10px 0 10px;";

Target All Elements by Tag Name

We can get all elements by tag name.

This is more convenient than getting a single element with its ID or using querySelector to get the first element with the given selector.

For example, we can write the following HTML:

<p>foo.</p>
<p>bar.</p>
<p>baz.</p>

Then we can get all the p elements and loop through them by writing:

const pars = document.getElementsByTagName('p')
for (const p of pars) {
  p.style.fontFamily = "Verdana, Geneva, sans-serif";
}

We get the p elements, then loop through them with the for-of loop.

In the loop body, we set the fontFamily style to change the font of the text.

Conclusion

We can add class names with the classList.add method.

Also, we can get elements and loop through them and change their styles.

Categories
JavaScript Basics

Highlights of JavaScript — Field Values, Images, and Text

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Setting Field Values

We can set input field values by using JavaScript.

For example, we can write the following HTML:

<form>
  fruit:<br>
  <input type="text" id="fruit" onBlur="fillColor();"><br>
  color:<br>
  <input type="text" id="color">
</form>

Then we can write the following JavaScript code:

const fillColor = () => {
  let color;
  const {
    value
  } = document.getElementById("fruit");
  switch (value) {
    case "apple":
      color = "red";
      break;
    case "orange":
      color = "orange";
      break;
    case "grape":
      color = "purple";
  }
  document.getElementById("color").value = color;
}

We added the onBlur attribute to the first input box.

So when we move the cursor away from the first input, the fillColor function is called.

Them we get the value if the input with ID fruit ‘s value with the value property.

Then we set the color variable’s value with according to the value of value .

We then set the input with ID color ‘s value with the value of the color variable.

Reading and Setting Paragraph Text

We can read and set paragraph text.

For example, we can write the following HTML:

<p id="text">
  Lorem ipsum dolor sit amet.
  <a href="javascript:void(0);" onClick="expandText();">
    <em>Click for more.</em>
  </a>
</p>

Then we can add the expandText function as follows:

const expandText = () => {
  const expandedParagraph = `Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras id lorem eget erat vestibulum consectetur. Donec vehicula porta est ut vestibulum. Mauris et nisl a sem iaculis laoreet. Nunc eleifend facilisis massa ut luctus. Nullam sollicitudin non lorem non eleifend. Curabitur elementum felis quis enim malesuada varius.`;
  document.getElementById("text").innerHTML = expandedParagraph;
}

The a element has the onClick attribute that is set to the expandText() expression.

So when we click on the ‘Click for more’ text, we’ll see the expanded text displayed on the screen.

This is because we set the expandedParagraph variable’s value as the value of the innerHTML property of the element with ID text .

We can insert anything into an element by setting the innerHTML property.

For example, we can keep the existing HTML and change the JavaScript to:

const expandText = () => {
  const expandedParagraph = `
    <ol>
      <li>Slow</li>
      <li>Fast</li>
      <li>Just-right</li>
     </ol>
   `;
  document.getElementById("text").innerHTML = expandedParagraph;
}

We set the content of the element with ID text to an ordered list.

So that’s what we’ll see when we click on Click for more.

Manipulating Images and Text

We can manipulate images with JavaScript.

For example, we can write the following HTML:

<img src="https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo" id="image" onClick="makeInvisible();">

Then we can add the following CSS:

.hidden {
  visibility: hidden;
}

Then the makeInvisible function is:

const makeInvisible = () => {
  document.getElementById("image").className = "hidden";
}

The hidden class has the visibility property set to hidden .

Therefore, when we click on the image, the makeInvisible function is run.

Then the hidden class is added to the img element.

So the image will be hidden.

Conclusion

We can use JavaScript to set field values, manipulate images, and paragraph text.

Categories
JavaScript Basics

Highlights of JavaScript — Button, Mouse, and Input Events

To learn JavaScript, we must learn the basics.

In this article, we’ll look at the most basic parts of the JavaScript language.

Button Events

We can add event handling code to buttons so that it can do something when we click it.

For example, we can write:

<input type="button" value="Click Me" onClick="alert('Hello world!');">

We have a button that has the onClick attribute with JavaScript code to call alert .

Therefore, we’ll see an alert box displayed when we click it.

The value attribute has the button text.

We can do the same for other elements.

For example, we can write:

<a href="http://google.com"><img onClick="alert('Hello world!');" src="https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo"></a>

When we click on the image, we see the alert box displayed.

If we want to make the code cleaner, we can put the alert call into its own function.

We can write the following HTML:

<a href="http://google.com"><img onClick="greet()" src="https://i.picsum.photos/id/23/200/300.jpg?hmac=NFze_vylqSEkX21kuRKSe8pp6Em-4ETfOE-oyLVCvJo"></a>

And the following JavaScript:

const greet = () => {
  alert('Hello world!');
}

Mouse Events

We can listen to mouse events by using attributes and set their values to JavaScript code.

For example, we can write:

<h1 onMouseover="alert('hello world.');">hello world</h1>

to show an alert box when we hover over the h1 element.

We can also add the onMouseout event handler to do something when we hover over the element and then reverse it when we move the mouse away from it:

<h1 onMouseover="this.style.color='green'" onMouseout="this.style.color='black'">hello world</h1>

this in the code above is the h1 element.

We set the color style to 'green' when we hover over the h1 element.

Then when we move the mouse away, then we set the color back to black.

Input Events

Likewise, we can listen to events emitted by the input element.

For example, we can write:

<input type="text" size="30" onFocus="this.style.backgroundColor = 'yellow';" onBlur="this.style.backgroundColor = 'white';">

We added the onFocus and onBlur handlers to set the backgroundColor style to 'yellow' when we focus on the input element.

Then when we move the cursor away from the input, it goes back to a white background.

Reading Field Values

We can read the value entered into the input field when we submit the form.

We can write the following HTML:

<form onSubmit="checkAddress('email'); return false;">
  Email:
  <input type="text" id="email">
  <input type="submit" value="Submit">
</form>

And the following JavaScript to check the email field:

const checkAddress = (fieldId) => {
  if (document.getElementById(fieldId).value === "") {
    alert("Email is required.");
  }
  return false;
}

The checkAddress function gets the value of the input with ID email .

Then if it’s empty, we see the 'Email is required' message in the alert.

We need the return false in the onSubmit attribute and the checkAddress function to prevent the default submit behavior.

We can clean up the function by writing:

const checkAddress = (fieldId) => {
  const {
    value
  } = document.getElementById(fieldId)
  if (value === "") {
    alert("Email is required.");
  }
  return false;
}

Conclusion

We can listen to button, mouse, and input events to listen to events from various input devices and do as we wish with them.