How do I toggle a css class to elements of the same class, on click of another single element, in pure JavaScript?

I want to toggle a css class on all elements with the same class, on click of another element. I had it working with jQuery but need to switch to pure JavaScript. The lovely jQuery that works:

$(function () {
            $("#logo").click(function () {
                $(".grey").toggleClass("white",1000);
                $(".red").toggleClass("orange",1000);
        });
        });

—when you click on the element with id=”logo”, everything with class=”grey” toggles “white” class and everything with class=”red” toggles “orange”. Perfect.

I’ve googled like mad for a solution to this, but I can’t get anything to work even though it seems like a simple thing — I’ve taken over a day to try to learn what I need to know but a solution is escaping me. (Scripting is not my first language by any stretch.) Thank you in advance.

How to use _sortBy in an array of objects that contains nested array of objects

I have a list of array of objects that contains a nested array of objects like so:

const mainList = [
{
    id:'001',
    category: 'A',
    content: [ 
        {
            title: 'Apples',
            language: 'en'
        },
        {
            title: '苹果',
            language: 'zh-cn'
        },
        {
            title: '苹果HK',
            language: 'zh-hk'
        },
    ],
},
{
    id:'002',
    category: 'B',
    content: [
        {
            title: 'Grapes',
            language: 'en'
        },
        {
            title: '葡萄',
            language: 'zh-cn'
        },
        {
            title: '葡萄HK',
            language: 'zh-hk'
        },
    ],
},
{
    id:'003',
    category: 'C',
    content: [
        {
            title: 'Bananas',
            language: 'en'
        },
        {
            title: '香蕉',
            language: 'zh-cn'
        },
        {
            title: '香蕉HK',
            language: 'zh-hk'
        },
    ]
}
]

I want to display this list using lodash _sortBy, by its title in alphabetical order like this:

Apples, Bananas, Grapes

My approach:

console.log(_sortBy(mainList.content.title))

But the result comes back with undefined at index 0

Thanks in advance!

Make the List to be responsive design

Goal:
Make the list (ul and its li) to be responsive design in relation to the screen’s width.

Problem:
I don’t know how to solve it.

Info:
*You need to take account to amount of li in each ul list. Different responsive design depends on the width of the ul.
*Each ul can be random from 1 to 10 li or more.

JSBin:
https://jsbin.com/xibalahave/edit?html,css,output

Thank you!


<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
</head>
<body>
  <div class="aaa">
    <ul class="listlist">
      <li>1Test 1</li>
      <li>1Test 2</li>
      <li>1Test 3</li>
    </ul>
  </div>
  <br />
  <div class="aaa">
    <ul class="listlist">
      <li>1Test 1</li>
      <li>1Test 2</li>
      <li>1Test 3</li>
      <li>1Test 4</li>      
    </ul>
  </div>  
  <br />
  <div class="aaa">
    <ul class="listlist">
      <li>1Test 1</li>
      <li>1Test 2</li>
    </ul>
  </div> 
  
</body>
</html>

.aaa ul.listlist{
    margin: 10px 0 16px;
    padding: 0;
    display: -webkit-box;
    display: -ms-flexbox;
    display: flex;
}

.aaa ul.listlist li {
  font-size: 1.125rem;
  display: block;  
  margin-right: 24px;
  line-height: 22px;
  border-radius: 12px 12px 12px 12px;  
  padding: 8px 24px;
  background-color: #00FFFF;
  white-space: nowrap;
}

SignalR instant notification doesn’t work at client page but after one refresh, it works fine

I have used signalR in my project to provide instant notification for the clients. When I send a message to a client, there is no update in the notification. But if I refresh the client page, the notification is updated and no further refresh is necessary. I checked the console in client page. There was an error:

Error: Cannot start a HubConnection that is not in the 'Disconnected' state.
    at L.j (signalr.js:1)
    at L.start (signalr.js:1)
    at pmPage:513

and after that, the following message has been written in the console:

[2022-01-08T07:37:35.208Z] Information: WebSocket connected to wss://localhost:7166/Home/Messages?id=hPCczwx4iIzIUdirBjH9ig.

