make these slides loop?

I have been working on this for a little while, and I think I’m stuck at this point.

I made a div slider with arrows. Each div slide is set to a min-width of 80px.

The code works just fine, except, when I navigate either to the left or the right, it stops at the last item. I want this slider to loop (as in endlessly), instead of ending at the last item.

let buttonLeft = document.getElementById('slide_left')
    let buttonRight = document.getElementById('slide_right')

    buttonLeft.addEventListener('click', function() {
        document.getElementById('slider').scrollLeft -= 90
    })

    buttonRight.addEventListener('click', function() {
        document.getElementById('slider').scrollLeft += 90
    })
body{
            background-color: #555;
            height: 100vh;
            display: grid;
            align-items: center;
            justify-items: center;
            font-family: 'Helvetica';
        }
        
        div#slide_wrapper{
            width: 440px;
            display: flex;
            justify-content: space-between;
            height: fit-content;
        }
        
        div#slider{
            width: 350px;
            display: flex;
            height: fit-content;
            flex-wrap: nowrap;
            overflow: hidden;
        }
        
        div.thumbnail{
            min-width: 80px;
            min-height: 80px;
            cursor: pointer;
            display: grid;
            place-items: center;
            font-size: 30px;
        }

        div.thumbnail:not(:last-child){
            margin-right: 10px;
        }

        div.thumbnail:nth-child(1){
            background-color: darkturquoise;
        }
        div.thumbnail:nth-child(2){
            background-color: goldenrod;
        }
        div.thumbnail:nth-child(3){
            background-color: rebeccapurple;
        }
        div.thumbnail:nth-child(4){
            background-color: powderblue;
        }
        div.thumbnail:nth-child(5){
            background-color: firebrick;
        }
        div.thumbnail:nth-child(6){
            background-color: sienna;
        }
        div.thumbnail:nth-child(7){
            background-color: bisque;
        }
        div.thumbnail:nth-child(8){
            background-color: navy;
        }
        
        div#slide_wrapper > button{
            height: fit-content;
            align-self: center;
            font-size: 24px;
            font-weight: 800;
            border: none;
            outline: none;
        }
        
        div#slide_wrapper > button:hover{
            cursor: pointer;
            background-color: dodgerblue;
            color: #fff;
        }
<div id="slide_wrapper">
        <button id="slide_left" class="slide_arrow">&#10094;</button>
        <div id="slider">
            <div class="thumbnail active">1</div>
            <div class="thumbnail">2</div>
            <div class="thumbnail">3</div>
            <div class="thumbnail">4</div>
            <div class="thumbnail">5</div>
            <div class="thumbnail">6</div>
            <div class="thumbnail">7</div>
            <div class="thumbnail">8</div>
        </div>
        <button id="slide_right" class="slide_arrow">&#10095;</button>
    </div>

Objects instances retrieved by findOne do not have any methods

Whenever I retrieve an object from my mongo database, it doesn’t have any methods and I am trying to figure out (1) why and (2) a solution.

To summarise, the following sums up the problem:

(1) I can create an object and its methods work:

const newUser = new User(email, hashedPassword);
console.log(newUser.test); // correct - it’s not undefined

(2) I can insert the instance (with its methods) into the database (via saveToDb):

const insertedUser = await collection.insertOne(this);

(3) I can retrieve it from the database (via findByEmail):

const user = await collection.findOne({ email });

(4) But it doesn’t have any methods anymore:

if (!user) return; // temporary code
console.log(user); // correctly displays object keys and values
console.log('user.test', user.test); // undefined - why?

Why does this happen? I’ve read a few other posts about it, but they all seem to use mongoose, which I do not use in my app (maybe I should use it?). This post did not get an answer, which I think is a similar issue.

Any insight would be appreciated, thank you.

Incase needed to see, here’s the class:

export class User {
  email: string;
  hashedPassword: any;
  dateCreated: Date;

  constructor(email: string, hashedPassword: any) {
    this.email = email; // make email.toLowerCase(); 
    this.hashedPassword = hashedPassword; 
    this.dateCreated = new Date();
  }

