Helpful Scripts

setTimeout

Runs code after 1.5 seconds

setTimeout(() => {  
    // do something
}, 1500);


setInterval

Do something every 1.5 seconds

setInterval(function () {
    // do something
}, 1500);


Webflow Ready

Run code only after Webflow is ready. Useful for running code after Webflow sliders, tabs, or similar components have been created.

Webflow.push(function () {
  console.log("Webflow ready");
});


Set cursor div to follow mouse position

let cursor = $(".cursor-div").css({ position: "fixed", top: "0", left: "0", zIndex: "2000" });
$(document).on("mousemove", function (e) {
  let xPosition = e.pageX;
  let yPosition = e.pageY - window.scrollY;
  cursor.css("transform", `translate(${xPosition}px, ${yPosition}px)`);
});


When typing on a form field, set a text element to match field value

$(".my-form-field").on("input", function () {
  let fieldValue = $(this).val();
  $(".my-text-element").text(fieldValue);
});


Do something on key press

$(document).on('keydown', function(e) {
    if (e.key === "Escape") {
        console.log("Escape key pressed");
    }
});


Create a press and hold interaction

$(".your-button").on("mousedown touchstart", function() {
    console.log("Mousedown or touchstart event triggered");
});

$(".your-button").on("mouseup touchend", function() {
    console.log("Mouseup or touchend event triggered");
});


Copy to clipboard

HTML

<button data-copy-text="This text will be copied on button click"></button>

jQuery

$("[data-copy-text]").on("click", function () {
  let textToCopy = $(this).attr("data-copy-text");
  let input = $("<input>").appendTo($(this));
  input.val(textToCopy).select();
  document.execCommand("copy");
  input.remove();
});


Add a 0 in front of any number that's less than 10

function numberWithZero(num) {
  if (num > 9) return num;
  return "0" + num;
}
let result = numberWithZero(8);


JavaScript matchMedia

Run JavaScript when switching between breakpoints

function checkBreakpoint(x) {
  if (x.matches) {
    // desktop code here
  } else {
    // tablet & below code here
  }
}
const matchMediaDesktop = window.matchMedia("(min-width: 992px)");
checkBreakpoint(matchMediaDesktop);
matchMediaDesktop.addListener(checkBreakpoint);


Scrolls to ".your-section" on click of ".your-link" over 1.5 seconds

$(".your-link").on("click", function () {
  $("html, body").animate({ scrollTop: $(".your-section").offset().top }, 1500);
});


Show one random item in your cms list

$(".your-cms-list").each(function (index) {
  let items = $(this).children();
  let randomNumber = Math.floor(Math.random() * items.length);
  items.hide().eq(randomNumber).show();
});


Add commas to number

function numberWithCommas(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
let yourNumber = numberWithCommas(5240);


Show a different div for each day of the week

Apply code to a list containing 7 divs. The first div should be for Sunday.

$(".your-list").each(function (index) {
  let currentDay = +new Date().getDay();
  let items = $(this).children();
  let currentItem = items.eq(currentDay);
  items.not(currentItem).remove();
});


Reload page on browser back button click

Reload page when hitting back button instead of pulling up cached version

window.onpageshow = function(event) {
    if (event.persisted) window.location.reload();
};


Run code on every page that hasn't been visited before

if (localStorage.getItem(window.location.href) === null) {
    // run code
}
localStorage.setItem(window.location.href, "visited");


localStorage & sessionStorage

// All these same options work with sessionStorage also

// gets the value of item
localStorage.getItem("Name");
// sets the value of item
localStorage.setItem("Name", "Value");
// removes item
localStorage.removeItem("Name");
// removes all local storage
localStorage.clear();

// Check if item has been set before
if (localStorage.getItem("Name") !== null) {
	// item is set
} else {
	// item is not set
}

// Check if item equals a certain value
if (localStorage.getItem("Name") === "Your Name") {
	// item matches
} else {
	// item does not match
}


Query Parameters

Example url: https://www.your-website.com/?username=John&hobby=Sports

// store params
const params = new URLSearchParams(window.location.search);

// check if the url contains a certain parameter
if (params.has("username")) {
	// run code
}

// check the value of a certain parameter
if (params.get("username") === "John") {
	// run code
}


Control videos

// get video
let video = $(".my-section").find("video");
// pause video
video[0].pause();
// play video
video[0].play();
// restart video
video[0].currentTime = 0;
// mute video
video.prop('muted', true);
// unmute video
video.prop('muted', false);
// enable loop
video.prop('loop', true);
// disable loop
video.prop('loop', false);
// on video end (loop must be disabled for this to run)
video.on('ended', function() {
    // run code
});
// on play
video.on('play', function() {
    // run code
});
// on pause
video.on('pause', function() {
    // run code
});
// on timeupdate
video.on('timeupdate', function() {
    $(".my-text").text(this.currentTime);
});
// on volumechange
video.on('volumechange', function() {
    $(".my-text").text(this.volume);
});


AJAX

On click of ".your-link", get ".item-on-next-page" and add it to current page.

$(".your-link").on("click", function (e) {
  e.preventDefault();
  let link = $(this).attr("href");
  $.ajax({
    url: link,
    success: function (response) {
      let element = $(response).find(".item-on-next-page");
      $("body").append(element);
    },
    complete: function () {
      console.log("Got It");
    }
  });
});

On page load, get item from certain page and bring it to current page

// include this code on 404 page to add cms navbar to 404 page
let link = window.location.origin; // homepage url
$.ajax({
  url: link,
  success: function (response) {
    let element = $(response).find(".your-navbar");
    $("body").prepend(element);
  },
  complete: function () {
    console.log("Got It");
  }
});


Insert text into field while triggering any events attached to that field

$(".my-field").val("").focus();
document.execCommand("insertText", false, "Field Text");

Last updated