Pause at top and bottom continuous vertical scroll HTML

I have an embedded HTML page containing a single table of event results. I have found the code below which perfectly gives a continuous scroll, however I which to be able to pause for say 10 seconds at both the top and bottom before continuing.

How do I intercept the top and bottom and insert the pause?

Any suggestions would be much appreciated.

/*
Advanced window scroller script-
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScripts here!
*/
var currentpos=0,alt=1,curpos1=0,curpos2=-1
function initialize(){
startit()
}
function scrollwindow(){
if (document.all)
temp=document.body.scrollTop
else
temp=window.pageYOffset
if (alt==0)
alt=1
else
alt=0
if (alt==0)
curpos1=temp
else
curpos2=temp
if (curpos1!=curpos2){
if (document.all)
currentpos=document.body.scrollTop+300
else
currentpos=window.pageYOffset+1
window.scroll(0,currentpos)
}
else{
currentpos=0
window.scroll(0,currentpos)
}
}
function startit(){
setInterval("scrollwindow()",25)
}
window.onload=initialize
</script>

Can you tell me why my else condition is overwriting my if condition? [duplicate]

I’m trying to write a ‘welcome’ function that takes a parameter (‘language’) and returns a greeting in that language from the database. For example, if the user types ‘Spanish’,“Bienvenido” is returned. If the language is not in the database, ‘Welcome’ is returned.

I have done a for-in loop with an if condition of ‘greetings == language’ which produces the desired result for those languages in the database.

The problem is when I add an else condition for the ‘undefined’ languages, my else condition ends up overwriting everything.

Can anyone please tell me where I’m going wrong?

const greet = language => {
Languages = {
    english: 'Welcome',
    irish: 'Failte',
    italian: 'Benvenuto',
    latvian: 'Gaidits',
    lithuanian: 'Laukiamas',
    polish: 'Witamy',
    spanish: 'Bienvenido',         
    swedish: 'Valkommen',
    welsh: 'Croeso'    
}



for (let greetings in Languages) {
    if (greetings == language) {
     return Languages[greetings]
    }
    else {
      return 'Welcome'
    }
}
}

What I want to produce is this

console.log(greet('swedish')) // Output: 'Valkommen'
console.log(greet('welsh')) //  Output: 'Croeso'
console.log(greet('chinese')) // Output: 'Welcome' (not in the database)

But instead, I get this

console.log(greet('swedish')) // Output: 'Welcome'
console.log(greet('welsh')) //  Output: 'Welcome'
console.log(greet('chinese')) // Output: 'Welcome' 

Auth0 loginWithRedirect Adding Code and State Parameters to URL Causing isAuthenticated to Return False

When I use the loginWithRedirect function from the useAuth0 hook the redirect adds the code and state parameters to the URL. However, when these parameters are added to the URL the isAuthenticated flag from the useAuth0 hook returns false. When I remove the parameters the isAuthenticated flag from the useAuth0 hook returns true (as intended). I don’t understand why this is happening or how to avoid this issue. Is there a reason Auth0 is adding these parameters onto the URL after redirect?

If I am manipulating the DOM with vanilla JS… can I make one of those items a React component?

I’ve got an applet right now that builds a table of TODOs using vanilla JS.

Is it possible to add a React component button to one of those TODOs? Specifically trying to update the button, but React does not like you manipulating the DOM manually… so is this even doable? I thought it was possible to have React alongside other code. I’ve seen static examples such as this in their docs, but nothing dynamic like this.

e.g.

document.addEventListener('DOMContentLoaded', function () {
    fetch('/getTodos')
    .then(response => response.json())
    .then(data => {
        console.log(data)
        loadTodos(data)
    })
})

function loadTodos(data) {

    const table = document.getElementById("todos-list")

    if (data.length === 0) { return table.innerHTML = "<tr><td>Nothing to do!</td></tr>" }

    let content = ""

    data.forEach( ({id,todo,dueDate}) => {
        content += `<tr><td>${todo}</td></tr>`
        content += `<tr><td>${new Date(dueDate).toLocaleString()}</td></tr>`
        content += `<tr><td><button class="delete-btn" data-id=${id} onclick='deleteMe(${id})'>Delete</button></td></tr>`
    })

    table.innerHTML = content

}

Sort object consists of key and value by key(<-number) in JavaScript [duplicate]

I want to sort Object consists of key and value by key(<-number) in JavaScript.