  async saveToDb() {
    try {
      const collection = getCollection(USERS_COLLECTION_NAME);
      const sanitisedEmail = this.email.toLowerCase();
      const insertedUser = await collection.insertOne(this);

      console.log('THIS HAS BEEN INSERTED TO DB:', this);
      console.log('this.test:', this.test); // works
      this.test();

      const token = jwt.sign(insertedUser, sanitisedEmail, {
        expiresIn: 60 * 24,
      });
      return token;
    } catch (err) {
      throw err;
    }
  }

  test() {
    console.log('test() within class Fn');
    return 5;
  }

  static staticTest() {
    console.log('staticTest() within class Fn');
    return 6;
  }

  signToken() {
    const token = jwt.sign(this, this.email, {
      expiresIn: 60 * 24,
    });
    return token;
  }

  static async fetchAll() {
    try {
      const collection = getCollection(USERS_COLLECTION_NAME);
      const users = await collection.find().toArray();  
      return users;
    } catch (err) {
      throw err;
    }
  }

  static async findByEmail(email: string) {
    try {
      const collection = getCollection(USERS_COLLECTION_NAME);
      const user = await collection.findOne({ email });
      if (!user) return; // temporary code
      console.log('FOUND THIS USER: ', user); // works
      console.log('user.test', user.test); // undefined - key problem lies here...
      return user;
    } catch (err) {
      throw err;
    }
  }
}

alternative node js “fs” to work with vanilla js

Anyone clever enough to let me know how to use “fs” without nodejs? Like in a async vanilla js type of way. I have some code below that I am trying to convert but I think “fs” is just for node.

    const fs = require('fs'),
  const text = fileEncoding ? 
                                fs.readFileSync(filePath,'base64') : 
                                fs.readFileSync(filePath).toString('utf8');
                    
                            content += text + newLine;

Unable to access object properties while doing a post request

I am creating a post request that adds new posts to MongoDB. The post request works well and I can see the post in Mongo.

I am struggling at accessing properties from the object using req.body, specifically req.body._id. I would like to console.log the req.body._id to verify that it worked. In the terminal, I keep on getting ‘undefined’.

All the solutions I have seen so far say include app.use(express.json()); and app.use(express.urlencoded({ extended: false })); which I have.

I am stumped on what to try next. Any suggestions would be appreciated.

Here is my server.js file

const express = require('express');
const dotenv = require("dotenv").config();
const mongoose = require('./db/mongoose');
const app = express();
const postsRoute = require('./routes/posts');

app.use(express.json());
app.use(express.urlencoded({ extended: false }));

app.use("/posts", postsRoute);

app.listen( process.env.PORT || 5000, (err) => {
    console.log(`listening on port ${process.env.PORT}`);
});

Here is my routes file

const express = require('express');
const router = express.Router();

const { allPosts, createPost } = require('../db/models/postModel');


router.get("/", async (req, res) => {
    console.log(`req.title is: ${req.title}`);
    try {
        const posts = await allPosts();
        res.send(posts);
    } catch (err) {
        console.log(err.message);
    }
    });

router.post("/create", async (req, res) => {
    const newPost = req.body;
    try {
        const addingPost = await createPost(newPost);
        console.log(`req.body is:${addingPost}`);
        console.log(`req.body title:${addingPost.title}`);
        console.log(`addingPost is: ${addingPost} with id of ${addingPost._id}`);
        res.send (addingPost);
    } catch (err) {
        res.status(500).send(err.message);
    }
});

module.exports = router;

Here is my Schema file

const mongoose = require('mongoose');
const { Schema } = mongoose;

const postSchema = new Schema({
    author: {
        type: String,
        required: true
    },
    title: {
        type: String,
        required: true
    },
    content: {
        type: String,
        required: true,
    },
    tags: [String],
    file: String,
    likes: {
        type: Number,
        //We want to default to 0 likes
        default: 0,
    },
    createdAt: {
        type: Date,
        default: new Date(),
    },
});


