Back Button in Onsen UI Navigator Triggering Validation Checks

I’m building out a small vehicle inspection form application for my wife’s company using Onsen UI. The app allows users to visually and functionally check that a vehicle is free from damage and functioning as expected upon delivery. Users should be able to freely navigate between eight pages in the app, and when they get to the last page all data will be stored to a MySQL database. Before advancing to the next page in the flow, some simple validation checks are performed to make sure required data has been input.

All was working fine until I began adding validation checks into the flow. The problem I’m seeing is that when the Back button is clicked, the validation checks that should be performed when the Next button is clicked are triggered. I’m struggling to understand why the checks are triggering.

Each page has checks such as the following performed when the Next button is clicked:

function next(){
            // Check each set of radio buttons to see if checked
            var envelopeChecked = checkRadios('envelope'),
                insuranceChecked = checkRadios('insurance'),
                accidentChecked = checkRadios('accident'),
                registrationChecked = checkRadios('registration'),
                manualChecked = checkRadios('manual');    
            
            // If all radio buttons checked, the initial validity test is passed    
            var isFormValid = envelopeChecked &&
                insuranceChecked &&
                accidentChecked &&
                registrationChecked &&
                manualChecked;
                console.log(isFormValid);
            
            // TO DO: Add logic to check for entered value description for any observed damages
            
            if (!isFormValid) {
                console.log('Missing radio options page3');
            } else {
                const navigator = document.querySelector('#navigator');
                /*navigator.pushPage('page4.html');*/
                navigator.bringPageTop('page4.html');
            }

checkRadios and checkText are simple validation checks to make sure all radio button groups have an option checked and all required textarea inputs have text. Any ideas on why these validation checks are triggering on the Back button?

Tealium custom container javascript running with page view trigger but not with click (add to cart tracking)

I have a custom container tag that I have stripped down to one console.log statement for debugging purposes.

When I set the rule for this tag to all pages or to specific pages and turn on Tealium debugging output, the console statement comes in the output right after

SENDING: [my tag’s tealium UID]

After some work to set up the correct trigger that fires on a link event for add to cart, I can see it still SENDING: but I don’t think the custom container tag’s javascript runs and there is no console output from the tag.

I don’t have an extension associated with this tag, although I am going to need one.

How does this JS sort when it has a function inside that returns multiple things?

I created a secondary sort and its working but I don’t understand how.

    this.report.sort((a, b) => {
        if(a[col] > b[col]) return 1;
        if(a[col] < b[col]) return -1;
        if(a[secondaryFilter] > b[secondaryFilter]) return  1;
        if(a[secondaryFilter] < b[secondaryFilter]) return -1;
    });

I thought when the sort sees the first return, it would exit the sort. How does it reach the secondary filter sort?

The code works and I learned the syntax online but I don’t get how it works.

Generate a ggplot2 palette in javascript

The ggplot2 color palette is very common in data visualization, but how can we get a similar palette generated on the web?

At this point, i would consider just manually generating some palettes using R code, and copying the resulting hex codes to a data array in JS, but having an accurate formula for the coloring would be interesting

I am trying the built-in LCH (light chroma hue) support in CSS, but the spectrum that the CSS LCH has seems to just not match what R has. I also tried oklch and it is a bit better, but still doesn’t match

reference https://developer.mozilla.org/en-US/docs/Web/CSS/hue

// tested and this matches R version of seq
// reproduced from https://stackoverflow.com/questions/8197559/emulate-ggplot2-default-color-palette
function seq(start, end, n) {
  return Array.from(
    { length: n + 1 },
    (_, i) => start + (i * (end - start)) / n
  );
}
function gg_color_hue(n) {
  const hues = seq(50, 410, n);
  return hues.map((h) => `lch(65% 100% ${h})`).slice(0, n);
}

function ColRow({ n }) {
  const cols = gg_color_hue(n);
  return (
    <div>
      {cols.map((c) => (
        <div
          style={{
            display: "inline-block",
            width: 100,
            height: 100,
            background: c,
          }}
        ></div>
      ))}
    </div>
  );
}

export default function App() {
  return (
    <>
      <ColRow n={2} />
      <ColRow n={3} />
      <ColRow n={4} />
      <ColRow n={5} />
      <ColRow n={6} />
    </>
  );
}

color palette generated by the JS code

lch palette from js

color palette generated by the JS code if lch is replaced with oklch

oklch palette from js

color palettes generated by R code

R palette

code sandbox https://codesandbox.io/p/sandbox/funny-archimedes-jj6h77?file=%2Fsrc%2FApp.js%3A1%2C1-64%2C1

Trigger function ONLY on threshold changes with continuously-updating variables?

I’m trying to make a simple local webpage (not for production, this is just a personal project) that changes image randomly from a set when I tilt my tablet past a threshold using HTML and Javascript. So far, I’ve got the accelerometer giving me continuously-updated values (which I’m assuming is necessary, else there may be problems detecting the tilt on time), and I can get it to partially work if I set static images instead of randomly-selected ones. Once I add the randomization in there, it falls apart.

I can’t figure out how to only make the randomize bit trigger on threshold changes. So far, it seems the proxy bit of code runs the display function every time the tablet tilt changes even a tiny bit (which is no different behavior than when I wasn’t using proxies), causing the images to flicker and flash between all possible images. I’ve tried a few different things, the most recent being using proxy to detect changes (but that doesn’t seem to work either).

It’s only for a small personal project, but I’ve been working at this for a few days now and still haven’t cracked it, so any input would be appreciated!

JS:

window.onload = function () {

    var displayImage = './resources/main.png';

    let main1 = './resources/main.png'
    let main2 = './resources/main2.png'
    let left1 = './resources/left.png'
    let left2 = './resources/left2.png'
    let right1 = './resources/right.png'
    let right2 = './resources/right2.png'
    let right3 = './resources/right3.png'
    let down1 = './resources/down.png'
    let down2 = './resources/down2.png'
    let down3 = './resources/down3.png'
    let up1 = './resources/up.png'
    let up2 = './resources/up2.png'

    let main = [main1, main2]
    let left = [left1, left2]
    let right = [right1, right2, right3]
    let down = [down1, down2, down3]
    let up = [up1, up2]

    const obj = {};
    const handler = {
        get(target, key) {
            if (typeof target[key] === "object" && target[key] !== null) {
                return new Proxy(target[key], handler)
            }
            return target[key]
        },
        set(target, prop, value) {
            console.log(target[prop], value)
            if (!target[prop]) {
                console.log('no target[prop]')
            } else if (target[prop] === value) {
                console.log('same value')
            } else {
                display(value);
            }
            target[prop] = value;
            return true;
        }
    }
    const tilt = new Proxy(obj, handler)

    function handleMotionEvent(event) {
        let x = event.accelerationIncludingGravity.x;
        let y = event.accelerationIncludingGravity.y;
        let z = event.accelerationIncludingGravity.z;

        if (-3 < x < 3 && -2 < z < 5) {
            tilt.pos = 'def'
        }
        if (x < -3 && -2 < z < 5) {
            tilt.pos = 'left'
        }
        if (x > 3 && -2 < z < 5) {
            tilt.pos = 'right'
        }
        if (-3 < x < 3 && z > 5) {
            tilt.pos = 'up'
        }
        if (-3 < x < 3 && z < -2) {
            tilt.pos = 'down'
        }
    }

    function display(value) {
        if (value === 'def') {
            displayImage = main[Math.floor(Math.random() * main.length)];
        }
        if (value === 'left') {
            displayImage = left[Math.floor(Math.random() * left.length)];
        }
        if (value === 'right') {
            displayImage = right[Math.floor(Math.random() * right.length)];
        }
        if (value === 'up') {
            displayImage = up[Math.floor(Math.random() * up.length)];
        }
        if (value === 'down') {
            displayImage = down[Math.floor(Math.random() * down.length)];
        }

        document.getElementById('displayimage').src = displayImage;
    }

    window.addEventListener("devicemotion", handleMotionEvent, true);

}

Javascript Code for Image Advancement // Squarespace 7.1 Specific

I’m working on customizing my website and some funcationality. I recently added this which allows the user to cycle through images in a slideshow with the left and right arrows. The live website is www.gregmionske.com for reference.

<script>
document.addEventListener('keydown', function(event) {
    let buttons = document.querySelectorAll('.gallery-slideshow-control-btn');
    // Check for the right arrow key for the 'next' button
    if (event.key === "ArrowRight") {
        let nextButton = buttons.length > 1 ? buttons[1] : null; // Assumes the next button is the second button
        if (nextButton) {
            nextButton.click();
        }
    }
    // Check for the left arrow key for the 'prev' button
    else if (event.key === "ArrowLeft") {
        let prevButton = buttons.length > 0 ? buttons[0] : null; // Assumes the prev button is the first button
        if (prevButton) {
            prevButton.click();
        }
    }
});
</script>

Now I’m trying to add a function where when the user clicks on the right half of the .page-section they are able to advance to the next image and when they click on the left half they are able to go to the previous image in the gallery.

I tried using this script, however the function only appears to work on the left half of the screen for cycling through previous images. I can only advance to the next image by clicking on the actual next arrow located on the page.

document.querySelector('.page-section').addEventListener('click', function(event) {
    let bounds = this.getBoundingClientRect();
    let x = event.clientX - bounds.left;
    let buttons = document.querySelectorAll('.gallery-slideshow-control-btn');
    // If click is on the right half of the page section
    if (x > bounds.width / 2) {
        let nextButton = buttons.length > 1 ? buttons[1] : null; // Assumes the next button is the second button
        if (nextButton) {
            nextButton.click();
        }
    }
    // If click is on the left half of the page section
    else {
        let prevButton = buttons.length > 0 ? buttons[0] : null; // Assumes the prev button is the first button
        if (prevButton) {
            prevButton.click();
        }
    }
});

Find position of cursor in monaco editor from window object

I am trying to find the cursor position in an editor instance of a monaco editor on the page that has already been created. I am doing this through a browser extension so I don’t have access to the code that created the editor.

I just want to find the position of the cursor in the editor. But for that I need to somehow get the instance of the editor on the page.

Can I somehow do this using a combination of the model and the DOM element of the editor?

I can see there is a monaco.editor property on window but window.monaco.editor.getEditors() is not a function.

const model = monaco.editor.getModels()[0]; // Returns the actual model used on the page

const container = document.querySelector(".monaco-editor").parentElement; // the editor in the DOM

const editorInstance = window.monaco.editor.getEditors(); // Not a function

Not all elements are being replaced

I’m having issues replacing iframes with text about each iframe. Here’s an example below:

// once
console.log(document.getElementsByTagName("iframe").length)
for (let iframe of document.getElementsByTagName("iframe")) {
  iframe.replaceWith(`"${iframe.title}": ${iframe.src}`)
}

// twice
console.log(document.getElementsByTagName("iframe").length)
for (let iframe of document.getElementsByTagName("iframe")) {
  iframe.replaceWith(`"${iframe.title}": ${iframe.src}`)
}

// thrice
console.log(document.getElementsByTagName("iframe").length)
for (let iframe of document.getElementsByTagName("iframe")) {
  iframe.replaceWith(`"${iframe.title}": ${iframe.src}`)
}
console.log(document.getElementsByTagName("iframe").length)
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>
<iframe width="560" height="315" src="https://www.youtube.com/embed/AW8OOp2undg?si=GSgNE9ERhGMkX_o4" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen=""></iframe>

As shown in the console, we begin with 7 iframes, which goes down to 3, then 1, and finally 0. Why isn’t the first for-loop replacing all the iframes? Am I doing something wrong?

Why is the fetch url not updating on button click

I’m working on a JavaScript only project and can’t seem to get my fetch api url to update when I click the happy button. I’ve included my JavaScript below. Any ideas?

I don’t know why but stack overflow wants me to write more non code so i’m just blabbing about that to include more text :/

let apiUrl = 'https://api.quotable.io/random?tags='
let happyUrl = 'happiness'
let endPoint = '';
let choiceUrl = `${apiUrl}${endPoint}`;
console.log(choiceUrl)

async function quoteOptions() {

  let quoteTypes = document.createElement('div');

  quoteTypes.innerHTML =
    `<div class='container2'>
    <p>Welcome! How are you feeling today?</p>
        <button id="happyBtn">Happy</button>
        <button id="motivationalBtn">Motivational</button>
        <button id="lovedBtn">Loved</button>
        <button id="humorousBtn">Silly</button>
      </div>`

  let content = document.querySelector('.container');
  content.appendChild(quoteTypes)

}
quoteOptions();

async function fetchQuoteOption() {

  try {

    const response = await fetch(`${apiUrl}${endPoint}`);
    const data = await response.json();
    console.log(data);
    return data;

    console.log(`Why is ${endPoint} not updating?`);

  } catch (error) {
    console.error('Error:', error);
  }

}

document.getElementById("happyBtn").addEventListener("click", myFunction);

function myFunction() {
  let endPoint = 'happiness';

  fetchQuoteOption();
}

Sizing a canvas (in javascript) via ‘style’ gives bad results?

I want to generate my canvas in javascript. Sizing it via ‘style’ doesn’t work. (Option ‘a’ in my code) Why?

But the way to do it is with canvas.width and .height (Option ‘b’). The default size is Option ‘c’.

<html>
  <head>
    <meta charset="utf-8">
    <style>
canvas { outline:1px dotted black; } 
    </style>
  </head>
  <body>
    <script>
  "use strict";
  let option = prompt('a, b, or c','a');
  let canvas = document.createElement('canvas');
  canvas.setAttribute('id','canvas');
  switch(option) {
  case 'a': // setting size with style - NG
    canvas.setAttribute('style','width:500px; height:500px;');
    break;
  case 'b': // setting size with .width/.height - OK
    canvas.width = 500;
    canvas.height = 500;
    break;
  case 'c':
  default: // default size
    option = 'c';
  }
  document.body.appendChild(canvas);
  let ctx = canvas.getContext("2d")
  ctx.font = '20px Ariel';
  ctx.fillText('Option: '+option,10,20);
  ctx.arc(250,250,200, 0, 6.2832);
  ctx.stroke();
    </script>
  </body>
</html>

What’s currently the best way to get onKeyUp events on Chrome in Android?

keyUp is not supported on Android Chrome due to using a virtual keyboard. e.key will always be Undefined, and e.keyCode will always be 229 no matter which key you use. This feature is depreciated https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event .

I want to know which key a user has done “keyUp” on last. What I have seen as proposed solutions are hacks, for example, if a user is using a textarea, just get the last character of the textarea target value. But these are not true solutions, if a user is editing the middle of a paragraph in a textarea, then this method will not work.

In modern Android Chrome browsers, what is the preferred way of getting a keyUp event?

Is there a way to set a cookie using JS and force a dynamic element reliant on the cookie to update without reloading the page?

apologies if the title question is confusing, but I’m not entirely sure how to ask or phrase this. Basically, I want a button to trigger (it opens a popup) on page load—easy enough.

However, the button is a “Find a Location” thing, so upon a user’s first-time (or cookie-less) visit, they see that button. If the user clicks it and inputs their location info, they get redirected to a page, and the button changes to one displaying their location, and the popup content also changes; the button gets fed a stored cookie with the location info, which is how the content updates.

I need to figure out a way to get this location info, via this cookie, injected on page load without the user having to enter their information at all, OR refreshing/navigating away from the page.

Right now, I have a function written to set the cookie upon load, and then automatically trigger the popup, but the button does not automatically update via the manual cookie setting unless the user reloads the page. I need everything to happen in one seamless motion. Is this feasible, or no?

I need to do this via Javascript, if it is even possible—no other methods, please. Also, this is not something I can do via the site’s back end or some CMS either.

Thanks.

When a node is created in JavaScript the value property is not updating [closed]

I am trying to make a sign-in system, and currently I am just using document.createElement('input') to create the input element then appending it to the container element.

But, when I try to access the value property later, it is not updating. I am really confused because when I select the input element in the Elements panel and then type $0.value in the console, the value is correct. It turns out inputElementCreatedInJavascript != $0. Shouldn’t they be the same object?!?

I have no idea how to solve this problem – I always thought that all referneces to an element were the same. Can someone explain this to me?!?

useSearchParams() should be wrapped in a suspense boundary at page

How can I add the Suspense tags to the following code :-

"use client";

import { Suspense, useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Suspense } from 'react'

import Form from "@components/Form";

const UpdatePrompt = () => {
    const router = useRouter();
    const searchParams = useSearchParams();
    const promptId = searchParams.get("id");

    const [post, setPost] = useState({ prompt: "", tag: "", });
    const [submitting, setIsSubmitting] = useState(false);

    useEffect(() => {
        const getPromptDetails = async () => {
            const response = await fetch(`/api/prompt/${promptId}`);
            const data = await response.json();

            setPost({
                prompt: data.prompt,
                tag: data.tag,
            });
        };

        if (promptId) getPromptDetails();
    }, [promptId]);

    const updatePrompt = async (e) => {
        e.preventDefault();
        setIsSubmitting(true);

        if (!promptId) return alert("Missing PromptId!");

        try {
            const response = await fetch(`/api/prompt/${promptId}`, {
                method: "PATCH",
                body: JSON.stringify({
                    prompt: post.prompt,
                    tag: post.tag,
                }),
            });

            if (response.ok) {
                router.push("/");
            }
        } catch (error) {
            console.log(error);
        } finally {
            setIsSubmitting(false);
        }
    };

    return (
        <Suspense>
            <Form
                type='Edit'
                post={post}
                setPost={setPost}
                submitting={submitting}
                handleSubmit={updatePrompt}
            />
        </Suspense>
    );
};

export default UpdatePrompt;

I tried adding it in the return statement but during deployment in Vercel this error showed :-
Error:
x Unexpected token. Did you mean {'}'} or &rbrace;?
,-[/vercel/path0/app/update-prompt/page.jsx:63:1]

Can someone help me in adding the Suspense tags in the above code. Thanks in Advance!

Why Webview2 set value of an input element but value desapears after submiting the form as never had been set?

I’m calling ExecuteScriptAsync and pass a script that find an input element and set its value. After I submit the form, the site behaves like there isn’t any text in the input. Clicking in the submit button, the text desapears. Clicking into the input element, same occurs. See the code below.

await webView.CoreWebView2.ExecuteScriptAsync("var obj = document.evaluate("//descendant::input[@placeholder='Type the code']", document,  null,  XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue; if (obj != undefined && obj != null) {obj.value='AP37060';}");

The text is changed, but it seems as nothing is there. Can somebody help me? Thanks.