const wantToSort = {
    "0.2122": "hello",
    "0.6458": "world",
    "0.4323": "javascript",
    "0.5127": "computer",
    "1234": "want",
    "1090": "sort",
    "700": "this",
    "400": "object",
    "500": "key",
    "950": "number",
    "324": "stack",
    "1433": "overflow",
    "123": "developer",
    "353": "program",
};

I want to sort this object,
I need result like,

const sortedResult = {
    "1433": "overflow",
    "1234": "want",
    "1090": "sort",
    "950": "number",
    "700": "this",
    "500": "key",
    "400": "object",
    "353": "program",
    "324": "stack",
    "123": "developer",
    "0.6458": "world",
    "0.5127": "computer",
    "0.4323": "javascript",
    "0.2122": "hello",
};

So when
console.log(sortedResult);
result is like

{
    "1433": "overflow",
    "1234": "want",
    "1090": "sort",
    "950": "number",
    "700": "this",
    "500": "key",
    "400": "object",
    "353": "program",
    "324": "stack",
    "123": "developer",
    "0.6458": "world",
    "0.5127": "computer",
    "0.4323": "javascript",
    "0.2122": "hello",
}

How can I get sorted result?

How do I combine the two json files and use their contents together? [duplicate]

How do I combine the two requested json files and work with their contents? How do I place their contents into a variable and work with them throughout the program? Assistance would be appreciated as I am stuck attempting to merge the two data files which are formatted like below. So if I wanted to combine the lapsLed key after names, raceWin, and number I would be able to without problems.

async function populate() {

    const requestURL = 'nascar.json';
    const request = new Request(requestURL);
    
    const response = await fetch(request);
    const nascarDrivers = await response.json();
    
    findDriver(nascarDrivers);

    return nascarDrivers;
}

