Scroll down to specific contact onclick a letter

I created a contact list agenda with a contact-alphapets sidebar filter. What Im trying to achieve is when clicking on a specific letter it will scroll down to the first contact that start with the Letter chosen.
Exemple when I click on Letter A it will scroll down to contacts that starts with the letter A.

Here the code Im using:

HTML part:

<div class="contact-box clearfix">
    <div class="contact-cat col-xs-12 col-sm-4 col-lg-3">
        <div class="roles-menu">
            <ul class="nav">                                            
                <li class="contacts_tab active" rel="customers"><a href="#customers">Customers</a></li>
                <li class="contacts_tab" rel="suppliers"><a href="#suppliers">Suppliers</a></li>
            </ul>
        </div>
    </div>
    <div class="contacts-list col-xs-12 col-sm-8 col-lg-9">
        <ul class="contact-list" id="contact-list" >
            <!-- DISPLAY CONTACTS LIST WITH AJAX-->
        </ul>      
    </div>
    
    <div class="contact-alphapets">
        <div class="alphapets-inner">
            <a href="#" id="A" class="findContact" rel="A">A</a>
            <a href="#" id="B" class="findContact" rel="B">B</a>
            <a href="#" id="C" class="findContact" rel="C">C</a>
            <a href="#" id="D" class="findContact" rel="D">D</a>
            <a href="#" id="E" class="findContact" rel="E">E</a>
            <a href="#" id="F" class="findContact" rel="F">F</a>
            <a href="#" id="G" class="findContact" rel="G">G</a>
            <a href="#" id="H" class="findContact" rel="H">H</a>
            <a href="#" id="I" class="findContact" rel="I">I</a>
            <a href="#" id="J" class="findContact" rel="J">J</a>
            <a href="#" id="K" class="findContact" rel="K">K</a>
            <a href="#" id="L" class="findContact" rel="L">L</a>
            <a href="#" id="M" class="findContact" rel="M">M</a>
            <a href="#" id="N" class="findContact" rel="N">N</a>
            <a href="#" id="O" class="findContact" rel="O">O</a>
            <a href="#" id="P" class="findContact" rel="P">P</a>
            <a href="#" id="Q" class="findContact" rel="Q">Q</a>
            <a href="#" id="R" class="findContact" rel="R">R</a>
            <a href="#" id="S" class="findContact" rel="S">S</a>
            <a href="#" id="T" class="findContact" rel="T">T</a>
            <a href="#" id="U" class="findContact" rel="U">U</a>
            <a href="#" id="V" class="findContact" rel="V">V</a>
            <a href="#" id="W" class="findContact" rel="W">W</a>
            <a href="#" id="X" class="findContact" rel="X">X</a>
            <a href="#" id="Y" class="findContact" rel="Y">Y</a>
            <a href="#" id="Z" class="findContact" rel="Z">Z</a>
        </div>
    </div>
</div>

Display contacts with ajax/jquery

var baseUrl = $('#baseUrl').val();
$('.contacts_tab').on('click', function(){
    
    var params = $(this).attr('rel');
    $('#contact-list > li').remove();

    $.ajax({
        url: `${baseUrl}api/contacts/list.php?params=${params}`,
        success: function (result) {
            
            $.each(result, function(index, data) {
                var html = `<li class="${data.firstname.slice(0,1)}">`;
                    html += '<div class="contact-cont">';
                    html += '<div class="pull-left user-img m-r-10">';
                    html += `<a href="" title="${data.firstname} ${data.lastname ?? ''}"><img src="${baseUrl}public/attachements/${params}/${data.logo}" alt="" class="w-40 img-circle"></a>`;
                    html += '</div>';
                    html += '<div class="contact-info">';
                    html += `<span class="contact-name text-ellipsis">${data.firstname} ${data.lastname ?? ''}</span>`;
                    html += `<span class="contact-date"><i class=""><a href="tel:${data.phone}">${data.phone}</a></span>`;
                    html += '</div>';
                    html += '</div>';
                    html += '</li>';
                                       
                    $("#contact-list").append(html);
            });    
        }
    });
})

The code above works just fine.

Here is the code I tried for the scroll down:

$(".findContact").on('click', function(e){
    e.preventDefault();
    var findContact = $(this).attr('rel');    
    $('html,body').animate({ scrollTop: $(`.${findContact}`).offset().top},  'slow');
})

**

Wrong swipe direction js

Please tell me, if you start touchmove from the middle of the page and move to the right, then console.log() goes right, but if you move to the left and cross the middle of the screen, console.log() will show the opposite direction, although the swipe goes in the same direction. As I understand it, this is due to the fact that touchstart coordinates are fixed from where touchmove started. How to fix this error. (see video).

