0 Actionable Prompts for Generating JavaScript Functions

JavaScript functions are essential building blocks for creating dynamic and interactive web pages. Whether you are a beginner or an experienced developer, having a set of actionable prompts can help you generate useful functions quickly and efficiently. This article provides 0 practical prompts to inspire your JavaScript coding process and improve your workflow.

1. Create a Function to Toggle Element Visibility

Write a function that accepts an element ID and toggles its visibility. This is useful for show/hide features in your web interface.

function toggleVisibility(elementId) {
  const element = document.getElementById(elementId);
  if (element) {
    if (element.style.display === 'none') {
      element.style.display = 'block';
    } else {
      element.style.display = 'none';
    }
  }
}

2. Generate a Function for Form Validation

Create a function that validates form inputs, such as checking if required fields are filled or if email addresses are valid.

function validateForm(formId) {
  const form = document.getElementById(formId);
  let valid = true;
  const requiredFields = form.querySelectorAll('[required]');
  requiredFields.forEach(field => {
    if (!field.value.trim()) {
      valid = false;
      alert(`Please fill out the ${field.name} field.`);
    }
  });
  return valid;
}

3. Develop a Function to Fetch Data from an API

Write an asynchronous function that fetches data from a specified API endpoint and processes the response.

async function fetchData(apiUrl) {
  try {
    const response = await fetch(apiUrl);
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

4. Create a Debounce Function for Optimized Input Handling

Implement a debounce function that delays invoking a callback until a specified time has elapsed since the last event, useful for search inputs or resize events.

function debounce(func, delay) {
  let timeoutId;
  return function(...args) {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

5. Write a Function to Smooth Scroll to an Element

Create a function that smoothly scrolls the page to a specific element when called.

function smoothScrollTo(elementId) {
  const element = document.getElementById(elementId);
  if (element) {
    element.scrollIntoView({ behavior: 'smooth' });
  }
}

6. Implement a Function to Generate a Random Number Within a Range

This function returns a random integer between two specified values, inclusive.

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

7. Develop a Function to Copy Text to Clipboard

Create a function that copies a given string to the user’s clipboard, useful for sharing links or code snippets.

function copyToClipboard(text) {
  navigator.clipboard.writeText(text).then(() => {
    alert('Text copied to clipboard!');
  }).catch(err => {
    console.error('Could not copy text: ', err);
  });
}

8. Write a Function to Calculate the Difference Between Two Dates

This function computes the number of days between two date strings.

function dateDifference(date1, date2) {
  const d1 = new Date(date1);
  const d2 = new Date(date2);
  const diffTime = Math.abs(d2 - d1);
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  return diffDays;
}

9. Create a Function for Lazy Loading Images

Implement a function that loads images only when they are about to enter the viewport, enhancing page load performance.

function lazyLoadImages() {
  const images = document.querySelectorAll('img[data-src]');
  const observer = new IntersectionObserver((entries, obs) => {
    entries.forEach(entry => {
      if (entry.isIntersecting) {
        const img = entry.target;
        img.src = img.getAttribute('data-src');
        img.removeAttribute('data-src');
        obs.unobserve(img);
      }
    });
  });
  images.forEach(img => {
    observer.observe(img);
  });
}

10. Develop a Function to Detect Browser Language

This function retrieves the user’s preferred language from the browser settings.

function getBrowserLanguage() {
  return navigator.language || navigator.userLanguage;
}