async function texas() {

    const requestURL = 'texasMS.json';
    const request = new Request(requestURL);
    
    const response = await fetch(request);
    const texasLaps = await response.json();
    
    findLaps(texasLaps);

    return texasLaps;
}
{
    
    "season" : 2022,
    "sport" : "Nascar",
    "drivers" : [
      {
        "name" : "Chase Elliot",
        "raceWin" : "Low",
        "number" : 9
      },
      {
        "name" : "Kyle Larson",
        "raceWin" : "High",
        "number" : 5
      },
      {
        "name" : "William Byron",
        "raceWin" : "Medium",
        "number" : 24
      },
      {
        "name" : "Kevin Harvick",
        "raceWin" : "Medium",
        "number" : 4
      },
      {
        "name" : "Kyle Bush",
        "raceWin" : "Medium",
        "number" : 18
      },
      {
        "name" : "Kurt Bush",
        "raceWin" : "Medium",
        "number" : 45
      }
    ]
{
    
    "track" : "Texas",
    "sport" : "Nascar",
    "drivers" : [
      {
        "name" : "Chase Elliot",
        "lapsLed" : 180
      },
      {
        "name" : "Kyle Larson",
        "lapsLed" : 72
        
      },
      {
        "name" : "William Byron",
        "lapsLed" : 0
      },
      {
        "name" : "Kevin Harvick",
        "lapsLed" : 55
      },
      {
        "name" : "Kyle Bush",
        "lapsLed": 33
      },
      {
        "name" : "Kurt Bush",
        "lapsLed" : 10
      }
    ]
  }

React component won’t re-render on state change

Here is my code. The imageChunks state variable is not updating correctly. Selecting an image returns an empty array. Selecting another image returns an array of the last image’s base64 chunks. It seems that setImageChunks() is not triggering a re-render. What is causing this? Any help would be appreciated.

const [ imageChunks, setImageChunks ] = useState([])
    
const handleImageChange = async (e) => {    
            const files = e.target.files
    
            // Break image base64 string into chunks for database upload, store each in object with series (filename) and part
            const getChunks = (filename, baseStr, chunkSize) => {
                const str = baseStr.split("")
                const chunks = []
                let part = 0
                let count = str.length
                let start = 0
                while (count){
                    part++
                    start = str.length - count
                    const allowedCount = count < chunkSize ? count : chunkSize
                    chunks.push({
                        series: filename,
                        part: part,
                        data: str.slice(start, start + allowedCount).join("")
                    })
                    count -= allowedCount
                }
                
                return chunks 
            }
    
            // empty imageChunks array to prepare for new file selection
            const fileChunks = []
    
            for (let i = 0; i < files.length; i++){
                // Push file name to product object imageFiles array  
                const fileNames =  formValues.imageFiles
                fileNames.push(files[i].name)
                setFormValues({...formValues, imageFiles: fileNames})
    
                // get array of file chunk objects, push to imageChunks array
                const file = await new Response(files[i]).arrayBuffer()
                const baseString = Buffer.from(file).toString('base64')
                const chunks = getChunks(files[i].name, baseString, 10000)
    
                fileChunks.push(chunks)
            }
    
            setImageChunks(null)
            setImageChunks([...fileChunks])
            console.log(imageChunks)
        }

How do I use .NET bundler with Webpack’s code splitting chunks?

I have a .NET project where I’m trying to use Webpack’s code-splitting functionality.

My Webpack output (the relevant part) looks like this:

{
    output: {
        path: resolve(__dirname, config.path.public),
        pathinfo: false,
        filename: 'js/[name].js',
        chunkFilename: 'js/[name].js',
        publicPath: '/'
    },
}

My bundle config looks something like this:

private void RegisterBundles(BundleCollection bundles)
{
    bundles.Add(new ScriptBundle("~/bundles/js").Include(
        "~/assets/store/js/vendor.js",
        "~/assets/store/js/index.js",
        "~/assets/marketing/js/index-prod.js"));
}

When I build the front-end, Webpack generates several JS chunks: index.js, index-prod.js, 2.js, 3.js, 4.js, etc. So, the code-splitting seems to be working. However, when I fire up my browser, the pages are mostly blank, and I see an error stating that it couldn’t find the source for 4.js. So it seems that the app can’t find the correct path. Note that everything was working before I tried to implement code-splitting. I thought that simply specifying index.js/index-prod.js in the bundle would be sufficient, and that it would dynamically/lazy-load components (i.e. the chunks) on user interaction.

What am I doing wrong? I don’t want the bundler to concatenate all the chunks (which would defeat the purpose of chunking them). And ideally, I shouldn’t have to manually add each chunk file to the bundle.

Destructure object to pass n parameters [duplicate]

I have a function that I use to update my UI

updateUser: async (userId, slug, avatar, coverImage) => {
    const payload = {
        ...(slug && {
            slug
        }),
        ...(description && {
            avatar
        }),
        ...(coverImage && {
            coverImage
        })
    };
    return result.user.mutationUpdate({
        variables: {
            payload,
            userId
        }
    });
},

The thing is that this function is called in different placed in the UI, some of these places are to update the avatar only, or the user slug and so on. This has led to multiple functions on the UI where we do this

const handleUserCoverUpdate = useCallback(async (userId, coverImage) => {
    try {
        await user.updateChannel(userId, null, null, coverImage);
    } catch {
        //
    }
}, []);

const handleUserSlugUpdate = useCallback(async (userId, slug) => {
    try {
        await user.updateChannel(userId, slug, null, null);
    } catch {
        //
    }
}, []);

Meaning we pass parameters as whatever we need and the others as null, I feel this is getting a bit out of hand, would a better way be to pass a payload object and destructure it to get what is being send? If so how would that look with my current implementation, or is there a better way?

Split a string with HTML tag into multiline string

I’ve a string that contains html break tag to split the string as I would like to split the string into multiple lines but it doesn’t seem to render the string as multi-line in UI. How can I achieve the following?

testString = "This is line one<br>This is line two<br>This is line three"

Expected Output:

This is line one
This is line two
This is line three

I have tried using split but that didn’t work. Any hint or help would be appreciated.

React-Redux load firebase auth current user in the redux store

I try to persist the redux store state with the currentUser from the Firebase Auth. When I try to access auth.currentUser I get null and I think it’s because the currentUser info is loaded asynchronously. What I want is to make my application wait until I fetch the currentUser and then to load the currentUser inside the redux store to access it in my application.

Store.js

import { auth } from "../firebase"
const preloadedState = {
    account: auth.currentUser
}
export const store = createStore(
    reducers,
    preloadedState,
    composeEnhancers(applyMiddleware(thunk)),
)

Firebase.js

// Initialize Firebase
const app = initializeApp(firebaseConfig);
const auth = getAuth(app);

How should I wait for currentUser to be fetched and then load inside the redux store to keep the user authenticated?

How to iterate over an array with map or forEach in node express with the HBS template engine and return it in my .hbs file?

[when iterating over objects I have no problem, but I have no way or idea of how to do it with the arrays, I need that after filling in the data of my form when clicking on send, it takes me to my page with the route /products (which until now that works) but I need it to show me a list of all the products that I am adding, and it only shows me a list with a single product, I keep adding products and it replaces the singular product that was there before, therefore I cannot keep all the products]

[INDEX.JS]

const express = require("express");
const routes = require("./routes");
const path = require("path");
let hbs = require('hbs')
const app = express();
const port = 8080;
const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);

