Categories
JavaScript Answers

How to get relative time 24 hours ago as time with JavaScript?

To get the relative time 24 hours ago using JavaScript, you can create a new Date object for the current time and then subtract 24 hours from it.

To do this, we can write

// Get the current time
var currentTime = new Date();

// Subtract 24 hours (24 * 60 * 60 * 1000 milliseconds)
var twentyFourHoursAgo = new Date(currentTime - 24 * 60 * 60 * 1000);

// Format the date to display
var formattedTime = twentyFourHoursAgo.toLocaleString();

console.log("24 hours ago:", formattedTime);

In this code, we create a new Date object called currentTime, representing the current time.

We then subtract 24 hours from currentTime by creating a new Date object called twentyFourHoursAgo using the milliseconds equivalent of 24 hours.

Finally, we format the twentyFourHoursAgo date object into a human-readable string using the toLocaleString() method.

This will give you the date and time 24 hours ago relative to the current time. You can adjust the formatting to suit your needs.

Categories
JavaScript Answers

How to manually add some items with Selectize.js?

To manually add items to a Selectize.js dropdown, you can use the addOption() method.

To do this we can try the following.

1. Include Selectize.js

Make sure you have included Selectize.js in your HTML file. You can either download it and include it locally or use a CDN.

<link rel="stylesheet" href="path/to/selectize.css">
<script src="path/to/selectize.js"></script>

2. Create HTML Select Element

Create a select element in your HTML file and give it an ID.

<select id="mySelect"></select>

3. Initialize Selectize

Use JavaScript to initialize the Selectize plugin on your select element.

var mySelect = $('#mySelect').selectize({
    create: true,
    sortField: 'text'
});

4. Add Items Programmatically

You can then add items to the select element using the addOption() method.

var selectize = mySelect[0].selectize;

// Add items manually
selectize.addOption({value: '1', text: 'Option 1'});
selectize.addOption({value: '2', text: 'Option 2'});

You can call addOption() as many times as needed to add multiple items.

5. Trigger Dropdown Refresh

After adding options, you might need to refresh the dropdown to reflect the changes. You can do this by calling the refreshOptions() method.

selectize.refreshOptions();

That’s it! You’ve now manually added items to a Selectize.js dropdown. This can be useful when you want to dynamically populate the dropdown based on user actions or data from an external source.

Categories
JavaScript Answers

How to create and submitting a form with JavaScript?

Creating and submitting a form with JavaScript involves several steps. Here’s a basic guide:

1. Create the HTML Form

First, you need to create an HTML form in your webpage. This form should contain input fields, buttons, etc., that you want to include. For example:

<form id="myForm">
  <label for="name">Name:</label>
  <input type="text" id="name" name="name"><br><br>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email"><br><br>
  <button type="button" onclick="submitForm()">Submit</button>
</form>

2. JavaScript Function to Handle Form Submission

Create a JavaScript function to handle the form submission. This function will be called when the submit button is clicked.

In this function, you can gather the form data and perform any necessary processing.

function submitForm() {
  // Get form data
  var name = document.getElementById("name").value;
  var email = document.getElementById("email").value;

  // Create an object to hold the form data
  var formData = {
    name: name,
    email: email
  };

  // Do something with the form data (e.g., send it to a server)
  // For example, you can use AJAX to send the data asynchronously
  // Here, I'm just logging the data to the console
  console.log(formData);
}

3. Submitting the Form

Depending on your requirements, you might want to submit the form data to a server.

This can be done using various methods such as AJAX or by setting the form’s action attribute to the URL of a server-side script.

If you want to submit the form using AJAX, you can use the XMLHttpRequest object or the fetch API.

Here’s an example using fetch:

function submitForm() {
  var name = document.getElementById("name").value;
  var email = document.getElementById("email").value;

  var formData = {
    name: name,
    email: email
  };

  // Send form data to server using fetch
  fetch('submit.php', {
    method: 'POST',
    body: JSON.stringify(formData),
    headers: {
      'Content-Type': 'application/json'
    }
  })
  .then(response => {
    if (response.ok) {
      console.log('Form submitted successfully');
    } else {
      console.error('Form submission failed');
    }
  })
  .catch(error => {
    console.error('Error:', error);
  });
}

Remember to replace 'submit.php' with the URL of your server-side script.

Categories
JavaScript Answers

How to Remove “OK” button from sweet alert dialog with JavaScript?

To remove the “OK” button from a SweetAlert dialog using JavaScript, you can customize the SweetAlert options.

To do this we can write

Swal.fire({
  title: 'Custom HTML title',
  html: 'I will close in <strong></strong> milliseconds.',
  timer: 2000,
  timerProgressBar: true,
  showConfirmButton: false, // Remove the "OK" button
  allowOutsideClick: false, // Prevent the dialog from closing by clicking outside
  allowEscapeKey: false // Prevent the dialog from closing by pressing the escape key
});

In this code, showConfirmButton: false removes the “OK” button from the SweetAlert dialog.

timer specifies the duration (in milliseconds) after which the dialog will automatically close.

timerProgressBar: true displays a progress bar indicating the remaining time before the dialog closes.

allowOutsideClick: false and allowEscapeKey: false prevent the user from closing the dialog by clicking outside or pressing the escape key, respectively.

Adjust the SweetAlert options according to your specific requirements.

This configuration will create a dialog that automatically closes after a specified duration without requiring any user interaction.

Categories
Angular Answers

How to lock mat-toolbar and mat-tabs to the top with Angular Material 2?

To lock a mat-toolbar and mat-tab component to the top of the page using Angular Material 2, you can use CSS positioning or Angular’s sticky directive.

We can try the following:

Using CSS Positioning

HTML:

<mat-toolbar color="primary" class="sticky-toolbar">
    <!-- Toolbar content -->
</mat-toolbar>

<mat-tab-group class="sticky-tabs">
    <mat-tab label="Tab 1">
        <!-- Tab content -->
    </mat-tab>
    <mat-tab label="Tab 2">
        <!-- Tab content -->
    </mat-tab>
</mat-tab-group>

CSS:

.sticky-toolbar {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    z-index: 1000; /* Ensure toolbar is above other content */
}

.sticky-tabs {
    margin-top: 64px; /* Adjust according to toolbar height */
}

Using Angular’s Sticky Directive

HTML:

<mat-toolbar color="primary" sticky>
    <!-- Toolbar content -->
</mat-toolbar>

<mat-tab-group sticky>
    <mat-tab label="Tab 1">
        <!-- Tab content -->
    </mat-tab>
    <mat-tab label="Tab 2">
        <!-- Tab content -->
    </mat-tab>
</mat-tab-group>

Angular Component:

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

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

CSS:

/* Add any additional styling as needed */

In this approach, the mat-toolbar and mat-tab-group components are given the sticky attribute, which enables sticky behavior.

CSS adjustments may be required for positioning the tabs below the toolbar to ensure they don’t overlap.

Both methods should effectively lock the toolbar and tabs to the top of the page.