Categories
JavaScript Answers

How to Use the JavaScript Temporal API?

The Temporal API in JavaScript provides a modern way to handle dates and times, offering precise and flexible methods to work with temporal data.

We can use the functions that comes with Temporal API as follows:

Temporal.PlainDate

Temporal.PlainDate represents a calendar date without time or timezone information.

For example, we write

const date = Temporal.PlainDate.from('2023-07-07');
console.log(date.toString()); // 2023-07-07

const now = Temporal.Now.plainDateISO();
console.log(now.toString()); // Current date in YYYY-MM-DD format

const nextWeek = date.add({ days: 7 });
console.log(nextWeek.toString()); // 2023-07-14

const pastDate = date.subtract({ months: 1 });
console.log(pastDate.toString()); // 2023-06-07

Dates are returned in YYYY-MM-DD format.

Temporal.PlainTime

Temporal.PlainTime represents a time of day without a date or timezone.

For instance, we write:

const time = Temporal.PlainTime.from('14:30:00');
console.log(time.toString()); // 14:30:00

const now = Temporal.Now.plainTimeISO();
console.log(now.toString()); // Current time in HH:mm:ss.sss format

const later = time.add({ hours: 2 });
console.log(later.toString()); // 16:30:00

const earlier = time.subtract({ minutes: 15 });
console.log(earlier.toString()); // 14:15:00

Temporal.PlainDateTime

Temporal.PlainDateTime combines a date and a time without timezone information.

For example, we write

const dateTime = Temporal.PlainDateTime.from('2023-07-07T14:30:00');
console.log(dateTime.toString()); // 2023-07-07T14:30:00

const now = Temporal.Now.plainDateTimeISO();
console.log(now.toString()); // Current date and time in YYYY-MM-DDTHH:mm:ss.sss format

const nextHour = dateTime.add({ hours: 1 });
console.log(nextHour.toString()); // 2023-07-07T15:30:00

const pastWeek = dateTime.subtract({ weeks: 1 });
console.log(pastWeek.toString()); // 2023-06-30T14:30:00

Temporal.ZonedDateTime

Temporal.ZonedDateTime represents a date and time with a timezone.

For example, we write:

const zonedDateTime = Temporal.ZonedDateTime.from('2023-07-07T14:30:00+01:00[Europe/London]');
console.log(zonedDateTime.toString()); // 2023-07-07T14:30:00+01:00[Europe/London]

const now = Temporal.Now.zonedDateTimeISO();
console.log(now.toString()); // Current date and time with timezone

const newYorkTime = zonedDateTime.withZone('America/New_York');
console.log(newYorkTime.toString()); // 2023-07-07T09:30:00-04:00[America/New_York]

const later = zonedDateTime.add({ hours: 2 });
console.log(later.toString()); // 2023-07-07T16:30:00+01:00[Europe/London]

Temporal.Duration

Temporal.Duration represents a length of time.

For example, we can use it as follows:

const duration = Temporal.Duration.from({ days: 2, hours: 5 });
console.log(duration.toString()); // P2DT5H

const dateTime = Temporal.PlainDateTime.from('2023-07-07T14:30:00');
const newDateTime = dateTime.add(duration);
console.log(newDateTime.toString()); // 2023-07-09T19:30:00

const elapsed = newDateTime.since(dateTime);
console.log(elapsed.toString()); // P2DT5H

We use Temporal.Duration.from to create the duration of 2 days and 5 hours.

And we can calculate the elapsed time between 2 different date time with since.

Temporal.Calendar

Temporal.Calendar allows for working with different calendar systems.

For example, we write:

const isoDate = Temporal.PlainDate.from('2023-07-07');
const hebrewDate = isoDate.withCalendar('hebrew');
console.log(hebrewDate.toString()); // Hebrew calendar date

const convertedBack = hebrewDate.withCalendar('iso8601');
console.log(convertedBack.toString()); // 2023-07-07

We call withCalendar to convert dates to different calendar systems.

Temporal.TimeZone

Temporal.TimeZone provides information about time zones.

For example, we write

const timeZone = Temporal.TimeZone.from('America/New_York');
const dateTime = Temporal.PlainDateTime.from('2023-07-07T14:30:00');
const zonedDateTime = dateTime.toZonedDateTime(timeZone);
console.log(zonedDateTime.toString()); // 2023-07-07T14:30:00-04:00[America/New_York]

const nowInZone = Temporal.Now.zonedDateTime(timeZone);
console.log(nowInZone.toString()); // Current date and time in the specified time zone

to convert date times to date times with time zones with toZonedDateTime.

And we get the current date time with time zone with zonedDateTime.

The Temporal API offers a more robust and intuitive way to work with date and time in JavaScript, addressing many limitations of the existing Date object.

Categories
JavaScript Answers

How to add a relative URL to a different port number in a hyperlink with HTML?

To add a relative URL to a different port number in a hyperlink with HTML, you can simply specify the port number along with the relative path in the href attribute of the <a> tag.

To do this, we write:

<a href="http://example.com:8080/relative/path">Link to Different Port</a>

