Dynamic routing of next js

I have make a website using next js and it contain dynamic routing which is working perfecting on localhost but I have uploaded on godaddy and vercel on both routes work but dynamic routes [id] like this not working on live server how to solve it. Is there any configrations for it??

I am expecting solutions of it

I can’t make Javascript code work in WPCode in any way

I have a WordPress website where I’m trying to add this small Javascript code which all it have to do is move an image left and right when the user scrolls the page with the mousewheel:

let didScroll = false;
let paralaxTitles = document.querySelectorAll(".challenger");

const scrollInProgress = () => {
didScroll = true
}

const raf = () => {
if(didScroll) {
paralaxTitles.forEach((element, index) => {
element.style.transform = "translateX("+ window.scrollY / 10 + "%)"
})
didScroll = false;
}
requestAnimationFrame(raf);
}

requestAnimationFrame(raf);
window.addEventListener('scroll', scrollInProgress)

The script works fine if I add it between a <script> tag directly inside a custom HTML widget (yea I know is bad practice, I just used it for testing) and as soon as I am inside the Elementor editor it works the way it should.

I’ve seen online that in order to add JS on WordPress I need to use WPCode, and here’s the issue: I can’t understand why but no matter what I do, no matter if I insert the script in header, footer, or body, no matter if I use Global Script or Code Snippet, the script doesn’t work in any way and I can’t really figure out what I’m doing wrong…

Here’s the whole code that as I previously mentioned works in Elementor editor:

HTML + JS

<script>
let didScroll = false;
let paralaxTitles = document.querySelectorAll('.challenger');

const scrollInProgress = () => {
  didScroll = true
}

const raf = () => {
  if(didScroll) {
    paralaxTitles.forEach((element, index) => {
      element.style.transform = "translateX("+ window.scrollY / 10 + "%)"
    })
    didScroll = false;
  }
  requestAnimationFrame(raf);
}


requestAnimationFrame(raf);
window.addEventListener('scroll', scrollInProgress)
</script>

<div class="track_big">
    <div class="challenger">
        <img src="../wp-content/uploads/2023/09/chall_divisory.png">
    </div>
</div>

CSS:

.track_big {
    position:relative;
    background-image: url("../wp-content/uploads/2023/09/track2.png");
    background-repeat: repeat-x;
    height: 9px;
    margin-top: 85px;
}

.challenger {
    position: absolute;
    bottom: 0px;
    width: 3325px;
    z-index: 11;
    right: 150%;
}

Any help will be greatly appreciated.

How to replace date picker in ckan?

I’m currently working with ckan 2.10 and also I install ckanext-scheming extension. When we add a metadata field with date preset, it shows a date picker which is not a part of scheming extension and it is set by the ckan itself. I need to change this date picker to another one. How can I do that and where should I look?

Inject javaScript inline code into header or before closing body tag section

I would like to inject a script into one of the 3 page sections (Head, Bottom or DropedPosition)

I achieved this using the Html.Script helper when the script type use the reference.
The problem is to render a script that is coming as a string and inject it in one of these sections anyway. The else statement is the part that its not working and I have no idea it it can be achievable from the partial view. Here is what I have:

@if (scriptType == "reference")
    {
        if (position == "Head")
        {        
            Html.Script(fileUrl, "head");
        }
        if (position == "DropedPosition")
        {        
            <text>
                <script src="@fileUrl" type="text/javascript"></script>
            </text>
        }
        if (position == "BeforeClosingBodyTag")
        {
            Html.Script(fileUrl, "bottom");
        }
    }
    else // script type is inLine
    {
        if (position == "Head")
        {
            Html.Script(inlineCode, "head");
        }
        if (position == "DropedPosition")
        {
            <text>
                <script type="text/javascript">               
                   @Html.Raw(inlineCode)
                </script>
            </text>
        }
        if (position == "BeforeClosingBodyTag")
        {        
            Html.Script(inlineCode, "bottom");
        }
    }

Creating a global variable inside my module to be used in the index.html, with ViteJS

I have a TS based / ViteJS project that build a small library.

I’d like to expose one of my object to the global window (or equivalent), to be used outside of my modules, after the library has been builded.

Here is a simplified exemple, I want to use my Test() function directly in my HTML page :

