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.

Categories
Angular Material

Angular Material — Radio Buttons, Ripple Effects, and Select Dropdowns

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Radio Button

We can add a radio button with Angular Material.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatRadioModule } from '@angular/material/radio';
import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatRadioModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  favoriteFruit: string;
  fruits: string[] = ['apple', 'orange', 'grape'];
}

app.component.html

<div>
  <label>Pick your favorite fruit</label>
  <mat-radio-group [(ngModel)]="favoriteFruit">
    <mat-radio-button *ngFor="let fruit of fruits" [value]="fruit">
      {{fruit}}
    </mat-radio-button>
  </mat-radio-group>
  <div>Your favorite fruit is: {{favoriteFruit}}</div>
</div>

We import the MatRadioModule and FormsModule to add the radio button with data binding.

Then in app.component.html , we add the mat-radio-group to bind the value with ngModel .

Inside it, we loop through the fruits array and render the buttons with the mat-radio-button component.

The value has the radio button value.

Now when we click on a radio button, we should see the favoriteFruit value change since we bind the radio button value with ngModel .

Ripples

We can add a ripple effect when we click or tap on something.

For example, we can write:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatRippleModule } from '@angular/material/core';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatRippleModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  myColor = 'lightyellow'
}

app.component.html

<div>
  <div matRipple [matRippleColor]="myColor">
    hello world
  </div>
</div>

We import the MatRippleModule to add the effect.

Then we add the matRipple directive to the div with the matRippleColor to set the color of the ripple effect.

Now when we click or tap on ‘hello world’, we see the ripple effect.

Select

We can add a select dropdown with the MatSelectModule .

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatSelectModule } from '@angular/material/select';
import { MatFormFieldModule } from '@angular/material/form-field';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatSelectModule,
    MatFormFieldModule,
    FormsModule,
    ReactiveFormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { FormControl } from '@angular/forms';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  toppings = new FormControl();
  toppingList: string[] = ['Extra cheese', 'Mushroom', 'Onion', 'Pepperoni', 'Sausage', 'Tomato'];
}

app.component.html

<div>
  <mat-form-field appearance="fill">
    <mat-label>Toppings</mat-label>
    <mat-select [formControl]="toppings" multiple>
      <mat-select-trigger>
        {{toppings.value ? toppings.value[0] : ''}}
        <span *ngIf="toppings.value?.length > 1">
          (+{{toppings.value.length - 1}}
          {{toppings.value?.length === 2 ? 'other' : 'others'}})
        </span>
      </mat-select-trigger>
      <mat-option *ngFor="let topping of toppingList" [value]="topping">
        {{topping}}</mat-option>
    </mat-select>
  </mat-form-field>
</div>

We add the FormsModule and ReactiveFormsModule to let us bind the value selected with a reactive form control.

In the template, we rendered the toppingList with the mat-option component.

The mat-select-trigger lets us trigger the dropdown.

We display the selected items by rendering the toppings string.

Now we should see a dropdown that lets us pick one or more items from the list.

Conclusion

We can add radio buttons, ripple effects, and dropdowns with Angular Material.

Categories
Angular Material

Angular Material — Paginator and, Progress Bar, and Progress Spinner

Angular Material is a popular UI framework based on Material Design for Angular.

In this article, we’ll look at how to use Angular Material into our Angular project.

Paginator

The paginator component lets us add a form control to control the pagination settings.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatPaginatorModule } from '@angular/material/paginator';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatPaginatorModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <mat-paginator [length]="100" [pageSize]="10"
    [pageSizeOptions]="[5, 10, 25, 100]">
  </mat-paginator>
</div>

We add the mat-paginator component to add a pagination control.

length is the total number of entries.

pageSize is the size of the page.

pageSizeOptions is an array of page sizes we can set.

Progress Bar

We can add a progress bar with the mat-progress-bar component.

For example, we can write:

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatProgressBarModule } from '@angular/material/progress-bar';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatProgressBarModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div>
  <mat-progress-bar mode="buffer"></mat-progress-bar>
</div>

We add the MatProgressBarModule to add a progress bar.

The mat-progress-bar adds the progress bar.

The mode attribute sets the appearance of the progress bar.

We can also make it determinate:

<div>
  <mat-progress-bar mode="determinate" value="40"></mat-progress-bar>
</div>

or indeterminate:

<div>
  <mat-progress-bar mode="indeterminate"></mat-progress-bar>
</div>

Progress Spinner

The mat-progress-spinner lets us add a progress spinner to our app.

For example, we can write:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatProgressSpinnerModule } from '@angular/material/progress-spinner';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    BrowserAnimationsModule,
    MatProgressSpinnerModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component } from '@angular/core';
import { ThemePalette } from '@angular/_material_/core';
import { ProgressSpinnerMode } from '@angular/material/progress-spinner';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  color: ThemePalette = 'primary';
  mode: ProgressSpinnerMode = 'indeterminate';
  value = 50;
}

app.component.html

<div>
  <mat-progress-spinner class="example-margin" [color]="color" [mode]="mode"
    [value]="value">
  </mat-progress-spinner>
</div>

We add the MatProgressSpinnerModule to let us add the progress spinner.

Then in app.component.ts , we add the color , mode and value variables to set the color, spinner mode, and the progress value respectively.

In the template, we add the mat-progress-spinner component to set those variables to the attributes.

The value is used when the progress spinner has mode set to 'determinate' .

Conclusion

We can add the paginator, progress bar, and progress spinner with Angular Material.