const postModel = mongoose.model('Post', postSchema);

//Get all posts
const allPosts = async () => {
    const posts = await postModel.find();
    return posts;
};

//Create posts
const createPost = async (post) => {
    const newPost = await postModel.create(post);
    return newPost;
};


module.exports = { allPosts, createPost }; 

How to execute all queries in graphql inside gatsby-node.js?

I want to execute multiple queries nodes at the same time in gatsby-node.js in order to create pages accordingly to my query , so these are the queries :

{
      allPrismicLastPosts {
        nodes {
          data {
            blogs {
              blog {
                document {
                  ... on PrismicBlog {
                    uid
                  }
                  ... on PrismicCulture {
                    uid
                    }
                  }
                }
              }
            }
          }
        }
      }
      allPrismicMainBlogs {
        nodes {
          data {
            blogs {
              blog {
                document {
                  ... on PrismicBlogMain {
                    uid
                  }
                }
              }
            }
          }
        }
      }
}

So in order to createPage in gatsby-node.js I need both the uid of allPrismicLastPosts and allPrismicMainBlogs from these queries , this is what I ‘ve tried :

{
      allPrismicLastPosts {
        nodes {
          data {
            blogs {
              blog {
                document {
                  ... on PrismicBlog {
                    uid
                  }
                  ... on PrismicCulture {
                    uid
                    }
                  }
                }
              }
            }
          }
        }
      }
      allPrismicMainBlogs {
        nodes {
          data {
            blogs {
              blog {
                document {
                  ... on PrismicBlogMain {
                    uid
                  }
                }
              }
            }
          }
        }
      }
}

But this will only fetch the allPrismicLastPosts uid instead I want all the uid ,Any idea to solve this ?

How to searching a data with a search bar in Next.js with Local API, using search query?

I want searching products for title with search bar, I suing a API local with Next.js, i want search the products by title

Url API Next

http://localhost:3000/api/products

JSON Data

{
id: "1",
title: "Polo manga corta",
image: "https://res.cloudinary.com/dj1ethf6d/image/upload/v1654948335/Mayoral/polo-manga-corta-contrastes-chico_id_22-06107-044-M-4_yfe04a.jpg",
price: 12.9
},

Handler query

import { products } from './dataproducts'


export default async function handlerTitle (req, res){
    const products = req.query 
    const getTitle = await fetch(
        `http://localhost:3000/api/products/${products}`
        );
        const data = await getTitle.json(products);
        res.status(200).json(data);
}

Search component

import { useState } from 'react'
import styles from '../../styles/SearchBar.module.css'

function SearchBar({ data }) {

    const [query, setQuery] = useState('')

    const onChange = async (e) => {
        const {value} = e.target;
        setQuery(value)

        if (value.length > 3) {
            const response = await fetch(`http://localhost:3000/api/products?=${value}`);
            const data = await response.json();
            console.log(response)
        }
    }

input passing it the onChange and value

    return (
        <input 
        className={styles.input} 
        onChange={onChange}
        id='city'
        type="search" 
        name="search"
        value={query} 
        placeholder="Nombre producto..." />
    )
}

export default SearchBar

How Do I handle receiving multiple WebSocket onopen & onmessage Using JavaScript?

I Am New to Coding and Learning to start small Projects to help me improve and learn-

I wanted to get Different WebSocket feed simultaneously in the same Script- response for both granularity for 300 & 900 at the same time;
below is the actual code for a single request

const WebSocket = require('ws');
var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');


ws.onopen = function(evt) {
   
    ws.send(JSON.stringify(
    {ticks_history: "R_25",
     subscribe: 1,
     adjust_start_time: 1,
     count: 1,
     end: "latest",
     granularity: 300,
     start: 1,
     style: "candles"}
     
    ));

};

ws.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   console.log('ticks update: %o', data.tick.quote);

};

Where by I can get different granularity response of same feed at the same time, although I have been able to get this independently but would love to be able to get them all from the same script!

Below is my script

