# Helpful Scripts

## setTimeout

Runs code after 1.5 seconds

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

***

## setInterval

Do something every 1.5 seconds

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

&#x20;

***

## Webflow Ready

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

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

***

## Set cursor div to follow mouse position

```javascript
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

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

&#x20;

***

## Do something on key press

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

***

## Create a press and hold interaction

```javascript
$(".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

{% code overflow="wrap" %}

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

{% endcode %}

#### jQuery

```javascript
$("[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

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

***

## JavaScript matchMedia

Run JavaScript when switching between breakpoints

```javascript
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);
```

***

## Scroll to element on link click

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

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

***

## Show one random item in your cms list

```javascript
$(".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

```javascript
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.

```javascript
$(".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

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

***

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

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

***

## localStorage & sessionStorage

```javascript
// 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`

```javascript
// 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

```javascript
// 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.

```javascript
$(".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

```javascript
// 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

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jquery.timothyricks.com/helpful-scripts.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