https://youtu.be/_pB49S2BR2o

var initialX = null;
var initialY = null;
$("#content, .menu").on("touchstart", function(e) {
  initialX = e.touches[0].clientX;
  initialY = e.touches[0].clientY;
});
$("#content, .menu").on("touchmove", function(e) {
  var diffX = initialX - e.touches[0].clientX;
  var diffY = initialY - e.touches[0].clientY;

  if (Math.abs(diffX) > Math.abs(diffY)) {
    if (diffX > 0) {
      console.log("Right");
    } else {
      console.log("Left");
    }
  } else {
    return;
  }
  var width = parseInt($("body").css("width"));
  clientX = e.touches[0].clientX;
  width = width - clientX;
  if (width >= 0 || width <= 375) {
    $(".menu").css("left", "-" + width + "px");
  } else {}
})
body {
  margin: 0px;
  overflow: hidden;
  font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
}

.menu {
  background: blue;
  width: 100%;
  height: 100%;
  z-index: 1;
  position: absolute;
  left: -100%;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
}

#content {
  width: 100%;
  height: 100vh;
  color: #000;
  display: flex;
  align-items: center;
  justify-content: center;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

<body>
  <div class="menu" style="transition-duration: 0ms;">Menu slide</div>
  <div id="content">
    Content slide
  </div>
</body>

Error when installing Opencv for Javascript/nodejs

I am trying to use opencv for nodejs for my image processing. I’m slightly familiar with it’s Python version, but it seems like it also exists in Javascript. When trying to install it, I keep running in errors. The most common one is this:

PS C:UsersmyNameProjectsthewaveChatbotwebpagetestOpenCV> npm i opencv4nodejs
npm ERR! code 1
npm ERR! path C:UsersmyNameProjectsthewaveChatbotwebpagetestOpenCVnode_modulesopencv4nodejs
npm ERR! command failed
npm ERR! command C:WINDOWSsystem32cmd.exe /d /s /c node ./install/install.js
npm ERR! info install using lib dir: C:/Users/myName/Projects/thewave/Chatbotwebpage/testOpenCV/node_modules/opencv-build/opencv/build/lib/Release
npm ERR! C:UsersmyNameProjectsthewaveChatbotwebpagetestOpenCVnode_modulesopencv4nodejsinstallinstall.js:37
npm ERR!   throw new Error('library dir does not exist: ' + libDir)
npm ERR!   ^
npm ERR!
npm ERR! Error: library dir does not exist: C:/Users/myName/Projects/thewave/Chatbotwebpage/testOpenCV/node_modules/opencv-build/opencv/build/lib/Release      
npm ERR!     at Object.<anonymous> (C:UsersmyNameProjectsthewaveChatbotwebpagetestOpenCVnode_modulesopencv4nodejsinstallinstall.js:37:9)
npm ERR!     at Module._compile (node:internal/modules/cjs/loader:1101:14)
npm ERR!     at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
npm ERR!     at Module.load (node:internal/modules/cjs/loader:981:32)
npm ERR!     at Function.Module._load (node:internal/modules/cjs/loader:822:12)
npm ERR!     at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
npm ERR!     at node:internal/main/run_main_module:17:47

npm ERR! A complete log of this run can be found in:
npm ERR!     C:UsersmyNameAppDataLocalnpm-cache_logs2022-03-15T12_52_08_489Z-debug.log

I found that others also have a similar issue, but I have tried many things (added opencv to my system variables for starters), reinstalled everything, but still.. I keep getting this error 🙁

Any help is welcome! 🙂 I thank you in advance. I am using https://www.npmjs.com/package/opencv4nodejs#how-to-install

Is there any way to change AG-grid checkbox border width and color without using any Custom Component?

I’m using AG-Grid to show data in a grid. I want to customize checkbox without using any Custom Component for Checkbox.

I have to make the border slightly thin and change the border color and I’m struggling to do so.

I have tried this:-

.ag-theme-alpine .ag-checkbox-input-wrapper {
  font-size: 0.875rem !important;
  font-weight: 10px !important;
  border-color: #b3b3b3 !important;
}

I’m able to reduce the height/width of the checkbox by giving it a font-size. But the border color and border width is unaffected.

I also tried using border property- border: 0.5rem solid #b3b3b3. But it didn’t work.

How to abstract environmental JS class implementations

I have an abstraction of an adapter. Through an environmeht variable I control which implementation is used. I am not satisfied with this approach, since the mock variant is imported in production code. I would like to have something like in Symfony, where implementation of abstractions can be defined in environmental service configurations.

Currently I have following abstraction:

import HttpERPAdapter from "./HttpERPAdapter";
import MockERPAdapter from "./MockERPAdapter"; // todo, find an abstraction solution to not deploy this in production
import httpClient from "common/HttpClient";

const create = () => {
    if (process.env.REACT_APP_ERP_API_URL === 'mock') {
        return new MockERPAdapter();
    }
    return new HttpERPAdapter(httpClient);
}

const erpAdapter = create();
export default erpAdapter;
  • The mock variant: Mainly used when developing GUI when I have not to rely on real api data, for faster development.
  • The productive variant: For for developing with real api data, and for the productive build

I am sure that a compilation in a production build will contain the mock class. This is what I want to prevent.

Any ideas on how to separate the mock implementation from the productive code, so that it will not be dumped in the productive build?

can we validate multiple functions inside if condition with AND operator using java script is there any other way to check multiple functions true?

I have added these functions and need return something based which function is returning true but it is not working.

//this is function1/
function A() {
  return true;
}

function B() {
  return true;
}

function C() {
  if ({
      {
        var -customJS - page_type_lookup
      }
    } === 'product') {
    var config = document.querySelector('#product-content > div.product-variations.clearfix > div.attribute.variant-dropdown > div.attribute-values-section > div.label.va-navSectionalOrientation').innerText;
    if (config.includes('Sectional Orientation')) {
      return true;
    } else {
      return false;
    }
  }
}
if (A() === true && B() === true && C() === true) {
  return 'A+ Content, RTA Product, Sectional Configurator';
} else if (A() === true && B() === true) {
  return 'A+ Content, RTA Product';

} else if (B() === true && C() === true) {
  return 'RTA Product, Sectional Configurator';
} else if (C() === true && A() === true) {
  return 'Sectional Configurator, A+ Content';
} else if (A() === true) {
  return 'A+ Content';
} else if (B() === true) {
  return 'RTA Product';
} else {
  return 'Sectional Configurator';
}
}

React JS setState not working, showing blank page

I am trying to create a count function in which I want counter to get increased by 1 when user click on button, but code is getting compiled successfully and react app is showing white blank page.

App.js:

import './App.css';
import Count from './Components/Count';

function App() {
  return (
    <div className='App'>
    <Count></Count>
    </div>
  );
}

export default App;

Count.js (inside src/Components Folder):

import React, {Component} from "react";

class Count extends Component{
    constructor(){
        super();
        this.state({
            count:0
        });
    }
    count(){
        this.setState({
            count : this.state.count + 1
        }
        );
    }
        render(){
            return(
                <div>
                    <h1>
                        {this.state.count}
                    </h1>
                    <button onClick={() => {this.count()}}>Increase Count</button>
                </div>
            );
        }
}
export default Count;

Slider to change slides on scroll

I am trying to implement the following setup:

When a user scrolls down my web page, I want scroll to function normally, until they reach a section where I have a slider. Once this section is in the viewport, the website should stop scrolling down the page, and the slider should scroll from slide 1 to slide 2. When the slides are finished, the page should continue to scroll as normal again.

The same should happen when the user is scrolling from bottom to top.

https://project-1-6122b1.webflow.io/slider

I have gotten it to mostly work on desktop, but unfortunately, it does not work on Mobile. The slides also just infinitely scroll. After slide 2, the page should cacrry on scrolling as normal.

<script>
    function debounce(func, wait, immediate) {
        var timeout;
        return function() {
            var context = this,
                args = arguments;
            var later = function() {
                timeout = null;
                if (!immediate) func.apply(context, args);
            };
            var callNow = immediate && !timeout;
            clearTimeout(timeout);
            timeout = setTimeout(later, wait);
            if (callNow) func.apply(context, args);
        };
    }

    var onScroll = debounce(function(direction) {
        if (direction == false) {
            $("#w-slider-arrow-right").trigger('tap');
        } else {
            $("#w-slider-arrow-left").trigger('tap');
        }
    }, 200, true);

    $('#slider').bind('wheel mousewheel', function(e) {
        e.preventDefault();
        var delta;
        if (typeof event != 'undefined' && event.wheelDelta) {
            delta = event.wheelDelta;
        } else {
            delta = -1 * e.originalEvent.deltaY;
        }
        onScroll(delta >= 0);
    });
</script>

How to test error handling functions in Javascript

I m trying to write unit test cases to handle error codes that are defined below. not sure how to achieve it.

module.exports = {
    Error: Err,
    BadRequest: function () {
        return new Err(400, 'Bad Request');
    },
    NotAcceptable: function () {
        return new Err(406, 'Not Acceptable');
    },
    NotAuthorized: function () {
        return new Err(401, 'Not Authorized');
    }
};

