Prevent click a link if dragged

I’m trying to stop click events if dragged.

I think the simplest version of this is dragging yourself. Basically IF the user presses down, then moves, then releases I don’t want a click event.
this is the script

const tabsBox = document.querySelector('.kemem'),
  allTabs = tabsBox.querySelectorAll('.pop-post'),
  arrowIcons = document.querySelectorAll('.icon-mem svg')

let isDragging = false

const handleIcons = scrollVal => {
  let maxScrollableWidth = tabsBox.scrollWidth - tabsBox.clientWidth
  arrowIcons[0].parentElement.style.display = scrollVal <= 0 ? 'none' : 'flex'
  arrowIcons[1].parentElement.style.display =
    maxScrollableWidth - scrollVal <= 1 ? 'none' : 'flex'
}

arrowIcons.forEach(icon => {
  icon.addEventListener('click', () => {
    // if clicked icon is left, reduce 350 from tabsBox scrollLeft else add
    let scrollWidth = (tabsBox.scrollLeft += icon.id === 'left' ? -340 : 340)
    handleIcons(scrollWidth)
  })
})

allTabs.forEach(tab => {
  tab.addEventListener('click', () => {
  e.preventDefault();
  e.stopPropagation();
    tabsBox.querySelector('.active').classList.remove('active')
    tab.classList.add('active')
  })
})

const dragging = e => {
  e.preventDefault();
  e.stopPropagation();
  if (!isDragging) return
  tabsBox.classList.add('dragging')
  tabsBox.scrollLeft -= e.movementX
  handleIcons(tabsBox.scrollLeft)
}

const dragStop = () => {
  isDragging = false
  e.preventDefault();
  e.stopPropagation();
  tabsBox.classList.remove('dragging')
}

tabsBox.addEventListener('mousedown', () => (isDragging = true))
tabsBox.addEventListener('mousemove', dragging)
document.addEventListener('mouseup', dragStop)
    <div class='icon-mem lefto'><div class='overflow-left'></div><svg aria-hidden='true' class='jt-icon' id='left'><use xlink:href='#i-arrow-l'></use></svg></div>
      <ul class="kemem">
        <li class="pop-list">Programming</li>
        <li class="pop-list">HTML</li>
        <li class="pop-list">CSS</li>
        <li class="pop-list">Python</li>
      </ul>
    <div class='icon-mem righto'><div class='overflow-right'></div><svg aria-hidden='true' class='jt-icon' id='right'><use xlink:href='#i-arrow-r'></use></svg></div>

this is the demo : demo

Am I missing a simpler solution?

Integrating React Native View above Custom Native Camera in Android – Display Issue

• Created a custom camera using a native module.
• Now I have called this custom camera in my react native component
• Once I call this, the camera opens and the corresponding layout (XML file) also opens above the camera.
• I want to display react native’s view above the custom native camera screen instead of the Android’s XML layout.

I have used callback but it didn’t work
I want to display the layout for the custom Android native module using react native inside the View component.

Creating a new page after the build is done and the app is online (Next Js 13)

I have a dynamic route in NextJS 13 where I fetch the slugs from a database.
Is it possible that after the build I don’t have to rebuild the whole application if a new slug is added to the database?

I was able to update the content on a dynamic page using “export const revalidate=5”, but I am unable to add new pages even if a new slug is inserted into the database (404 error when accessing the new route).

I want the page to be created automatically after the app is online when a new slug is added.

Resolve CSP issues in angular 15

This may be the head-on. I ran DAST report for my angular(v-15) app. Found the below CSP vulnerabilities in my app.

enter image description here

angular.json