index.html (root of my project)

<!DOCTYPE html>
<html>
  <head>
  </head>
  <body>
    <script type="module" src="/src/main.ts"></script>
    <script>

      console.log("Hello vite...");
      Test();

    </script>

  </body>
</html>

src/main.ts

console.log("Hello from main.ts");

function Test(){
  console.log("Hello TEST !");
}

window.Test = Test;

the builded dist/index.html (no error during the build)

<!DOCTYPE html>
<html lang="en">
  <head>
    <script type="module" crossorigin src="/assets/index-3ba57d45.js"></script>
  </head>
  <body>
    
    <script>

      console.log("Hello vite...");
      Test();

    </script>

  </body>
</html>

When I run the dist/index.html in the browser (from a local server), “Test” is not defined

Hello vite...
ERROR: Uncaught ReferenceError: Test is not defined
Hello from main.ts

How can I use my Test() on my index.html scripts ?

Thanks!

is it posible to make part of a div transparant with the margin of another div?

I am making a website with css, html and js.

I have created a circular div with a margin and i have a div that is partly inside the margin with postition absolute and i want to make the part that is inside the margin to be transparant

i made a illustartion so you can vissualise it
The image

black is the vissible part of the circle div

purple is the margin for the circle div

red is the div i want to be partly transparant

i have made most of the graphics in css but the bg is a picture that i want to still be visible

here is the code
html:

<!DOCTYPE html>

<meta charset="UTF-8">

<head>
    <link rel="stylesheet" href="socialsStyle.css">
    <script src="socialsScript.js"></script>
</head>
<body>
    
    <input type="checkbox" value="socialsLinks" onclick="addDay()" id="XD">
        <div id="circle">SOCIALS!</div>

        <div class="socialsLinks" id="twitter">twitter</div>

        <div class="socialsLinks" id="idk">idk</div>

        <div class="socialsLinks" id="kommmerSnart">idk</div>
        
        <div class="socialsLinks" id="vetInte">idk</div>


</body>

</html>

css:

html{
    height: 100%;
}

@font-face {
    font-family: 'allerbold';
    src: url('aller_bd-webfont.woff2') format('woff2'),
         url('aller_bd-webfont.woff') format('woff');
    font-weight: normal;
    font-style: normal;
}

body{
    height: 100%;
    width: 100%;
    background-image: linear-gradient(rgba(0, 0, 0, 0.8),rgba(0, 0, 0, 0.1)) , url('356357.jpg');
    background-repeat: no-repeat;
    background-size: cover;
}

#circle{
    z-index: 100;
    display: flex;
    height: 66vh;
    width: 66vh;
    border-radius: 50%;
    background-color: #E867A0;
    outline: solid white 6vh;
    font-family: 'allerbold', serif;
    justify-content: center;
    align-items: center;
    color: white;
    font-size: 13vh;
    user-select: none;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    transition: transform 200ms;
    margin: 2vh;
}

input{
    display: flex;
    z-index: 999;
    opacity: 1;
    height: 78vh;
    width: 78vh;
    border-radius: 50%;
    user-select: none;
    border: 1px solid #ff0000;
    appearance: none;
    -webkit-appearance: none;
    outline: none;
    position: absolute;
    top: 49.6%;
    left: 49.8%;
    transform: translate(-50%, -50%);
    transition: transform 200ms;
}

input:checked + #circle{
    transform: translate(-31vw, -50%);
}

input:checked{
    transform: translate(-34vw, -50%);
}

.socialsLinks{
    background-color: #E867A0;
    z-index: 98;
    opacity: 0;
    height: 12vh;
    width: 33vw;
    margin: 2vh;
    position: relative;
    font-family: 'allerbold', serif;
    text-align: center;
    font-size: 8vh;
    color: white;
    justify-content: center;
    align-items: center;
    display: grid;
    justify-self: center;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -230%);
    user-select: none;
    transition: all 150ms;
}

js:

let clicks = 1;