Javascript code that I use is as follows (message.js):

    var connection = new signalR.HubConnectionBuilder().withUrl("/Home/Messages").withAutomaticReconnect().build();
connection.start();
if (document.getElementById("sendBtn") != null) {
    document.getElementById("sendBtn").addEventListener("click", function () {
        var costCenter = $("#cost-center").val();
        connection.invoke("SendMessage", costCenter).catch(function (err) {
            return console.error(err);
        });
    });
}

The code for Hub is:

public async Task SendMessage(string costCenter)
    {
        var HttpContext = _httpContext.HttpContext;
        string userId = _userRepository.GetUserIdByCostCenter(costCenter).ToString();
        string sender = HttpContext.Session.GetString("department");
        await Clients.User(userId).SendAsync("ReceiveMessage", sender);
    }

Javascript code for the client page:

<script>
connection.on("ReceiveMessage", function (param) {
    var currentMessageNum = parseInt($('#badge-count').text());
    var messageBadge = @Model.MessagesList.Where(x => x.receiverUserId == userId).Count();
    if($('#badge-count').length){
        $('#badge-count').text(currentMessageNum + 1);
        $('.main-msg-list').prepend('<li><a class="dropdown-item message-item" asp-controller="Messages" asp-action="Index" id="msg-'+ currentMessageNum + 1 +'">New message from '+ param +'</a></li>');
    }else{
        $('#badge-count').text('1');
    }
});
connection.start().catch(function (err) {
return console.log(err);
});

How can I fix this problem?

How do I perform the mouse slider in react using react-router-dom?

This is my app.js

import React from "react";
import { BrowserRouter as Router, Routes, Route } from "react-router-dom";
import "./App.css";
import Home from "./Home";
import Navbar from "./Navbar";
import Works from "./Works";

function App() {
  return (
    <>
      <Router>
        <Routes>
          <Route path="/" element={<Home />} />
          <Route path="/works" element={<Works />} />
        </Routes>
      </Router>
    </>
  );
}

export default App;

This is my Home.js

import React, { useEffect, useState } from "react";
import "./App.css";
import ClimbingBoxLoader from "react-spinners/ClimbingBoxLoader";
import "./mainpage.css";
import cloud1 from "./images/cloud1.svg";
import cloud02 from "./images/cloud02.svg";
import cloud2 from "./images/cloud2.svg";
import moon from "./images/moon.svg";
import cloud3 from "./images/cloud3.svg";
import cloud01 from "./images/cloud01.svg";
import { useNavigate } from "react-router-dom";
import {
  MouseParallaxChild,
  MouseParallaxContainer,
} from "react-parallax-mouse";
import Navbar from "./Navbar";

function Home() {
  let navigate = useNavigate();
  const [loading, setloading] = useState(false);
  useEffect(() => {
    setloading(true);
    setTimeout(() => {
      setloading(false);
    }, 1000);
  }, []);

  return (
    <MouseParallaxContainer className="App">
      {loading ? (
        <ClimbingBoxLoader size={20} color={"#F37A24"} loading={loading} />
      ) : (
        <MouseParallaxContainer
          className="main-page"
          containerStyles={{
            width: "100%",
            overflow: "none",
          }}
        >
          <Navbar />
          <h1 className="heading">SASWATA</h1>
          <h1 className="heading2">GHOSH</h1>
          <span className="bar1"></span>
          <span className="bar2"></span>
          <p className="para">web developer</p>
          <p className="scrolldown">SCROLL DOWN</p>
          <span className="verticaline"></span>
          <MouseParallaxContainer
            className="moon"
            containerStyles={{
              width: "100%",
              overflow: "none",
            }}
          >
            <MouseParallaxChild
              className="moon_text"
              factorX={0.01}
              factorY={0.01}
            >
              <p>PORTFOLIO</p>
            </MouseParallaxChild>
            <MouseParallaxChild
              className="moon_img"
              factorX={0.03}
              factorY={0.05}
            >
              <img src={moon} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud01"
              factorX={0.04}
              factorY={0.06}
            >
              <img src={cloud01} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud02"
              factorX={0.03}
              factorY={0.05}
            >
              <img src={cloud02} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud_front1"
              factorX={0.04}
              factorY={0.07}
            >
              <img src={cloud1} alt="cloud1" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud3"
              factorX={0.03}
              factorY={0.05}
            >
              <img src={cloud3} alt="" />
            </MouseParallaxChild>
            <MouseParallaxChild
              className="cloud2"
              factorX={0.06}
              factorY={0.05}
            >
              <img src={cloud2} alt="cloud2" />
            </MouseParallaxChild>
          </MouseParallaxContainer>
          <div className="nav-left">
            <span className="span1"></span>
            <span className="span2"></span>
            <span className="span3"></span>
            <span className="span4"></span>
          </div>
        </MouseParallaxContainer>
      )}
    </MouseParallaxContainer>
  );
}