const WebSocket = require('ws');
var ws = new WebSocket('wss://ws.binaryws.com/websockets/v3?app_id=1089');


ws.onopen = function(evt) {
   
    ws.send(JSON.stringify(
    {ticks_history: "R_25",
     subscribe: 1,
     adjust_start_time: 1,
     count: 1,
     end: "latest",
     granularity: 300,
     start: 1,
     style: "candles"}, 

//here is where i added the additional request for 900 time frame

     {ticks_history: "R_25",
     subscribe: 1,
     adjust_start_time: 1,
     count: 1,
     end: "latest",
     granularity: 900,
     start: 1,
     style: "candles"}
     
    ));

};

ws.onmessage = function(msg) {
   var data = JSON.parse(msg.data);
   console.log('ticks update: %o', data);

};

from the above script, I only get a data feed from only the second request -900

How do I write this that will allow me to get both data responses same time?

MVC-ish custom element

Coming from this custom element:

customElements.define('hello-world', class extends HTMLElement {
  constructor() {
    super();
    this.count = 0;
    this.innerHTML = `Hello World (clicked: <span>0 times</span>)`;
    this.onclick = (evt) => {
      this.count++;
      this.querySelector('span').innerHTML = `${this.count} ${this.count == 1 ? 'time' : 'times'}`;
    }
  }
});
hello-world {
  cursor: pointer;
}
<hello-world></hello-world>

Now I want to do it the MVC way:

class Model {
  constructor() {
    this.count = 0;
  }
  countUp() {
    this.count++;
  }
}

class View {
  constructor() {
    this.container = document.querySelector('hello-world');
    this.template = `Hello World (clicked: <span>0 times</span>)`;
    this.container.innerHTML = this.template;
  }
  bindCountUp(handler) {
    this.container.addEventListener('click', evt => {
      this.container.querySelector('span').innerHTML = `${this.count} ${this.count == 1 ? 'time' : 'times'}`;
    });
  }
}

class Controller {
  constructor(model, view) {
    this.model = model;
    this.view = view;
    this.view.bindCountUp(this.handleCountUp);
  }
  handleCountUp = () => {
    this.model.countUp();
  }
}

customElements.define('hello-world', class extends HTMLElement {
  constructor() {
    super();
    const helloWorld = new Controller(new Model(), new View());
    // const shadow = this.attachShadow({mode: 'open'});
  }
});
hello-world {
  cursor: pointer;
}
<hello-world></hello-world>
  1. Is that a sensible approach, aside from the cannons being used in this example?
  2. What am I doing wrong within the event listener?
  3. How to attach the view to the shadow DOM instead of just using a container?

For whatever reason Idk why I can’t my object through [String that extract from another array], it works normal with other String and simpler array [closed]

let money = {
  "ONE HUNDRED": 100,
  "Twenty Dollars": 20,
  "Ten Dollars": 10,
  "Five Dollars": 5,
  "Dollar": 1,
  "Quarter": 0.25,
  "Dime": 0.1,
  "Nickel": 0.05,
  "Penny": 0.01
};
let shit = [
  ["Penny", 101]
];
console.log(money[shit[0][0]])

let cid = [
  ["PENNY", 1.01],
  ["NICKEL", 2.05],
  ["DIME", 3.1],
  ["QUARTER", 4.25],
  ["ONE", 90],
  ["FIVE", 55],
  ["TEN", 20],
  ["TWENTY", 60],
  ["ONE HUNDRED", 100]
]

console.log(money[cid[0][0]])
console.log(typeof(cid[0][0]))

HTML checkboxes: replacing checkmark with other characters

Instead of cycling between blank & checkmark, I’d like to cycle through numbers or letters. Yes, it would no longer be a CHECKbox technically (well input element, type checkbox), but checkboxes provide a nice outlined blank properly-scaled square. If it would be easier to alter another HTML element to get this effect please let me know. I plan to control all the cycling logic with JavaScript.

Show rounded link with to act as a rounded button