function addDay() {
    const links = document.querySelectorAll('.socialsLinks');
    
if (clicks === 1){
    for (const bil of links) {
        bil.style.opacity = "1";
        bil.style.transform = "translate(0%, -235%)"
    }
    clicks += 1;

} else if (clicks >= 2){
    for (const bil of links){
        bil.style.opacity = "0";
        bil.style.transform = "translate(-50%, -235%)"
    }
    clicks -= 1;
}

  }

  var element = document.getElementById('circle');
  var style = getComputedStyle(element)

  console.log(style);     

if you have another better way of doing this plz recomend it to me 🙂

thank you for any help!

i have tried css mask even though i might just have feild to understand how to use it. i have also tried to find ways of doing it in js bygeting the size of the margin and trying to set the opacity for the divs inside to 0

Token refresh mechanism javascript

My application relies completely on API calls to Spotify.

Since it is client-side only it would not be safe for me to use the refresh token logic that Spotify suggests and therefore I am trying to implement a different mechanism, that consists in making the handleAuthorization call every time the token is about to expire, so that the user gets re-authenticated and gets a new token.

import React, { useEffect, useState } from 'react';
import { Route, Routes} from 'react-router-dom';
import LandingPage from './components/LandingPage';
import UserDashboard from './components/UserDashboard';
import PlaylistPage from './components/PlaylistPage';
import ConnectionError from './components/ConnectionError';
import 'react-notifications/lib/notifications.css';
import axios from 'axios';

function App() {
  const [token, setToken] = useState('');
  const [profile, setProfile] = useState({});
  const [playlists, setPlaylists] = useState([]);
  const [isOnline, setIsOnline] = useState(true);


  useEffect(() => {
    const handleOnlineStatusChange = () => {
      setIsOnline(window.navigator.onLine);
    };
  
    window.addEventListener('online', handleOnlineStatusChange);
    window.addEventListener('offline', handleOnlineStatusChange);
  
    return () => {
      window.removeEventListener('online', handleOnlineStatusChange);
      window.removeEventListener('offline', handleOnlineStatusChange);
    };
  }, []);
  


  
    const handleAuthorization = () => {
      const clientId = 'my-client-id';
      const redirectUri = 'http://localhost:3000';
      const scopes = ['user-library-read', 'playlist-read-private', 'playlist-modify-private', 'playlist-modify-public', 'playlist-read-collaborative'];
      const authorizationURL = `https://accounts.spotify.com/authorize?client_id=${clientId}&response_type=token&redirect_uri=${encodeURIComponent(
        redirectUri
      )}&scope=${scopes.join('%20')}`;
    
      // Redirect for authorization
      window.location.href = authorizationURL;
    };

    const fetchData = async () => {
      const hash = window.location.hash;
      const tokenParam = new URLSearchParams(hash.substring(1)).get('access_token');
  
      if (tokenParam) {
        // Token is present in the URL
        const newToken = tokenParam;
        window.localStorage.setItem('token', newToken);
        setToken(newToken);
  
        // Redirect to the dashboard
        window.location.href = '/dashboard';
      } else {
        // Token is not present in the URL, handle token expiration or other logic here
        const storedToken = window.localStorage.getItem('token');
  
        if (storedToken) {
          // Token is stored locally, you can set it and perform necessary actions
          setToken(storedToken);
  
          // Fetch user data and playlists here
          try {
            const response = await axios.get('https://api.spotify.com/v1/me', {
              headers: {
                Authorization: `Bearer ${storedToken}`,
              },
            });
  
            const { data } = response;
            setProfile(data);
  
            // Fetch playlists
            try {
              const playlistsResponse = await axios.get('https://api.spotify.com/v1/me/playlists', {
                headers: {
                  Authorization: `Bearer ${storedToken}`,
                },
                params: {
                  limit: 50,
                },
              });
  
              const { data: playlistsData } = playlistsResponse;
              setPlaylists(playlistsData.items);
              console.log(playlistsData.items);
            } catch (error) {
              console.error('Error fetching playlists:', error);
            }
          } catch (error) {
            console.error('Error fetching user data:', error);
          }
        }
      }
    };

    const checkTokenExpiration = () => {
      const storedToken = window.localStorage.getItem('token');
  
      if (storedToken) {
        const tokenData = JSON.parse(atob(storedToken.split('.')[1])); // Decode JWT payload
  
        // Calculate the remaining time before token expiration (in seconds)
        const currentTime = Math.floor(Date.now() / 1000);
        const expirationTime = tokenData.exp;
        const timeToExpiration = expirationTime - currentTime;
  
        // Set a threshold (e.g., 300 seconds) for when to refresh the token
        const tokenRefreshThreshold = 300;
  
        if (timeToExpiration <= tokenRefreshThreshold) {
          // Token is about to expire, refresh it
          handleAuthorization();
        }
      }
    };
  
    useEffect(() => {
      // Check token expiration every minute
      const tokenExpirationCheckInterval = setInterval(() => {
        checkTokenExpiration();
        fetchData();
      }, 60000); // 60 seconds
  
      return () => {
        clearInterval(tokenExpirationCheckInterval);
      };
    }, []);
    


 
  const logout = () => {
    setToken('');
    setProfile({});
    setPlaylists([]);
    window.localStorage.removeItem('token');
    // Redirect the user to the home page after logging out
    window.location.assign('http://localhost:3000');
  };




  return (
    <div>
    {isOnline ? (
      <Routes>
        <Route path="/" element={<LandingPage handleAuthorization={handleAuthorization} />} />
        <Route path="/dashboard" element={<UserDashboard profile={profile} playlists={playlists} logout={logout} />} />
        <Route path="/playlist/:id" element={<PlaylistPage />} />
      </Routes>
    ) : (
      <ConnectionError />
    )}
  </div>
  );
}