hbs.localsAsTemplateData(app);

app.set("view engine", "hbs");
app.use(express.static(__dirname + "public"));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/", (req, res) => {
  res.render("form", {
    title: "Productos",
  });
});

// app.locals.titulo = "Mi tienda";

app.post("/productos", (req, res) => {
  if (!req.body.title && !req.body.price && !req.body.thumbnail) {
    res.status(400).json({
      error: "Bad Request",
      message: "Title, price and thumbnail are required",
    });
  }
  const body = req.body;
  const producto = [
    {
      id: Number(nanoid(5)),
      title: body.title,
      price: body.price,
      thumbnail: body.thumbnail,
    },
  ];
  console.log(producto);
 return res.render("productos", {
    producto,
  });
});

app.get("/productos", (req, res) => {
  res.render("form", {
    title: "Productos",
  });
});

routes(app);

app
  .listen(port, () => {
    console.log(`App listening on port ${port}!`);
  })
  .on("error", (err) => {
    console.log(err);
    throw err;
  });

[FORM.JS]

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=10" />
    <title>Api Shoes Rest</title>
    <style>
      input::-webkit-outer-spin-button, input::-webkit-inner-spin-button {
      -webkit-appearance: none; margin: 0; } input[type=number] {
      -moz-appearance: textfield; }
    </style>
  </head>
  <body>
    <h1 style="font-family: arial; text-align: center">Ingresá tu producto!</h1>
    <form
      action="/productos"
      method="POST"
      style="
        display: flex;
        flex-direction: column;
        text-align: center;
        font-size: 21px;
        font-weight: bold;
        font-family: Arial, Helvetica, sans-serif;
        align-items: center;
        justify-content: center;
        margin: 5px 0;
      "
    >
      <label for="title">
        <input
          type="text"
          name="title"
          id="title"
          placeholder="Title"
          style="
            margin-bottom: 10px;
            border: 1px solid #ccc;
            outline: none;
            border-radius: 5px;
            padding: 8px;
          "
          required
        />
      </label>

      <label for="price">
        <input
          placeholder="Price"
          name="price"
          id="price"
          style="
            margin-top: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            outline: none;
            border-radius: 5px;
            padding: 8px;
          "
          pattern="[0-9.]+"
          type="number"
          required
        />
      </label>
      <label for="thumbnail">
        <input
          type="url"
          pattern="https?://.+"
          title="Include http://"
          placeholder="Thumbnail(URL)"
          name="thumbnail"
          id="thumbnail"
          style="
            margin-top: 10px;
            margin-bottom: 10px;
            border: 1px solid #ccc;
            outline: none;
            border-radius: 5px;
            padding: 8px;
          "
          required
        />
      </label>
      <button
        style="
          padding: 8px 70px;
          font-weight: 700;
          text-align: center;
          font-size: 15px;
          letter-spacing: 1px;
          max-width: 200px;
          cursor: pointer;
          font-family: Helvetica, sans-serif;
          border: 1px solid #ccc;
          border-radius: 5px;
          background-color: #ccc;
          margin-top: 10px;
          text-transform: uppercase;
        "
        type="submit"
      >
       SEND
      </button>
    </form>
    <script>
      document.querySelector("form").addEventListener("input", function (e) {
      const tgt = e.target; if (tgt.type && tgt.type === "number") { const val =
      tgt.value; const nums = val.replace(/[^d.-]/g, ""); if (!/d+/.test(val))
      tgt.value = ""; } });
    </script>
  </body>
</html>

[PRODUCTOS.HBS]

<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <link
      rel="stylesheet"
      href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css