export default Home;

This is my Works.js

import React, { useEffect, useState } from "react";
import "./App.css";
import ClimbingBoxLoader from "react-spinners/ClimbingBoxLoader";
import "./Works.css";
import cloud02 from "./images/cloud02.svg";
import works from "./images/LandingPage.png";
import { useNavigate } from "react-router-dom";
import cloud01 from "./images/cloud01.svg";
import {
  MouseParallaxChild,
  MouseParallaxContainer,
} from "react-parallax-mouse";
import Navbar from "./Navbar";

function Home() {
  let navigate = useNavigate();
  const [loading, setloading] = useState(false);
  useEffect(() => {
    setloading(true);
    setTimeout(() => {
      setloading(false);
    }, 1000);
  }, []);

  return (
    <MouseParallaxContainer className="App">
      <MouseParallaxContainer
        className="main-page"
        containerStyles={{
          width: "100%",
          overflow: "none",
        }}
      >
        <Navbar />

        <h1 className="heading">
          Web Sec<span className="name-span">urity</span>
        </h1>
        <h1 className="heading2">Project</h1>
        <span className="bar1"></span>
        <span className="bar2"></span>
        <p className="para">website</p>

        <MouseParallaxContainer
          className="moon"
          containerStyles={{
            width: "100%",
            overflow: "none",
          }}
        >
          <MouseParallaxChild className="cloud01" factorX={0.04} factorY={0.06}>
            <img src={cloud01} alt="" />
          </MouseParallaxChild>
          <img className="works-img" src={works} alt="" />
        </MouseParallaxContainer>
        <div className="nav-left">
          <span className="span11"></span>
          <span className="span12"></span>
          <span className="span13"></span>
          <span className="span14"></span>
        </div>
        <div className="page-number">
          <p>01</p>
        </div>
      </MouseParallaxContainer>
    </MouseParallaxContainer>
  );
}

export default Home;