I am customizing the SharePoint online main menu, and to do so i added this javaScript to add a button at the end of the menu items:-

var e = document.createElement('div');
e.classList.add('ms-HorizontalNavItem');

e.innerHTML = "<a data-automation-id='button-web-part' href='https://fullstackgear.com.au/' target='_blank' class='ms-Button ms-Button--primary root-251' data-is-focusable='true' style='background-Color:green;color:while'><span class='ms-Button-flexContainer flexContainer-252' data-automationid='splitbuttonprimary'><span class='ms-Button-textContainer textContainer-253'><span style='color:while'>Shop me some</span></span></span></a>";



var ele = document.querySelectorAll('[role="menubar"]');
ele[0].appendChild(e);

now i result i got will be as follow:-

enter image description here

but i want the item/button to be as follow, bigger with rounded corners:-

enter image description here

any advice?

Sequelize transactions: Part of the options object, or a separate argument?

The sequelize docs for create, findByPk and findAll state that a transaction should be passed as part of the options argument, here, but I’ve previously been using it as a separate arg with no issues (afaik):

await Example.create({ 
  // options
}, { transaction: t });

I’d naturally believe the docs, but while looking for examples I’ve come across a lot of this latter usage, with some even suggesting the docs might be wrong here for example. Was hoping someone could clarify which is correct, or if it even matters?

Why does this Firebase web authentication function ‘onAuthStateChanged’ occasionally not fire?

Why does this Firebase web authentication function ‘onAuthStateChanged’ occasionally not fire?

The intention of this code is to use Firebase for Web (JavaScript) and automatically sign-up
visitors to the website as an anonymous user, however if they created an account using email and the anonymous sign-in is ignored.

Symptoms of this issue are:

  • At random, maybe 2% of the time, the function ‘onAuthStateChanged’ does not fire at all.
  • Refreshing the browser does not fix the issue
  • Closing and reopening the tab does fix the issue
  • Mostly happens on the Chrome iOS app, but not only.

When this happens, the debug statements look like this:

  • loaded 4

  • loaded 5

  • loaded 6

  • loaded 7

  • loaded 8

~98% of the time this code works as intended but around 2% of the time is does not work at all and the user must close and reopen the tab and I can’t figure out why. Does anyone know what’s wrong?

    console.log("loaded 4");
    const analytics = getAnalytics(app);
    console.log("loaded 5");
    const db = getFirestore(app);
    console.log("loaded 6");
    const functions = getFunctions(app);
    console.log("loaded 7");
    const auth = getAuth();
    console.log("loaded 8");

    onAuthStateChanged(auth, (user) => {
      console.log("initiate on auth state change")

      if (user) {
        console.log("signed is as something")
        fuctionToLoadStuff();

        let uid = user.uid;
        const isAnon = user.isAnonymous;
        if (isAnon == true) {
          console.log("User is signed in anonymously as " + uid);
          annonUserStuff(uid);

        } else {
          console.log("User is signed into an account as " + uid);
          getProfile(uid);
        }
      } else {
        console.log("signed is as nothing");
        signInAnonymously(auth)
          .then(() => {
            const uid = auth.currentUser.uid;
            console.log("Anon user acct created");
          functionForANewAnonUser(uid);
          })
          .catch((error) => {
            const errorCode = error.code;
            const errorMessage = error.message;
            console.log(errorMessage);
          });
      }
    });

lowdb write() in codesandbox not saving data to file?

I don’t know if its a mistake on my end or a problem with codesandbox. I tryed a very basic setup with lowdb where i can load data from a json-file (so the connection is established) but the db.write() statement simply don’t work.

Has anyone an explanation/ solution for me? =(

https://codesandbox.io/s/stoic-cache-ne2n10?file=/src/index.js

import { LowSync, JSONFileSync } from "lowdb";

const db = new LowSync(new JSONFileSync("/src/file.json"));

const a = async () => {
  await db.read();
  db.data.test2 = "123";
  console.log(db.data);
  await db.write();
  await db.read();
  console.log(db.data);
};

a();