function Err(code, message) {
    assert(code, 'code');

    Error.call(this);
    Error.captureStackTrace(this, this.constructor);

    Object.defineProperty(this, 'code', {
        enumerable: true,
        value: code
    });

    this.reason = message;
}

Having trouble trying to access nested data [duplicate]

So I have a data structure like below and I’m trying to access inside tournaments the ‘_id’ Any help would be great. What would I need to console.log to get 29?

const sports = {
  "queryUrl": "config_tournaments/1/17",
  "doc": [{
    "event": "config_tournaments",
    "_dob": 1647341355,
    "_maxage": 600,
    "_configid": 12457,
    "data": {
      "tournaments": [{
        "_doc": "tournament",
        "_id": 29,
        "_sid": 1,
        "_rcid": 17,
        "_isk": 1,
        "_tid": 29,
        "_utid": 45,
        "name": "Bundesliga",
        "abbr": "BUN",
        "ground": null,
        "friendly": false,
        "seasonid": 84476,
        "currentseason": 84476,
        "year": "21/22",
        "seasontype": "21",
        "seasontypename": "Regular Season",
        "seasontypeunique": "68",
        "livetable": 57152,
        "cuprosterid": null,
        "roundbyround": true,
        "tournamentlevelorder": 1,
        "tournamentlevelname": "1st level",
        "outdated": false,
        "_sk": false
      }]
    }
  }]
}

console.log(sports.doc[0].data)

JavaScript static classes and methods

Help me solve this exercise:
Define a static method within the Person class which, given an object literal as input, instantiates a Person object

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  static fromObject() {
    
  }
}

const obj = {
  firstName: 'Mario',
  lastName: 'Rossi'
};

const person = Person.fromObject(obj);
console.log(`${person.firstName} ${person.lastName}`);

I have no idea! First time ever I add a static method to a class in JavaScript. I searched the internet but I still cannot solve it.

Why my value is not persisting in another page? specifically guest.js

Currently practicing the hook useContext and i am kinda confuse how this hook works.

the scenario is the generate OTP button is in the Login.js where the otpResult is rendered. the problem is i want my otpResult to show in the guest.js too,

This my React Context that i use in order to make a global variable.

import { useState, createContext, useContext } from "react";

const otpContext = createContext();
var dayjs = require("dayjs");
dayjs().format("HH:mm:ss");

export const OtpContextProvider = ({ children }) => {
  const [otpResult, setOtpResult] = useState();

  let startTime;
  let expirationTime;
  let otp = "";
  const generateOtp = (length, id) => {
    var characters =
      "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    var charactersLength = characters.length;

    for (var i = 0; i < length + 1; i++) {
      otp += characters.charAt(Math.floor(Math.random() * charactersLength));
    }
    console.log("the otp is: " + otp);
    setOtpResult(otp);
    startTime = dayjs().format("HH:mm:ss");
    expirationTime = dayjs().add(10, "m").format("HH:mm:ss");
  };

  const otpHandler = () => {
    generateOtp(3);
  };
  return (
    <otpContext.Provider value={{ otpResult, otpHandler }}>
      {children}
    </otpContext.Provider>
  );
};
export function useOtpContext() {
  return useContext(otpContext);
}

This is my Login.js component

import React, { useState } from "react";
import { useOtpContext } from "../context/context";

const Landing = () => {
  const { otpHandler, otpResult } = useOtpContext();
  const buttonHandler = () => {
    otpHandler();
  };

  return (
    <div className="">
      <header className="">
        <button onClick={buttonHandler}>Generate OTP: </button>
        <p>the otp result is : {otpResult}</p> <br />
        <p>Valid until {}</p>
      </header>
    </div>
  );
};

export default Landing;

This is my Guest.js

import React, { useEffect } from "react";
import { useOtpContext } from "../context/context";
const Guest = () => {
  const { otpHandler, otpResult, otp } = useOtpContext();

  useEffect(() => {
    console.log("the otp result on guest is : " + otpResult);
  }, [otpHandler]);

  return (
    <div>
      <>Otp result here : {otpResult}</>
    </div>
  );
};

export default Guest;

The App.js component

    import "./App.css";
import { OtpContextProvider } from "./context/context";
import { BrowserRouter, Routes, Route } from "react-router-dom";
import Landing from "./component/Landing";
import Guest from "./component/Guest";
function App() {
  return (
    <OtpContextProvider>
      <BrowserRouter>
        <Routes>
          <Route path="/" element={<Landing />} />
          <Route path="/guest" element={<Guest />} />
        </Routes>
      </BrowserRouter>
    </OtpContextProvider>
  );
}

export default App;

the login component

The guest component