export default App;

for debugging reasons, i’ve set the timer to call the function every minute, but the code does not work and I get this error: “Uncaught DOMException: Failed to execute ‘querySelector’ on ‘Document'”. How could I fix this?

array as value of linkedHashMap: Increment at a key

I have a problem using linkedHashMap. I have a Map built like this:

int v={0,0,0,0};
COD_OUT.put("A",0);
COD_OUT.put("V",0);
COD_OUT.put("R",0);
COD_OUT.put("G",0);

I have agents who are assigned a parameter p1 (“A”,”V”,”R”,”G”) via distribution.
Each agent is assigned a second integer p2 parameter between 0 and 3.

What I want to get is the increment of the vector by one unit at the position indicated by parameter p2 at the key of parameter p1.
I wrote:

int v[]=COUNT_OUT.get(agent.p1);
v[agent.p2]++;
COUNT_OUT.replace(agent.p1,COUNT_OUT.get(agent.p1),v);

What I get is an increment in the position of the parameter p1, but for all keys and not for that of parameter p2. How can I get the increment only for the p2 key?

export to excel in react js from api

I am having problems when I want to export data to Excel with a custom table

The number of bab corresponds to the data in the bab array and the number of children in the bab also depends on the number of arrays in the type

const data = [
    {
      student: [
        {
          studentId: 1,
          name: "jhon",
        },
        {
          studentId: 2,
          name: "kelvin",
        },
        {
          studentId: 3,
          name: "bagas",
        },
      ],
      data: {
        teacher_name: "guru baik",
        teacher_id: "02",
        class_name: "X 1",
        class_id: "cls01",
        subject_id: "sbj01",
        subject_name: "bahasa indonesia",
      },
      bab: [
        {
          name: "bab 1",
          bab_name: "Keterampilan",
          type: [
            {
              name: "harian 1",
              materi: "materi 1",
              materi_prosem: "materi prosem 1",
              nilai: [
                { id: "aaa", studentId: 3, value: 100 },
                { id: "bbb", studentId: 2, value: 90 },
                { id: "ccc", studentId: 1, value: 79 },
              ],
            },
            {
              name: "harian 2",
              materi: "materi 2",
              materi_prosem: "materi prosem 2",
              nilai: [
                { id: "ddd", studentId: 1, value: 22 },
                { id: "eee", studentId: 2, value: 88 },
                { id: "fff", studentId: 3, value: 45 },
              ],
            },
          ],
        },
        {
          name: "bab 2",
          bab_name: "Toleransi",
          type: [
            {
              name: "harian 1",
              materi: "materi 1",
              materi_prosem: "materi prosem 1",
              nilai: [
                { id: "ggg", studentId: 1, value: 77 },
                { id: "hhh", studentId: 2, value: 99 },
                { id: "iii", studentId: 3, value: 46 },
              ],
            },
            {
              name: "harian 2",
              materi: "materi 2",
              materi_prosem: "materi prosem 2",
              nilai: [
                { id: "jjj", studentId: 1, value: 21 },
                { id: "kkk", studentId: 2, value: 23 },
                { id: "lll", studentId: 3, value: 47 },
              ],
            },
            {
              name: "harian 3",
              materi: "materi 3",
              materi_prosem: "materi prosem 3",
              nilai: [
                { id: "mmm", studentId: 1, value: 43 },
                { id: "nnn", studentId: 3, value: 44 },
                { id: "ooo", studentId: 2, value: 71 },
              ],
            },
          ],
        },
      ],
    },
  ];

