This post is brought to you by Sponsor X, the best way to build paywalls and the sure way to understand your numbers.
Helpful Scripts
setTimeout
Runs code after 1.5 seconds
1setTimeout(() => {
2 // do something
3}, 1500);
setInterval
Do something every 1.5 seconds
1setInterval(function () {
2 // do something
3}, 1500);
Webflow Ready
Run code only after Webflow is ready. Useful for running code after Webflow sliders, tabs, or similar components have been created.
1Webflow.push(function () {
2 console.log("Webflow ready");
3});
Set cursor div to follow mouse position
1let cursor = $(".cursor-div").css({
2position: "fixed", top: "0", left: "0",
3zIndex: "2000"
4});
5$(document).on("mousemove", function (e) {
6 let xPosition = e.pageX;
7 let yPosition = e.pageY - window.scrollY;
8 cursor.css("transform",
9 `translate(${xPosition}px,
10 ${yPosition}px)`);
11});
When typing on a form field, set a text element to match field value
1$(".my-form-field").on("input", function () {
2 let fieldValue = $(this).val();
3 $(".my-text-element").text(fieldValue);
4});
Do something on key press
1$(document).on('keydown', function(e) {
2 if (e.key === "Escape") {
3 console.log("Escape key pressed");
4 }
5});
Create a press and hold interaction
1$(".your-button").on("mousedown touchstart", function() {
2 console.log("Mousedown or touchstart event triggered");
3});
4
5$(".your-button").on("mouseup touchend", function() {
6 console.log("Mouseup or touchend event triggered");
7});
Copy to clipboard
HTML
1<button data-copy-text=
2"This text will be copied on button click">
3</button>
4
5
jQuery
1$("[data-copy-text]").on("click", function () {
2let textToCopy = $(this).attr("data-copy-text");
3let input = $("<input>").appendTo($(this));
4input.val(textToCopy).select();
5document.execCommand("copy");
6input.remove();
7});
Add a 0 in front of any number that's less than 10
1function numberWithZero(num) {
2 if (num > 9) return num;
3 return "0" + num;
4}
5let result = numberWithZero(8);
JavaScript matchMedia
Run JavaScript when switching between breakpoints
1function checkBreakpoint(x) {
2 if (x.matches) {
3 // desktop code here
4 } else {
5 // tablet & below code here
6 }
7}
8const matchMediaDesktop = window.matchMedia("(min-width: 992px)");
9checkBreakpoint(matchMediaDesktop);
10matchMediaDesktop.addListener(checkBreakpoint);
Scroll to element on link click
Scrolls to ".your-section" on click of ".your-link" over 1.5 seconds
1$(".your-link").on("click", function () {
2 $("html, body").animate({ scrollTop:
3 $(".your-section").offset().top }, 1500);
4});
Show one random item in your cms list
1$(".your-cms-list").each(function (index) {
2 let items = $(this).children();
3 let randomNumber = Math.floor(Math.random() * items.length);
4 items.hide().eq(randomNumber).show();
5});
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
1window.onpageshow = function(event) {
2 if (event.persisted) window.location.reload();
3};
Run code on every page that hasn't been visited before
1if (localStorage.getItem(window.location.href) === null) {
2 // run code
3}
4localStorage.setItem(window.location.href, "visited");
localStorage & sessionStorage
1// All these same options work with sessionStorage also
2
3// gets the value of item
4localStorage.getItem("Name");
5// sets the value of item
6localStorage.setItem("Name", "Value");
7// removes item
8localStorage.removeItem("Name");
9// removes all local storagelocalStorage.clear();
10
11// Check if item has been set before
12if (localStorage.getItem("Name") !== null) {
13// item is set
14} else {
15// item is not set
16}
17
18// Check if item equals a certain value
19if (localStorage.getItem("Name") === "Your Name") {
20// item matches
21} else {
22// item does not match
23}
Query Parameters
Example url: https://www.your-website.com/?username=John&hobby=Sports
1// store params
2const params = new URLSearchParams(window.location.search);
3
4// check if the url contains a certain parameter
5if (params.has("username")) {
6 // run code
7}
8
9// check the value of a certain parameter
10if (params.get("username") === "John") {
11 // run code
12}
Control videos
1// get video
2let video = $(".my-section").find("video");
3// pause video
4video[0].pause();
5// play video
6video[0].play();
7// restart video
8video[0].currentTime = 0;
9// mute video
10video.prop('muted', true);
11// unmute video
12video.prop('muted', false);
13// enable loop
14video.prop('loop', true);
15// disable loop
16video.prop('loop', false);
17// on video end (loop must be disabled for this to run)
18video.on('ended', function() {
19 // run code
20});
21// on play
22video.on('play', function() {
23 // run code
24});
25// on pause
26video.on('pause', function() {
27 // run code
28});
29// on timeupdate
30video.on('timeupdate', function() {
31 $(".my-text").text(this.currentTime);
32});
33// on volumechange
34video.on('volumechange', function() {
35 $(".my-text").text(this.volume);
36});
AJAX
On click of ".your-link"
, get ".item-on-next-page"
and add it to current page.
1$(".your-link").on("click", function (e) {
2 e.preventDefault();
3 let link = $(this).attr("href");
4 $.ajax({
5 url: link,
6 success: function (response) {
7 let element = $(response).find(".item-on-next-page");
8 $("body").append(element);
9 },
10 complete: function () {
11 console.log("Got It");
12 }
13 });
14});
On page load, get item from certain page and bring it to current page.
1// include this code on 404 page to add cms navbar to 404 page
2let link = window.location.origin; // homepage url
3$.ajax({
4 url: link,
5 success: function (response) {
6 let element = $(response).find(".your-navbar");
7 $("body").prepend(element);
8 },
9 complete: function () {
10 console.log("Got It");
11 }
12});
Insert text into field while triggering any events attached to that field
1$(".my-field").val("").focus();
2document.execCommand("insertText", false, "Field Text");