{
  "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "version": 1,
  "newProjectRoot": "projects",
  "projects": {
    "artex-ui": {
      "projectType": "application",
      "schematics": {
        "@schematics/angular:component": {
          "style": "scss"
        }
      },
      "root": "",
      "sourceRoot": "src",
      "prefix": "app",
      "architect": {
        "build": {
          "builder": "@angular-devkit/build-angular:browser",
          "options": {
            "outputPath": "../dist/artex-ui",
            "index": "src/index.html",
            "main": "src/main.ts",
            "baseHref": "/artex/",
            "polyfills": [
              "zone.js"
            ],
            "tsConfig": "tsconfig.app.json",
            "inlineStyleLanguage": "scss",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          },
          "configurations": {
            "production": {
              "budgets": [
                {
                  "type": "initial",
                  "maximumWarning": "4mb",
                  "maximumError": "8mb"
                },
                {
                  "type": "anyComponentStyle",
                  "maximumWarning": "4kb",
                  "maximumError": "10kb"
                }
              ],
              "outputHashing": "all"
            },
            "development": {
              "buildOptimizer": false,
              "optimization": false,
              "vendorChunk": true,
              "extractLicenses": false,
              "sourceMap": true,
              "namedChunks": true
            }
          },
          "defaultConfiguration": "production"
        },
        "serve": {
          "builder": "@angular-devkit/build-angular:dev-server",
          "configurations": {
            "production": {
              "browserTarget": "artex-ui:build:production"
            },
            "development": {
              "browserTarget": "artex-ui:build:development"
            }
          },
          "defaultConfiguration": "development"
        },
        "extract-i18n": {
          "builder": "@angular-devkit/build-angular:extract-i18n",
          "options": {
            "browserTarget": "artex-ui:build"
          }
        },
        "test": {
          "builder": "@angular-devkit/build-angular:karma",
          "options": {
            "polyfills": [
              "zone.js",
              "zone.js/testing"
            ],
            "tsConfig": "tsconfig.spec.json",
            "karmaConfig": "karma.conf.js",
            "inlineStyleLanguage": "scss",
            "main": "src/test.ts",
            "assets": [
              "src/favicon.ico",
              "src/assets"
            ],
            "styles": [
              "src/styles.scss"
            ],
            "scripts": []
          }
        }
      }
    }
  },
  "cli": {
    "analytics": "5f9fd60f-a143-4804-b22f-f76b8ef82330"
  }
}

package.json

{
  "name": "artex-api",
  "version": "2.0.0",
  "description": "For artex-api folder",
  "main": "app.js",
  "scripts": {
    "ng": "ng",
    "server-start": "node ../dist/artex-api/app.js",
    "prod-build": "ng build --configuration production --watch --prod --aot --base-href /artex/",
    "dev-build": "ng build --watch --aot --base-href /artex/",
    "local-build": "ng build --watch --aot --base-href /artex/",
    "dev-start": "start npm run dev-build && start npm run server-start",
    "prod-start": "start npm run prod-build && start npm run server-start",
    "local-start": "start npm run local-build && start npm run server-start",
    "ng:bump-version:dev": "gulp ng-bump-version --configuration=dev",
    "build": "ng build --configuration production --base-href /artex/",
    "test": "ng testng test --code-coverage",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "format:lint": "prettier -l "src/**/*.{ts,json,less,html}"",
    "format:fix": "prettier --write "src/**/*.{ts,json,less,html}"",
    "preinstall": "npx force-resolutions",
    "postinstall": "ngcc --properties es2015 browser module main --first-only --create-ivy-entry-points",
    "sonar": "sonar-scanner"
  },
  "engines": {
    "node": "16.x"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "@angular-material-components/datetime-picker": "^16.0.1",
    "@angular-material-components/moment-adapter": "^16.0.1",
    "@angular/animations": "^15.2.7",
    "@angular/cdk": "^15.2.7",
    "@angular/common": "^15.0.0",
    "@angular/compiler": "^15.0.0",
    "@angular/core": "^15.0.0",
    "@angular/forms": "^15.0.0",
    "@angular/material": "^15.2.7",
    "@angular/material-moment-adapter": "^16.1.7",
    "@angular/platform-browser": "^15.0.0",
    "@angular/platform-browser-dynamic": "^15.0.0",
    "@angular/router": "^15.0.0",
    "@fortawesome/angular-fontawesome": "^0.12.1",
    "@okta/okta-angular": "6.1",
    "@okta/okta-auth-js": "7.2",
    "ag-grid-angular": "^28.2.0",
    "ag-grid-community": "^28.2.0",
    "ag-grid-enterprise": "^28.2.0",
    "bn-ng-idle": "^2.0.5",
    "bootstrap": "^5.2.3",
    "express": "^4.18.2",
    "karma-coverage-istanbul-reporter": "^3.0.3",
    "karma-junit-reporter": "^2.0.1",
    "karma-sonarqube-reporter": "^1.4.0",
    "lodash": "^4.17.21",
    "mat-select-autocomplete": "^1.3.0",
    "ngx-cookie-service": "^16.0.1",
    "ngx-mat-select-search": "^7.0.5",
    "ngx-ui-loader": "^13.0.0",
    "puppeteer": "^20.7.3",
    "rxjs": "~7.5.0",
    "tslib": "^2.3.0",
    "zone.js": "~0.12.0"
  },
  "devDependencies": {
    "@angular-devkit/build-angular": "^15.0.3",
    "@angular/cli": "~15.0.3",
    "@angular/compiler-cli": "^15.0.0",
    "@types/jasmine": "~4.3.0",
    "@types/lodash": "^4.14.195",
    "jasmine-core": "~4.5.0",
    "jasmine-spec-reporter": "~5.0.0",
    "karma": "~6.4.0",
    "karma-chrome-launcher": "~3.1.0",
    "karma-coverage": "~2.2.0",
    "karma-coverage-istanbul-reporter": "~3.0.3",
    "karma-jasmine": "~5.1.0",
    "karma-jasmine-html-reporter": "~2.0.0",
    "karma-junit-reporter": "^2.0.1",
    "karma-sonarqube-reporter": "^1.4.0",
    "sonar-scanner": "^3.1.0",
    "typescript": "~4.8.2"
  }
}