I want to perform mouse slide such that it lands on new page on mouse scroll.
This is the website I am referring.(https://kuon.space/).
It is done using HTML and jquery but I am trying it with React.js and CSS. I hope you can help me. I have tried almost all libraries and couldn’t help myself.

Multiple Values on Checkbox?

I am currently trying to make a “”””calculator”””” for an RP Server, anyways, I need to calculate a sentence and a fine using values on checkboxes.
I already did the sentence, and I would like to make the fine similar to it, but I know I can’t use more than 1 value on each input. What is the best way to get it done?

Sentence Code >

let checkedValue = 0;
let inputElements = document.getElementsByClassName('check');
for(let i=0; i < inputElements.length; ++i){
    const element = inputElements[i]

    if(element.checked){
      checkedValue = checkedValue + parseInt(element.value)
    }
}

How to create a session in axios

I am trying to log in to a website using forms data payload. It requires a _csrf token which is uniquely generated every time the login page opens up. I was trying to get to the login page to take the _csrf id then post the payload in the very same session.

My python code was able to do it with requests.session() but I am having trouble with axios.

My python code

login = {'_csrf': 0, 'email': '[email protected]', 'password': "password"}
with requests.Session() as s:
    url = "https://example.com/login.html"
    res = s.get(url, headers={'User-Agent': 'Mozilla/5.0'})
    soupy = soup(res.content, 'html.parser')
    _csrf = soupy.find('meta', attrs={'name': "csrf-token"})['content']
    login['_csrf'] = _csrf
    res = s.post(url, data=login, headers={'User-Agent': 'Mozilla/5.0'}

My Node.js Code

var url = "https://example.com/login.html";
let response = await axios.get(url,{
    headers:{
       'User-Agent': 'Mozilla/5.0'
    }
})
.then(function(response){
    let soup = cheerio.load(response.data, null, false);
    var _csrf = soup('meta[name="csrf-token"]').attr('content');
    var login = {'_csrf': _csrf, 'email': '[email protected]', 'password': "password"};
    response = axios.post(url,{
        headers:{
            'User-Agent': 'Mozilla/5.0'
        },
        data: login,
    }).catch((e)=> {console.log(e)});
    console.log(response.data);
});

but it doesn’t work as I get a _csrf mismatch error. What can I do to get axios work in a session?

I’m making a circle follow the cursor but want it to fadeout when the mouse stops

Im making a circle follow the cursor using jquery which works fine but i was wondering if there was a way so that the circle fades out whenever the mouse stops.

I have tried using mouseout funtion of jquery and making the opacity 0 but it would just stop the circle in between whenever the mouse stops which is obvious but is there some other method to achieve this ?

My jquery code –

 var mouseX = 0, mouseY = 0;
   var xp = 0, yp = 0;
        
  $(document).mousemove(function(e){
    
    $("#circlecc").css({opacity: 1})
     
    mouseX = e.pageX - 12;
    mouseY = e.pageY - 12;
    
  });

  setInterval(function(){

    xp += ((mouseX - xp)/6);
    yp += ((mouseY - yp)/6);
    $("#circlecc").css({left: xp +'px', top: yp +'px'});
    
  }, 20);

Also while moving the cursor below the site or beyond the site the circle goes beyond the site too and adds a scroll bar, is there a way to avoid that

The Website

How can I improve this paginated do while async await GET request in Javascript (NodeJS)?

I am learning JavaScript (Node.js – using the Pipedream platform). I have been writing scripts to help automate some little tasks in my day to day work.

I am creating one that generates a report on recent interactions with clients.

As part of this I am using axios to get “engagements” from the Hubspot API (basically a list of identifiers I will use in later requests).

The API returns paginated responses. I have encountered pagination previously and understand the principle behind it, but have never written a script to handle it. This is my first.

It works. But I feel it could be improved. Below I’ve commented how I’ve approached it.

The endpoint returns up to 100 values ‘per page’ along with a "hasMore":true flag and an "offset":987654321 value which can be passed as a query parameter in subsequent requests (if hasMore === true).

Example API response:

{"results":[1234,1235,1236],"hasMore":true,"offset":987654321}

My code:

import axios from 'axios';
//function to get each page of data
async function getAssoc(req){
      const options = {
        method: 'GET',
        url: `https://api.hubapi.com/${req}`,
        headers: {
          Authorization: `Bearer ${auths}`,
        },
      };
      return await axios(options);
}
//declare array in which to store all 'associations'
const assocs = [];
//store the ID that I get in an earlier step
const id = vid;
//declare variable in which to temporarily store each request response data
var resp;
//declare query parameter value, initially blank, but will be assigned a value upon subsequent iterations of do while
var offset = '';
do {
  //make request and store response in resp variable
  resp = await getAssoc(`crm-associations/v1/associations/${id}/HUBSPOT_DEFINED/9?offset=${offset}`);
  //push the results into my 'assocs' (associations) array
  resp.data.results.forEach(element => assocs.push(element));
  //store offset value for use in next iteration's request
  offset = resp.data.offset;
} while (resp.data.hasMore); //hasMore will be false when there's no more records to request

return assocs;

I feel it could be improved because:

  1. The DO WHILE loop, I believe, is making sequential requests. Is parallel a better/faster/more efficient option?
  2. I’m re-assigning new values to vars instead of using consts which seems simple and intuitive in my beginner’s mind, but I don’t understand a better way in this instance.
  3. I would welcome any feedback or suggestions on how I can improve this for my own learning.

Thank you in advance for your time and any assistance you can offer.

What is your review on IKIGAI?

The rather exotic sounding name of this book, ikigai, as the authors explain, is relatively straightforward. “This Japanese concept, which translates roughly as “the happiness of always being busy,” is, “like logotherapy, but it goes a step beyond.”helps people find their purpose in life.”Part of my ikigai is to be a nice person and not think disparagingly of anyone. And I am not here. This book was an interesting read for me, and may be a revelational read for you. I make no judgment on that. I just give you my experience as a reader.This book would, in my opinion, make an excellent gift for anyone in your life that might need a little boost or is otherwise hard to buy for. There is absolutely nothing here that could meet with controversy or resistance. It is decidedly upbeat throughout.And that is saying a lot of good things about any book. Read more…….

You can buy this book with exclusive offer here.

How to Make A second API call based on the value gotten from the first. with React and useEffect hooks

Im trying to make a call to the first APi that contains a payload of different CATEGORIES and then use that to make a second call to another API that contains different category items from each CATEGORY from the first. I am new to react and don’t quite know how to make the logic work. This is my idea below. Category items are displayed based on the selected CATEGORIES. I am confused on how to use the value from the first to make the second call.

const [catalog,setCatalog] = useState([]);
const [catalogItems,setCatalogItems]= useState([]);

useEffect(() => {

    const fetchData = async () => {

      await fetchMarketingCategories()

     .then((result)=>{

        setCatalog(result);

          console.log("result",result);
         
     })

     .then(async (categoryId)=>{
         
          const {items = []} = await getAdvisorMarketingCatalog(categoryId)

          setCatalogItems(items);
     })
     

    };
    fetchData();

    
    });
  }, []);

