Categories
JavaScript Answers

How to make jQuery Datepicker close datepicker after selected date?

To make the jQuery Datepicker close automatically after a date is selected, you can use the onSelect event handler to trigger the closing action.

To do this we can write

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Datepicker Example</title>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<script>
    $(document).ready(function() {
        // Initialize the Datepicker
        $("#datepicker").datepicker({
            onSelect: function(dateText, inst) {
                $(this).datepicker("hide"); // Close the Datepicker after selection
            }
        });
    });
</script>
</head>
<body>
    <p>Select a date:</p>
    <input type="text" id="datepicker">
</body>
</html>

In this code, the onSelect event handler is attached to the Datepicker input field.

When a date is selected, the onSelect function is triggered.

Inside the onSelect function, $(this).datepicker("hide") is used to hide/close the Datepicker popup after a date is selected.

This way, the Datepicker will automatically close after the user selects a date.

Categories
JavaScript Answers

How to limit framerate in Three.js to increase performance, requestAnimationFrame with JavaScript?

Limiting the frame rate in Three.js can be achieved by controlling when you request the next animation frame using requestAnimationFrame.

You can use a technique called frame throttling to achieve this.

To do this we can write:

var lastFrameTime = 0;
var maxFPS = 30; // Set the maximum desired frame rate

function animate() {
    var currentTime = performance.now();
    var deltaTime = currentTime - lastFrameTime;

    // Check if enough time has passed to render the next frame
    if (deltaTime > 1000 / maxFPS) {
        // Update last frame time
        lastFrameTime = currentTime;

        // Your animation/rendering code here
        renderer.render(scene, camera);
    }

    // Request the next frame
    requestAnimationFrame(animate);
}

// Start the animation loop
animate();

In this code, lastFrameTime stores the timestamp of the last frame.

maxFPS specifies the maximum frames per second you want to achieve.

animate function is called recursively using requestAnimationFrame.

Inside animate, the time elapsed since the last frame (deltaTime) is calculated.

The condition deltaTime > 1000 / maxFPS ensures that a frame is rendered only if enough time has passed to maintain the desired frame rate.

By controlling when you request the next animation frame based on the desired frame rate, you effectively limit the frame rate.

This can help increase performance by reducing unnecessary rendering when the screen refresh rate exceeds the desired frame rate.

Categories
JavaScript Answers

How to exclude weekends between two dates using Moment.js and JavaScript?

You can use Moment.js along with JavaScript to exclude weekends (Saturdays and Sundays) between two dates.

To do this we:

  1. Create Moment.js objects for the start and end dates.
  2. Iterate through the dates between the start and end dates.
  3. Check if each date falls on a weekend.
  4. Exclude weekends from the list of dates.

Here’s a code example demonstrating this:

const moment = require('moment');

function getWeekdayDates(startDate, endDate) {
    const dates = [];
    let currentDate = moment(startDate);
    const endDateMoment = moment(endDate);

    while (currentDate.isSameOrBefore(endDateMoment)) {
        // Check if the current date is not a Saturday (6) or Sunday (0)
        if (currentDate.day() !== 6 && currentDate.day() !== 0) {
            dates.push(currentDate.clone().toDate()); // Add the date to the array
        }
        // Move to the next day
        currentDate.add(1, 'day');
    }

    return dates;
}

// Example usage:
const startDate = '2024-04-01'; // Start date (YYYY-MM-DD format)
const endDate = '2024-04-15'; // End date (YYYY-MM-DD format)

const weekdayDates = getWeekdayDates(startDate, endDate);
console.log(weekdayDates);

This code will output an array containing dates between startDate and endDate, excluding weekends.

Ensure you have Moment.js installed via npm or include it via a CDN in your HTML file if you’re using it in a browser environment.

Categories
JavaScript Answers

How to create A Blank HTML Space On The Fly with JavaScript?

To create a blank HTML space dynamically using JavaScript, you can create an empty HTML element such as a <div> or a <span> and then append it to the document.

To do this we can write something like

// Create a new empty div element
var blankSpace = document.createElement('div');

// Set its style to create space
blankSpace.style.width = '100px'; // Set the desired width
blankSpace.style.height = '100px'; // Set the desired height

// Optionally, set other styles like background color, border, etc.
blankSpace.style.backgroundColor = 'lightgray';
blankSpace.style.border = '1px solid black';

// Append the blank space to the document body or any other parent element
document.body.appendChild(blankSpace);

In this example, a <div> element is created dynamically with a specified width and height.

You can adjust the width, height, and other CSS properties to customize the appearance of the blank space according to your requirements.

You can also use a <span> element or any other HTML element depending on your use case.

Categories
JavaScript Answers

How to validate a URL in Node.js?

You can validate a URL in Node.js using regular expressions or by utilizing built-in modules like url.

We can do this 2 ways.

Using Regular Expressions:

function isValidURL(url) {
    // Regular expression for a valid URL
    var urlRegex = /^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|localhost)(?::\d{2,5})?(?:[/?#]\S*)?$/i;
    return urlRegex.test(url);
}

// Example usage:
console.log(isValidURL("https://www.example.com")); // Output: true
console.log(isValidURL("ftp://ftp.example.com/file.txt")); // Output: true
console.log(isValidURL("not_a_url")); // Output: false

Using the url Module:

const url = require('url');

function isValidURL(urlString) {
    try {
        new URL(urlString);
        return true;
    } catch (error) {
        return false;
    }
}

// Example usage:
console.log(isValidURL("https://www.example.com")); // Output: true
console.log(isValidURL("ftp://ftp.example.com/file.txt")); // Output: true
console.log(isValidURL("not_a_url")); // Output: false

Both methods provide a way to check if a given string is a valid URL.

The second method using the url module is more concise and reliable because it leverages built-in functionality.