"
    />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Productos</title>
  </head>
  <body class="container form-control-plaintext">
    <div class="container">
      <div class="row">
        <div class="col-12">
          <h1>Productos</h1>
        </div>
      </div>
    <table class="table">
      <thead class="table-dark">
        <tr>
          <th class="text-center" scope="col">#</th>
          <th class="text-center" scope="col">Product</th>
          <th class="text-center" scope="col">Price</th>
          <th class="text-center" scope="col">Preview</th>
        </tr>
      </thead>
      <tbody>
        {{#each producto}}
        <tr>
          <th class="text-center" scope="row">{{id}}</th>
          <td class="text-center">{{title}}</td>
          <td class="text-center">{{price}}</td>
          <td class="text-center">
              <img
              src={{thumbnail}}
              alt="535353"
              style="width:100%; height: 184px; margin-left: 9px;"
            />
          </td>
        </tr>
        {{/each  }}
      </tbody>
    </table>
    <button style="outline: none; height: 55px; text-align: center; float: left; font-weight: bold; font-size: 26px; border: none; background-color: rgb(0, 0, 0); color: rgb(255, 255, 255);">
      Go to home
    </button>
    <script
      src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
    ></script>
  </body>
</html>

[API.JS]

const { customAlphabet } = require("nanoid");
const nanoid = customAlphabet("1234567890", 5);
class Productos {
  constructor() {
    this.productos = [];
  }

  obtenerProductos() {
    return this.productos;
  }

  obtenerProducto(id) {
    return this.productos.find((producto) => producto.id === Number(id));
  }

  create(data) {
    const newProduct = {
      ...data,
      id: Number(nanoid(5)),
    };
    this.productos.push(newProduct);
    return newProduct;
  }

  eliminarProducto(id) {
    this.productos = this.productos.filter(
      (producto) => producto.id !== Number(id)
    );
  }

  actualizarProducto(id, data) {
    const producto = this.obtenerProducto(id);
    if (producto) {
      Object.assign(producto, data);
      return producto;
    }
    throw new Error();
  }
}

module.exports = Productos;

hiding second select option based on first select option

I have 2 selects. Both have the same options (taken from db). Let’s say the options are:

Inventory 1
Inventory 2
Inventory 3

If I choose Inventory 1 in the first select, then in the second select it should disappear. If I choose Inventory 2 in the first select, then Inventory 1 should appear back in the second select and Inventory 2 should disappear.

This is my code so far:

$('#from-location').on('change', function() {
        from_location_value = $('#from-location option:selected').val();
        to_location_value = $('#to-location option:selected').val();

        $("#to-location option[value=" + from_location_value + "]").hide();
        
    });

How to shuffle playlist in javascript?

I’m currently creating a playlist and I got confused over the shuffle function. How do I shufffle it?

function loadTrack(track_index) {
  // Clear the previous seek timer
  clearInterval(updateTimer);
  resetValues();

  // Load a new track
  curr_track.src = track_list[track_index].path;
  curr_track.load();

  // Update details of the track
  track_art.style.backgroundImage =
    "url(" + track_list[track_index].image + ")";
  track_name.textContent = track_list[track_index].name;
  track_artist.textContent = track_list[track_index].artist;
  now_playing.textContent =
    "PLAYING " + (track_index + 1) + " OF " + track_list.length;

  // Set an interval of 1000 milliseconds
  // for updating the seek slider
  updateTimer = setInterval(seekUpdate, 1000);

  // Move to the next track if the current finishes playing
  // using the 'ended' event
  curr_track.addEventListener("ended", nextTrack);

  // Apply a random background color
  random_bg_color();
}

function random_bg_color() {
  // Get a random number between 64 to 256
  // (for getting lighter colors)
  let red = Math.floor(Math.random() * 256) + 64;
  let green = Math.floor(Math.random() * 256) + 64;
  let blue = Math.floor(Math.random() * 256) + 64;
}

// Function to reset all values to their default
function resetValues() {
  curr_time.textContent = "00:00";
  total_duration.textContent = "00:00";
  seek_slider.value = 0;
}

function playpauseTrack() {
  // Switch between playing and pausing
  // depending on the current state
  if (!isPlaying) playTrack();
  else pauseTrack();
}

function playTrack() {
  // Play the loaded track
  curr_track.play();
  isPlaying = true;

  // Replace icon with the pause icon
  playpause_btn.innerHTML = '<i class="fa fa-pause-circle fa-5x"></i>';
}

function pauseTrack() {
  // Pause the loaded track
  curr_track.pause();
  isPlaying = false;

  // Replace icon with the play icon
  playpause_btn.innerHTML = '<i class="fa fa-play-circle fa-5x"></i>';
}
//-------
function nextTrack() {
  // Go back to the first track if the
  // current one is the last in the track list
  if (track_index < track_list.length - 1) track_index += 1;
  else track_index = 0;

  // Load and play the new track
  loadTrack(track_index);
  playTrack();
}

Hi there, I’m currently creating a playlist and I got confused over the shuffle function. How do I shufffle it? I can only use the array that contains elements until the song is played again and each song is hopped once.