Format image to correctly pass through model.predict()

I created this model for image classification; however, when I try to pass the image path through model.predict(), I receive this error:

ValueError: Error when checking model : the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see 1 Tensor(s), but instead got 9 Tensors(s).

Is there any way to decrease the number of tensors going through the function, or correctly format the image in tensors to pass through and return a prediction?

I’ve looked everywhere, and other questions similar to this didn’t cover my use case in node.js. Any help or nudge in the right direction is welcome 🙂

Below is my model.json file, the model I created for image classification.
index.js is what I run through node.js to supposedly give a prediction.

model.json

{"modelTopology":{"class_name":"Sequential","config":[{"class_name":"Flatten","config":{"name":"flatten_Flatten1","trainable":true,"batch_input_shape":[null,7,7,256],"dtype":"float32"}},{"class_name":"Dense","config":{"units":100,"activation":"relu","use_bias":true,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":null,"distribution":null,"seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense1","trainable":true}},{"class_name":"Dense","config":{"units":3,"activation":"softmax","use_bias":false,"kernel_initializer":{"class_name":"VarianceScaling","config":{"scale":1,"mode":null,"distribution":null,"seed":null}},"bias_initializer":{"class_name":"Zeros","config":{}},"kernel_regularizer":null,"bias_regularizer":null,"activity_regularizer":null,"kernel_constraint":null,"bias_constraint":null,"name":"dense_Dense2","trainable":true}}],"keras_version":"tfjs-layers 0.7.0","backend":"tensor_flow.js"},"weightsManifest":[{"paths":["./ml-classifier-1-2-3.weights.bin"],"weights":[{"name":"dense_Dense1/kernel","shape":[12544,100],"dtype":"float32"},{"name":"dense_Dense1/bias","shape":[100],"dtype":"float32"},{"name":"dense_Dense2/kernel","shape":[100,3],"dtype":"float32"}]}]}

index.js

var tf = require('@tensorflow/tfjs-node');

const image = `./1-1.png`

const main = async () => {
  const model = await tf.loadLayersModel('file:///retake/savedmodels/model.json');
  model.summary();

  const prediction = model.predict(image);
  prediction.print();
}
main()