index.html

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Artex</title>
  <base href="/">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="icon" type="image/x-icon" href="assets/images/artex.png">
  <link rel="preload" as="style" onload="this.rel = 'stylesheet'" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" />
  <link rel="preload" as="style" onload="this.rel = 'stylesheet'" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <script type="text/javascript" src="https://unpkg.com/default-passive-events"></script>  
</head>
<body>
  <app-root></app-root>
</body>
</html>

Solutions tried so far:

  1. Tried to add some CSP properties in angular.json. But after adding not able to run. Getting this error.

    Error: Schema validation failed with the following errors:
    Data path "" must NOT have additional properties(csp).
    
  2. Added these meta tags. app crashed(i,e not rendered other 3rd party libraries).

2.1

   <meta http-equiv="Content-Security-Policy" content=" default-src 'self'; script-src 
    'self' https://unpkg.com; style-src 'self' https://fonts.googleapis.com; font-src 
     https://fonts.gstatic.com;">

2.2

    <meta http-equiv="Content-Security-Policy" content="style-src 'self'*.artex.com; 
    script- src  'self'*.artex.com;">
  

2.3

    <meta http-equiv="Content-Security-Policy" content="default-src 'self'; style-src 
   'self' 'unsafe-inline'">

Paste to div, without accepting text input

My question is in some ways similar to this post, that post seems very limited compared to what I want to do. I am playing with an idea of having a div that mimics the content editable but better. A user would be able to add text with various formats, styles, fonts, etc. Even including images, videos, and so on. Its nothing more than an idea (so don’t judge it too heavy on its practicality).

In short I have a div that looks like this

        <div tabindex="0" id="canvas">       
          <i id="canvas-cursor">&nbsp</i>
        </div>

the javascript has this

let canvas = document.getElementById("canvas");
let cursor = document.getElementById("canvas-cursor"); 

canvas.addEventListener("keydown", editText);