In this example, http://example.com:8080 is the base URL with the different port number (8080).

/relative/path is the relative path that you want to navigate to within the specified port.

Replace example.com with your actual domain name and 8080 with the desired port number.

The relative URL /relative/path can be replaced with your specific relative path as needed.

This hyperlink will navigate to the specified relative path on the specified port when clicked.

Categories
JavaScript Answers

How to obfuscate an e-mail address on a website with JavaScript?

Obfuscating an email address on a website with JavaScript involves converting the email address into a format that is not easily recognizable by email harvesting bots, while still allowing it to be interpreted correctly by human users.

One common approach is to replace characters with their HTML entity equivalents.

Here’s a basic example of how you can obfuscate an email address using JavaScript:

HTML:

<!-- Placeholder element to display obfuscated email -->
<p id="obfuscatedEmail"></p>

JavaScript:

// Function to obfuscate email address
function obfuscateEmail(email) {
    let obfuscated = '';
    for (let i = 0; i < email.length; i++) {
        // Convert character to HTML entity
        obfuscated += '&#' + email.charCodeAt(i) + ';';
    }
    return obfuscated;
}

// Original email address
const email = 'example@example.com';

// Obfuscate the email address
const obfuscated = obfuscateEmail(email);

// Display the obfuscated email address
const obfuscatedEmailElement = document.getElementById('obfuscatedEmail');
obfuscatedEmailElement.innerHTML = 'Obfuscated Email: ' + obfuscated;

In this code, we define a function obfuscateEmail that takes an email address as input and returns an obfuscated version of it.

Inside the function, we iterate over each character of the email address and convert it into its corresponding HTML entity using charCodeAt() to get the character code.

Next we then concatenate these HTML entities to form the obfuscated email address.

Then we call the obfuscateEmail function with the original email address, and display the obfuscated email address in an HTML element.

Keep in mind that while this method helps obfuscate the email address from bots, it may still be decipherable by determined attackers.

Additionally, it’s important to consider accessibility concerns, as obfuscating email addresses may make them difficult for screen readers to interpret.

Categories
JavaScript Answers

How to submit a form with JavaScript by clicking a link?

You can submit a form with JavaScript by triggering the form’s submit event when a link is clicked.

To do this, we write:

HTML:

<form id="myForm" action="/submit" method="post">
    <!-- Your form fields go here -->
    <input type="text" name="name" placeholder="Your Name">
    <input type="email" name="email" placeholder="Your Email">
    <button type="submit" id="submitButton">Submit</button>
</form>

<!-- Link to trigger form submission -->
<a href="#" id="submitLink">Submit Form</a>

JavaScript:

// Get reference to the form and the link
const form = document.getElementById('myForm');
const submitLink = document.getElementById('submitLink');

// Add event listener to the link
submitLink.addEventListener('click', function(event) {
    // Prevent the default link behavior (navigating to a new page)
    event.preventDefault();

    // Trigger the form's submit event
    form.submit();
});

In this code, we have an HTML form with some fields and a submit button.

We also have a link with the ID submitLink that will be used to trigger the form submission.

In the JavaScript code, we get references to the form and the link.

We add an event listener to the link that listens for the click event.

When the link is clicked, the default behavior of navigating to a new page is prevented using event.preventDefault().

Then, we trigger the form’s submit event using form.submit(), which submits the form data to the server.

This way, clicking the link will submit the form without reloading the page.

Categories
JavaScript Answers

How to change three.js background to transparent or other color with JavaScript?

In Three.js, you can change the background of your scene to be transparent or any solid color by adjusting the renderer object. Here’s how you can do it:

1. Set the Background to Transparent

If you want the background to be transparent, you can set the alpha property of the renderer to true, and then ensure that your scene’s background is transparent.

2. Set the Background to a Solid Color

If you want to set the background to a solid color, you can use the setClearColor method of the renderer and pass the desired color.

Here’s a code example demonstrating both scenarios:

// Create a scene
const scene = new THREE.Scene();

// Create a camera
const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
camera.position.z = 5;

// Create a renderer
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(window.innerWidth, window.innerHeight);

// Set the background to transparent
renderer.setClearColor(0x000000, 0); // Second argument (alpha) set to 0 for transparency

// Append the renderer to the DOM
document.body.appendChild(renderer.domElement);

// Create a cube
const geometry = new THREE.BoxGeometry();
const material = new THREE.MeshBasicMaterial({ color: 0x00ff00 });
const cube = new THREE.Mesh(geometry, material);
scene.add(cube);

// Animate the cube
function animate() {
    requestAnimationFrame(animate);

    cube.rotation.x += 0.01;
    cube.rotation.y += 0.01;

    renderer.render(scene, camera);
}

animate();

In this example, we create a basic scene with a cube.

We set the background of the renderer to transparent by passing 0x000000 (black) as the clear color and 0 as the alpha value.

We append the renderer to the DOM.

Finally, we animate the cube.

If you want to set the background to a solid color, you can change the setClearColor line to something like renderer.setClearColor(0xffffff) and pass the desired color as an argument (in this case, white).