Can the data variables be exported to Excel, then the export results are as shown in the picture. and how to do it?

the display in excel that I expected

How to get the height of several containers with the same class

I’m currently trying to find out and access the height of several div containers that have the same class “content”.

My HTML code Looks like this:

 <div class = “main”>
        <div class="item">
          <div class = “content”>
            <p></p>
          </div>
        </div>   
        <div class="item">
          <div class = “content”>
            <p></p>
          </div>
        </div>
        <div class="item">
          <div class = “content”>
            <p></p>
          </div>
        </div>
   </div>

My JavaScript looks like this:

let allContents = document.querySelectorAll(".content");

let allItems = document.querySelectorAll(”.item”);

let heightOfContents = allContents.offsetHeight;

Unfortunately I have no success with this.

I also tried the following:

let heightOfContents = document.querySelector(".content").getBoundingClientRect().height;

which didn’t work either.

I am expecting to get on the console the heigt of each container and to use them for further calculations.

Would any of you have an idea how this could work?

Thanks in advance for the help.

Looking for a way to get the first 30 seconds of audio from a video file in Javascript

I’m trying to figure out a way to get an audio file of the first 30 seconds of a video file using Javascript within the context of a browser extension.

I’ve essentially already done this taking the video file, using FileReader > readAsArrayBuffer to get an ArrayBuffer, then AudioContext.decodeAudioData to get an AudioBuffer, and then this method to slice the audio buffer.

However, I’ve found that AudioContext.decodeAudioData causes the Chrome tab to crash completely when the video is very long (several hours), so this approach might not be feasible.

I’ve been trying to find a way to instead slice the video file to the first 30 seconds, and then convert it to audio rather than convert the entire video file to audio first to get around the decodeAudioData issue. I also noticed there’s some upper limit on file size with readAsArrayBuffer that I’d like to get around.

Of course, if there’s any other possible solution outside of what I’ve described, I’d love to hear it. I’ve naturally come across ffmpeg often in my search, but I cannot seem to get the web assembly version to work in the context of the browser extension.

Cross-Domain Authentication and Session Sharing Between Multiple Parent Websites and a Common Child App

I have a website with a URL of (www.parent1.com), and inside this parent1 website there is an iframe. In the iframe, I’m loading a React app with a URL of (www.child.com) and login to the child app inside the iframe of the (parent1.com) website. There is another parent website with a URL of (www.parent2.com), and this site also has an iframe inside it that loads the same child app with the URL of (child.com). What I want is that if I login to the child app of (parent1.com) and if I open (parent2.com) in another tab, the child app of (parent2.com) should be logged in. Please give me your ideas on how to achieve this.

The problem I’m facing is that even though I login to the child app (child.com) in the iframe of the (parent1.com) website, And then, if I open the (parent2.com) website in another tab, the child app (child.com) in the iframe of (parent2.com) is not logged in.

react froala, how can i toolbar button icon change?

I’m using the Froala WYSIWYG editor with React. How can I change the toolbar button icon? For example, I’d like to change the icon of the “bold” button to the Font Awesome 6 FaCss3Alt icon from react-icons. Below is my current configuration for the Froala editor:

const config = {
   toolbarButtons: {
   ....
   },
   imageAllowedTypes: ["jpeg", "jpg", "png"],
   height: "434",
   width: "100%",
   quickInsertEnabled: false,
   videoInsertButtons: ["videoBack", "|", "videoByURL", "videoUpload"],
   paragraphFormat: {
     N: "Normal",
     heading1: "Heading 1",
     H2: "Heading 2",
   },
 };

How can I achieve this?