const removeAttributes = (element) => {
  for (let i = 0; i < element.attributes.length; i++) {
    element.removeAttribute(element.attributes[i].name);
  }
};
function editText(event) {  
  event.preventDefault;
  const keyName = event.key;
  
  if (keyName === "Control") {
    console.log(`Control key ${keyName}`);
    return;
  } 

  if (event.ctrlKey) {
    console.log(`Combination of ctrlKey ${keyName}`);
  } else {

    let newElement = document.createElement("span");
    newElement.setAttribute("class", "canvas-child");
    
    switch (keyName){
    case " ":
      newElement.innerHTML = "&nbsp"; 
      break;
    case "ArrowLeft":
      return;
    case "ArrowRight":
      return;
    case "Backspace":
      var deleted = canvas.removeChild(cursor.previousElementSibling);
      removeAttributes(deleted);
      return;
    case "ArrowUp":
      return; 
    case "ArrowDown":
      return
    case "Enter":
      newElement.innerText += "n"
      break;
    case "Shift": 
    case "Alt":
      console.log("Alt button is pressed.");
    case "Tab":
    case "Meta":
    case "CapsLock":
      return;
 
    default:
      newElement.innerText += keyName
      break;        
    }
    
    newElement.addEventListener("mouseenter", (event)=> {
      // newElement.style.background = "green";
    });

    newElement.addEventListener("mouseleave", (event)=> {
      newElement.style.background = "none";
    });

    newElement.addEventListener("dblclick", (event) => {
      console.log("On click event: " + event
                  + "nsource: " + newElement);
      canvas.insertBefore(cursor, newElement);
    });

    canvas.insertBefore(newElement, cursor); 
  }
}

and css

#canvas-cursor {
    background-color: red;
    animation: blinker 1s linear infinite;
}

Text navigation and font style/formatting has been remove for simplicity, but that works fine; the user can choose code style, underline, bold, font-style, hightlight, etc.

the next two events I want to deal with are copy and paste. I know that I can easily enable that functionality if i add the contenteditable="true" attribute, however, this will also take keyboard inputs and fill the div with text; which means that everything the user types will be repeated; i don’t want this, since I already am taking care of that. I only care to capture the paste event and handle it according to my whims. Is there a way to do this?

thanks in advance.

Google map offline in PWA angular application

I am creating a PWA application with offline capabilities and I want to implement google map in it. Currently I am using “@angular/google-maps” package for google map implementation.

So is it possible to use this google map as offline ?

Or is there any better method available for implementing google map with offline capability ?

Store a simple int variable to a server on github pages

I have created an html file with an int variable that is uploaded to GitHub pages.

When the user clicks a button, the int value is changed by += 1, and the value is displayed with <p> </p>.

I am a beginner and want to save the int value to some sort of free server or database so the int variable stays the same across all users. How can I achieve this?

Same Error and I have tried all possible fixes, Insufficient Funds gas * price + value

So, I’m constantly facing this error and there aren’t much about it except what I already fathom but is not the case, see, I have sufficient balance for gas, and for the eth value to transfer; I kept it 0, but the transaction is still not broadcasting.

To the people who’re thinking what I’m trying to do: I’m actually trying to send unconfirmed transactions of unavialble funds(flasg eth) through eth network(I know there are validity check that I have to bypass, which I will do later, but I’m already stuck in just only broadcasting a legitimate transaction!

const { ethers } = require("ethers");

async function sendTransaction() {
    const ethereumNodeUrl = 'https://mainnet.infura.io/v3/085077982f094073a03893b9e3e338ec';

    const provider = new ethers.providers.JsonRpcProvider(ethereumNodeUrl);

    const senderAddress = '0x0112fa4CB650dCa6eE0f9Bd74106EbB27C382622';
    const recipientAddress = '0xA705f5c1dEb081D329EdD2d2ED6817f161Cfd1F0';

    const privateKey = 'MY_PVT_KEY'; 

    try {
        const wallet = new ethers.Wallet(privateKey, provider);

        const tx = {
            to: recipientAddress,
            value: ethers.utils.parseEther('0'), // Set the value to 0.1 ETH (100 ether in wei)
            gasLimit: ethers.utils.hexlify(21000), // Adjust gas limit accordingly
            gasPrice: ethers.utils.parseUnits('25', 'gwei'), // Adjust gas price accordingly
        };

        // Create and broadcast the transaction
        const txResponse = await wallet.sendTransaction(tx);
        console.log(`Transaction hash: ${txResponse.hash}`);
    } catch (error) {
        console.error('Error:', error);
    }
}

sendTransaction();

Getting Internal error encountered when running Google APP script using GoogleAPI npm library

I have a Google app script that takes a DOC ID as input and converts it into a PDF using the below code:

 var pdfFile = DriveApp.createFile(doc.getBlob().getAs('application/pdf'));

Now I am running the above-mentioned Google APP script from a node js server using googleapis npm library and I am executing in the below way


     try {
        const request = {
          scriptId: SCRIPT_ID,
          resource: {
            function: 'exportDocToPDFAndSaveToDrive', 
          },
          auth: client,
        };
        const response = await script.scripts.run(request);
        console.log(response.data);
      } catch (err) {
        console.log("Error in executing a google app's script", JSON.stringify(err));
      }

Now when running the the above code from a NODE JS Server I am getting the below error
[{"message": "Internal error encountered.","domain": "global", "reason": "backendError"}]}
I am performing authentication using a service account and I shared the script with the service account email.
I linked the Google App script and GCP project of that service account in Project settings section of Google Apps script.
What could be the reason for this issue and in API’s and Services of the GCP project I enabled Google App script API.
i am using below scopes during authorisation

  'https://www.googleapis.com/auth/drive',
  'https://www.googleapis.com/auth/drive.file',
  'https://www.googleapis.com/auth/spreadsheets',
  'https://www.googleapis.com/auth/documents',
  'https://www.googleapis.com/auth/documents.readonly',
  'https://www.googleapis.com/auth/drive.readonly',
  'https://www.googleapis.com/auth/script.external_request',

Please help me with above query

How to handle firebase and webrtc tasks in a client side component in next js 13

I have create a next js 13 app to share the camera feed with webrtc and firestore. This is my page.tsx. i cant make this serve side becaus i have use react hooks and i cant move this to client side because it contains firestore and server data.

"use client";

import { useEffect, useRef, useState } from "react";
import { firestore } from "@/services/_configs/firestore";

export default function Page({ params }: { params: { userid: string } }) {

    const servers = {
        iceServers: [
            {
                urls: ['stun:stun1.l.google.com:19302',
                    'stun:stun2.l.google.com:19302']
            }
        ],
        iceCandidatePoolSize: 10,
    }

    const pc = new RTCPeerConnection(servers);

    const [viewerId, setViewerId] = useState('');

    const [localStream, setLocalStream] = useState<MediaStream | null>(null);
    const [remoteStream, setRemoteStream] = useState<MediaStream | null>(null);

    const localVideo = useRef<HTMLVideoElement | null>(null);
    const remoteVideo = useRef<HTMLVideoElement | null>(null);

    useEffect(() => {
        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then((currentStream) => {
                setLocalStream(currentStream);
            });
        setRemoteStream(new MediaStream());

        localStream?.getTracks().forEach((track) => {
            pc.addTrack(track, localStream);
        })

        pc.ontrack = event => {
            event.streams[0].getTracks().forEach((track) => {
                remoteStream?.addTrack(track);
            });
        }

        if (localVideo.current != null && remoteVideo.current != null) {
            localVideo.current.srcObject = localStream;
            remoteVideo.current.srcObject = remoteStream;
        }


    }, []);


    const requestLiveStream = async () => {

        const callDoc = firestore.collection('calls').doc();
        const offerCandidate = callDoc.collection('offerCandidates');
        const answerCandidate = callDoc.collection('answerCandidates');

        setViewerId(callDoc.id);

        pc.onicecandidate = event => {
            event.candidate && offerCandidate.add(event.candidate.toJSON());
        }

        const offerDescription = await pc.createOffer();
        await pc.setLocalDescription(offerDescription);

        const offer = {
            sdp: offerDescription.sdp,
            type: offerDescription.type,
        }

        await callDoc.set({ offer });

        callDoc.onSnapshot((snapshot) => {
            const data = snapshot.data();
            if (!pc.currentLocalDescription && data?.answer) {
                const answerDescription = new RTCSessionDescription(data.answer);
                pc.setRemoteDescription(answerDescription);
            }
        })

        answerCandidate.onSnapshot((snapshot) => {
            snapshot.docChanges().forEach((change) => {
                if (change.type === "added") {
                    const candidate = new RTCIceCandidate(change.doc.data());
                    pc.addIceCandidate(candidate);
                }
            })
        });
    }


    const startLiveStream = async () => {
        const callId = viewerId;
        const callDoc = firestore.collection('calls').doc(callId);
        const offerCandidate = callDoc.collection('offerCandidates');
        const answerCandidate = callDoc.collection('answerCandidates');

        pc.onicecandidate = event => {
            event.candidate && answerCandidate.add(event.candidate.toJSON());
        }

        const callData = (await callDoc.get()).data();

        const offerDescription = callData?.offer;
        await pc.setRemoteDescription(new RTCSessionDescription(offerDescription));

        const answerDescription = await pc.createAnswer();
        await pc.setLocalDescription(answerDescription);

        const answer = {
            sdp: answerDescription.sdp,
            type: answerDescription.type,
        }

        await callDoc.update({ answer });

        offerCandidate.onSnapshot((snapshot) => {
            snapshot.docChanges().forEach((change) => {
                console.log(change);
                if (change.type === "added") {
                    let data = change.doc.data();
                    pc.addIceCandidate(new RTCIceCandidate(data));
                }
            })
        });

    }



    return (
        <div>
            <h1>{viewerId}</h1>
            <input
                type="text"
                value={viewerId}
                onChange={(e) => setViewerId(e.target.value)}
            />
            <button onClick={requestLiveStream}>view live</button>

            <button onClick={startLiveStream}>Answer live</button>
            <video playsInline ref={remoteVideo} autoPlay />
            <br />
            <video playsInline ref={localVideo} autoPlay />
        </div>
    );
}

i get this error how do i solve that.

Module not found: Can't resolve 'net'

https://nextjs.org/docs/messages/module-not-found

Import trace for requested module:
./node_modules/request/request.js

./node_modules/request/index.js

./node_modules/retry-request/index.js

./node_modules/google-gax/build/src/streamingCalls/streaming.js

./node_modules/google-gax/build/src/fallback.js

./node_modules/@google-cloud/firestore/build/src/index.js

./src/services/_configs/firestore.ts

./src/app/app/live/page.tsx

I try to separate the firestore code to another but i could not do that because i have that firestore data change events in client side.

Hi I am new to react and trying to under components

I am trying to make a header, I have created an Header.js file within an components folder which consists of this.

export default function Header() {
   return(
       <h1 className="header-title">Just Because</h1>
   );
}

I import and call my Header() in App.js

import logo from './logo.svg';
import './App.css';
import {Header} from './components/Header.js';
function App() {
  return (
    <div className="App">
      <header className="App-header">
        <Header/>
      </header>
    </div>
  );
}

export default App;

Currently I am getting this error message

createRoot(…): Target container is not a DOM element.
at createRoot (http://localhost:3000/static/js/bundle.js:31288:15)
at Object.createRoot$1 [as createRoot] (http://localhost:3000/static/js/bundle.js:31668:14)
at exports.createRoot (http://localhost:3000/static/js/bundle.js:31744:16)
at ./src/index.js (http://localhost:3000/static/js/bundle.js:222:60)
at options.factory (http://localhost:3000/static/js/bundle.js:41776:31)
at webpack_require (http://localhost:3000/static/js/bundle.js:41199:33)
at http://localhost:3000/static/js/bundle.js:42422:37
at http://localhost:3000/static/js/bundle.js:42424:12

I understand its saying that Header is not DOM (Document Object Model) but do not understand why? Initially had a error such as export ‘Header’ (imported as ‘Header’) was not found in ‘./components/Header.js’ (possible exports: default) but I found this post import error: ‘Header’ is not exported from ‘components/Header’ and I removed the “default”, but I am finding myself going around in circles. Any suggestions would be greatly appreciated

How can I get post content from WordPress API and maintain or recreate positioning?

I’ve created a Next.js app and it’s my intention to pull post data from my WordPress.com site via the public WordPress API. I’ve gotten the HTML content of my posts just fine at this endpoint:

https://public-api.wordpress.com/wp/v2/sites//posts

but aside from minimal inline styling there’s no way to recreate the structure of the original post – ie, columns, galleries, grids, blocks, etc.

I can of course apply my own CSS to adjust fonts, colors, responsiveness, etc, but don’t I need the positioning styling to make sure that the post is as the original author intended it to be? Columns in the original post, for example, are not respected because the class names that denote them in the API response don’t exist anywhere in my CSS. I could conceivably use these class names to recreate similar element positioning, but this seems like an awkward and messy approach.

I’ve tried manually adding the stylesheets from the post’s page, but still the styling from the page did not appear to match the class names from the API post content.

I expected that the API response would include some way to at least recreate the original structure of the content from the post so that my app can position the content similar to how the author did. Or is this just not possible? Thanks in advance for any help!

Elements in different routes are inaccessible in a JavaScript single page application

I have a route "/login" which has 2 input fields for email and password, and also there’s a button to click after filling up the fields, however, I have to add an event listener for the fields if there’s an Enter Keypress because I want the user to send the data by pressing enter rather than mouse click manually on the button, and I don’t want to use forms.

Now, when I add that event listener in the home page as shown below, it says element is null since it cannot see it because it still didn’t load the content of "/login" to the home page.

Any way to access those elements in different routes?

Here’s the code for the index page "/":

<!DOCTYPE html>
<html>
    <head>
        <title>Vanilla SPA Router</title>
    <meta charset="UTF-8" />
    <link rel="stylesheet" href="css/styles.css" />
    <link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet" />
</head>

<body>
    <div id="root">
        <nav id="main-nav" class="sidebar">
            <a href="/" onclick="route()">Home</a>
            <a href="/about" onclick="route()">About</a>
            <a href="/lorem" onclick="route()">Lorem</a>
            <a href="/login" onclick="route()">login</a>

        </nav>
        <div id="main-page"></div>
    </div>

<script> 
    // adding event listener here for id elements password
    var input = document.getElementById("password");

    input.addEventListener("keypress", function(event) {
       if (event.key === "Enter") {
          event.preventDefault();
          document.getElementById("login_btn").click();
       }
    }); 

// the login() will be called by login_btn, but I didn't include 
// it for this question since it's unnecessary
</script>
    <script src="router.js"></script>
</body>

The code for the login page "/login" :

<input type="email" id="email" placeholder="email" />  
<input type="password" placeholder="password" id="password" />
              
<button onClick="login()" id="login_btn" className="btn btn-primary">Login</button>

Javascript code for routing:

const route = (event) => {
    event = event || window.event;
    event.preventDefault();
    window.history.pushState({}, "", event.target.href);
    handleLocation();
};

const routes = {
    404: "/pages/404.html",
    "/": "/pages/index.html",
    "/about": "/pages/about.html",
    "/lorem": "/pages/lorem.html",
    "/login": "/pages/login.html",

};

const handleLocation = async () => {
    const path = window.location.pathname;
    const route = routes[path] || routes[404];
    const html = await fetch(route).then((data) => data.text());
    document.getElementById("main-page").innerHTML = html;
};

window.onpopstate = handleLocation;
window.route = route;

handleLocation();

Ajax doesn’t work on mobile unless using www. prefix

I have a web page that uses Ajax and it works great on the desktop using domain.com or www.domain.com.
It also works great on mobile, as long as I use the www.domain.com URL.

When accessing the naked domain from mobile everything works except the “ajax button”. I added a alert() in the onclick event and it works, but won’t go on to call the Ajax function (doesn’t even get to the function – I added an alert() in there, too, but it never fires).

I am using IIS6 and have multiple identities defined for the website (for domain.com as well as www.domain.com). They both work, but the function that calls Ajax only works (on mobile) if the www is in front.

I am retrieving a local file with the Ajax call.

I have found lots of solutions to remap naked to www, but I don’t seem to have any URL rewrite/redirect functionality, I don’t have a web.config file, etc. being on IIS6.

I would like to support either URL being entered into a browser.

When using mobile, the button just seems “dead” when using the naked domain.

Find all firestore document with spesific range

I have document in Firestore that has “from” and “to” fields.
I want to find all documents that are touching the given range
for example:

Doc 1
from: 2
to: 4

Doc 2
from: 4
to: 8

Doc 3
from: 7
to: 10

Doc 4
from: 3
to: 5

Doc 5
from: 1
to: 2

Range
from: 3
to: 6

So the result is: Doc 1, Doc 2, Doc 4

Is there any way to do this in Firestore? I’ve provided the image for better understanding

Example

I’ve tried this code

.where('from', '>=', 3)
.where('to', '<=', 6)

But the problem is, if one of the conditions is not fulfilled, then the document will not included