Lazy Loading and Scroll to page (tag)

I ran into an issue on scroll to page where it is not accurately scrolling to the tag where I want it to scroll maybe because of lazy loading some images. I don’t want just to add offset value because of it would be different to each screen.

here’s my js code for scrolling

$('html, body').animate({
                scrollTop: $(".scroll-here").offset().top
            }, 2000);
            return false;

i’ve also added width and height to images but the seems not to work.

State becomes undefined after dispatch with UseReducer and UseContext

Goal: I am trying to toggle the visibility of a 3D model using React reducer and context. 3D rendering is done with React hooks version of a framework called Xeokit. Models are rendered into a canvas element (3DCanvas.js) by giving them as props to a Xeokit Viewer element (XKTModel.js).

The problem is, once a dispatch is sent, the state becomes undefined. The context works only with the default value given to the reducer. Doesn’t seem to matter which component sends the dispatch.

I have written into console the state for each component using the UseContext hook to see what is going on. Same thing with the reducer.

I did a lot of searching but could not find a similar issue being addressed. Can someone more experienced spot the mistake I have made?

Context creation:

import React from "react";

const ViewControlsContext = React.createContext()

export {ViewControlsContext as default}

Reducer:

const ViewControlsReducer = (state, action) => {
    switch (action.type) {
      case 'POPULATE_STATE':
          return action.state, console.log("populate dispatch: ", action, state)
      case 'TOGGLE_SITE_VISIBILITY':
        return {
            ...state,
            //site_visibility: !state.site_visibility
            //^commented out, as will cause an error because state undefined
        }, console.log("toggle dispatch: ", action, state)
      default:
        return state, console.log("default: ", action, state)
    }
  }

  export {ViewControlsReducer as default}

App:

import React from 'react';

import './App.scss'

import ThreeDeeCanvas from './Components/3DCanvas'

function App(){
  return (<div>
    <ThreeDeeCanvas />
  </div>)
};

export default App;

3DCanvas (component into which models are rendered, provides Context):

import React, { useEffect, useReducer } from 'react'
import { Container, Col, Row } from 'react-bootstrap'

import XKTModel from './XKTModel';
import ThreeDeeControls from './3DControls';
import LogoCanvas from './LogoCanvas'
import ViewControlsContext from '../Context/ViewControlsContext';
import ViewControlsReducer from '../Reducers/ViewControlsReducer';

const ThreeDeeCanvas = () => {

    const def = {
        site_visibility: false
    }

    const [viewControls, dispatch] = useReducer(ViewControlsReducer, def)

    useEffect(() => {
        dispatch({type: 'POPULATE_STATE', state: def})
        dispatch({type: 'POPULATE_STATE', state: def}) //test, with this state is undefined
    }, [])
    
    console.log("3dcanvas: ", viewControls)

    return (
        <div>
            <LogoCanvas/>
            <Col className='ThreeDeeWindow'>
            <ViewControlsContext.Provider value={{viewControls, dispatch}} >
                <XKTModel/>
                <ThreeDeeControls/>
            </ViewControlsContext.Provider>
            </Col>
        </div>
    )
}

export {ThreeDeeCanvas as default}

XKTModel (source and props for 3D models, uses Context):

import React, { useContext } from 'react';
import { navCubeSettings } from '../models';
import { XKTViewer } from 'xeokit-react';

import ViewControlsContext from '../Context/ViewControlsContext';
import { IFCObjectDefaultColors } from '../default_colors';

const mainModel = {
  id: 'main_model',
  src: './xkt/Showcase.xkt',
  metaModelSrc: './xkt/Showcase.json',
  edges: true,
  objectDefaults: IFCObjectDefaultColors,
}

const siteModel = {
  id: 'site_model',
  src: './xkt/ShowcaseSite.xkt',
  metaModelSrc: './xkt/ShowcaseSite.json',
  edges: true
}

const XKTModel = () => {

  const {viewControls} = useContext(ViewControlsContext)
  console.log("XKTModel: ", viewControls)

  //siteModel.visible = viewControls.site_visibility
  //^commented out, as will cause an error because state undefined
  
 
  return (
    <XKTViewer
    canvasID="modelCanvas"
    width={800}
    height={800}
    models={[mainModel, siteModel]}
    navCubeSettings={navCubeSettings}
    />
  ) 
};

export default XKTModel;

3DControls (Container for individual 3D controls):

import React, { useContext } from 'react'
import { Container, Col, Row } from 'react-bootstrap'

import ThreeDeeControl from './3DControl'
import ViewControlsContext from '../Context/ViewControlsContext'

const ThreeDeeControls = () => {

    const {viewControls} = useContext(ViewControlsContext)
    
    console.log("3dcontrols: ", viewControls)

    return (
        <Container className='ThreeDeeControls p-0 d-flex justify-content-between'>
            <ThreeDeeControl id='site' label='Show site'/>
        </Container>
    )
}

export {ThreeDeeControls as default}

3DControl (individual toggles for changing 3D view props, sends dispatch):

import React, {  useState, useContext, useReducer } from 'react'
import { Container, Form } from 'react-bootstrap'

import ViewControlsContext from '../Context/ViewControlsContext'


const ThreeDeeControl = ({id, label}) => {

    const {viewControls, dispatch} = useContext(ViewControlsContext)

    console.log("3dsinglecontrol: ", viewControls)

    const [isSwitchOn, setIsSwitchOn] = useState(false);

    const onSwitchAction = () => {
    setIsSwitchOn(!isSwitchOn);
    dispatch({type: 'TOGGLE_SITE_VISIBILITY'})
    }

    return (
            <Form className='ThreeDeeControl'>
                <Form.Check  
                    type="switch"
                    id={id}
                    label={label}
                    checked={isSwitchOn}
                    onChange={onSwitchAction}
                />
            </Form>
    )
}

export {ThreeDeeControl as default}

How to pass column paramter to datatables search through URL

I have successfully setup datatables with a search parameter to my datatbles table via URL. For example I can prefilter the search term on datatables by using the following URL.
abc.html?search=test

However I am not sure how to pass the parameter so that datatable is prefiltered by search term and topic value. Something like abc.com/?topic=my topic

My code shows me 3 results (since it searching my search terms) instead of 2 since there are only two my topics.
Please see the code I have on the datatables page below.

http://live.datatables.net/nitozucu/3/edit

JS code:

function getUrlVars() {
          var vars = [], hash;
          var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
          for(var i = 0; i < hashes.length; i++)
          {
              hash = hashes[i].split('=');
              vars.push(hash[0]);
              vars[hash[0]] = hash[1];
          }
          return vars;
      }

$(document).ready(function () {
var searchTerm = getUrlVars()['Topic'];
                var table = $('#myselector').DataTable({

orderCellsTop: true,
responsive: true,
paging: false,
      searching: true,
      lengthChange: false,
      bInfo: false,
search: {
        search: searchTerm
      },
      bSort: true,
                                          
              initComplete: function () {
            this.api().columns().every( function () {
                var column = this;
                var select = $('<select><option value=""></option></select>')
                    .appendTo( $("#myselector thead tr:eq(1) th").eq(column.index()).empty() )
                    .on( 'change', function () {
                        var val = $.fn.dataTable.util.escapeRegex(
                            $(this).val()
                        );
 
                        column
                            .search( val ? '^'+val+'$' : '', true, false )
                            .draw();
                    } );
 
                column.data().unique().sort().each( function ( d, j ) {
                    var val = $('<div/>').html(d).text();
select.append( '<option value="' + val + '">' + val + '</option>' );
                } );
            } );
        }
    } );
    });

HTML:

<!DOCTYPE html>
<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>

    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
    <script src="https://nightly.datatables.net/js/jquery.dataTables.js"></script>

    <meta charset=utf-8 />

  </head>
  <body>
    <table id="myselector" class="row-border stripe dataTable no-footer dtr-inline" role="grid" style=" width: 100%;"><thead>
<tr role="row">
<th class="filterhead">Date</th>
<th class="filterhead">Type</th>
<th class="filterhead">Topic</th>
</tr>

<tr>
<th>Date</th>
<th>Type</th>
<th>Topic</th>
</tr>

</thead><tbody>
<tr>
<td>Current</td>
<td>test</td>
<td>my topic</td>
</tr>

<tr>
<td>Current</td>
<td>test</td>
<td>my topic</td>
</tr>

<tr>
<td>Current</td>
<td>test</td>
<td>ABC</td>
</tr>

<tr>
<td>01/1997</td>
<td>test2</td>
<td>my topic</td>
</tr>

<tr>
<td>10/27/1993</td>
<td>test3</td>
<td>ABC</td>
</tr>



</tbody></table>
</div>

</html>

How to append a variable with base64 value to FormData?

I use Image-Cropper in my angular project. The cropped image is stored in a variable as follows:

.
.
croppedImage: any = '';
.
.
  imageCropped(event: ImageCroppedEvent) {
    this.croppedImage = event.base64;
  }
.
.
.

My current FormData is as follows:

const filedata = new FormData();
    filedata.append("file", this.selectedFile, this.selectedFile.name);
    this.http.post('https://localhost:5001/api/featuredpost/postimage/' + this.selectedPostId, filedata).subscribe(
      response => {
        console.log(response);
      }
    );

How can I append cropped image data instead of this.selectedFile, this.selectedFile.name. The current code uploads the original image, but I want to upload cropped one.

generic function to create an array of nested objects from a single object of arrays

This is a very specific problem but I have an object with arrays:

let rawData = {
    one: ["a", "a", "a", "b", "b", "b", "c", "c", "c"],
    two: [1,2,3,1,2,3,1,2,3],
    three: [1,4,9,3,9,7,6,5,5]
  }

and I want to write a generic function that will create a set of nested objects based on the first array (here a, but I’d like to make this function not dependent on a specific key.

In my first try I wrote a function that parses this into an array of objects:

dataframe_for_plot = (data) => {
  var length
  var names = []
  for (var name in data) {
        if (data.hasOwnProperty(name))
            names.push(name);
        length = rawData[name].length;
  }

    var results = [];
    var item;
    for (var row = 0; row < length; row++) {
        item = {};
        for (var col = 0; col < names.length; col++) {
            item[names[col]] = data[names[col]][row];
        }
        results.push(item);
    }
    return results;
}

Which yeilds

dataframe_for_plot(rawData)
[
  {one: "a", two: 1, three: 1},
  {one: "a", two: 2, three: 4},
  {one: "a", two: 3, three: 9},
  {one: "b", two: 1, three: 3},
  {one: "b", two: 2, three: 9},
  {one: "b", two: 3, three: 7},
  {one: "c", two: 1, three: 6},
  {one: "c", two: 2, three: 5},
  {one: "c", two: 3, three: 5},
]

But I want to build on this function to get my desired output where the first key is used to create objects based on the unique number of that key (3 in this case), and a new value key is created to contain a nested array of the other keys (two and three in this case, grouped together by one)

let desired_output = [
  {
    one:"a",
    values: [
      {two:1, three:1},
      {two:2, three:4},
      {two:3, three:9}
    ],
  },
    {
    one:"b",
    values: [
      {two:1, three:3},
      {two:2, three:9},
      {two:3, three:7}
    ],
  },
    {
    one:"c",
    values: [
      {two:1, three:6},
      {two:2, three:5},
      {two:3, three:5}
    ],
  }
]

I think my function is a good start, but I need a little help working on the nested part 2! Thanks!

Mutation observer on iframe is not fired when used as target in a form for php output

Mutation observer on iframe is not fired when used as target in a form for php output.

When change is made from within the java script with

targetNode.innerHTML = 'xxx';

the observer fires.

When the output of a php file is displayed by the form in the iframe,
nothing happens.

What am I doing wrong ?

Here is thet HTML/JavaScript

<!DOCTYPE html>
<html>
    <head>
        <title>Mutation Test</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <form action="dummy.php" target='iframe'>
            <input type='submit'>
        </form>
        <iframe name='iframe'></iframe>
        <script >
            targetNode = document.querySelector('IFRAME').contentDocument.body;
            config = {childList: true, subtree: true, attributes: true};
            callback = function (mutationsList, observer) {
                alert('mutation');
            };
            observer = new MutationObserver(callback);
            observer.observe(targetNode, config);

            //targetNode.innerHTML = 'xxx'; //<= this will trigger a mutaion !!!!!!!!!!!!!

        </script>
    </body>
</html>

Here is the php file used as the action for the form

<?php
echo "dummy.php";

I have this React Invalid Hook Call Error that I’m getting and I wanted to see if I was breaking the rules of hooks or is it something else?

I’m getting the error below.

Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:

  1. You might have mismatching versions of React and the renderer (such as React DOM)
  2. You might be breaking the Rules of Hooks
  3. You might have more than one copy of React in the same app

See (link I couldn’t add) for tips about how to debug and fix this problem.

  1. You might have mismatching versions of React and the renderer (such as React DOM)

Here is my code. Is it breaking rules of hooks or is the issue something else?

import React, { useEffect } from 'react';
import PropTypes from 'prop-types';
import { useData } from 'useData';

export const checkReference = ({
  refId,
}) => {
  const data = useData(); //useContext hook
  let refData = {};
  if (refId) refData = data.getReference(refId);

  useEffect(() => {
    console.log('INITIAL LOGIC');
    if (refData.parameter){
      console.log('SECONDARY LOGIC', refData);
    }
  }, [])
  
  checkReference.propTypes = {
    refId: PropTypes.string,
  }
  checkReference.defaultProps = {
    refId: null,
  }
}

I am calling it from another file using
checkReference('page-name');

Typescript issue with using multiple types

Been racking my brain for hours on this, basically I have a bunch of different types defined like this:

export type SharedAPIProps = {
  id: string;
};

export type ButtonAPIProps = SharedAPIProps & {
  type: "paragraph--button";
  field_title: string;
};

export type SlideAPIProps = SharedAPIProps & {
  type: "paragraph--slide";
  field_slides: []
};

export type allAvailableComponents = ButtonAPIProps | SlideAPIProps;


export type ButtonProps = {
  title: string;
}

export type SlideProps = {
  slides: [];
} 

export type allCleanedProps = ButtonProps | SlideProps;

Then I have a function to convert an API response to a clean version:

export const toCleanProps(component: allAvailableComponents): allCleanedProps => {
  const { type } = component;
  
  const convertedProps: allCleanedProps = {}

  switch (type) {
    case "paragraph--button":
      convertedProps.title = component.field_title;
      break;
    case "paragraph--slide":
      convertedProps.slides = component.field_slides;
      break;
  }

  return convertedProps;
}

Issue is I’m getting Typescript errors on every property of the convertedProps. When I have just a single type defined in allComponentProps like:

export type allAvailableComponents = ButtonAPIProps;

I don’t get the errors on the paragraph--button convertedProps properties, but of course do on the paragraph--slide convertedProps properties.

New to Typescript, so bear with me, I’m probably missing something simple here and tried a bunch of different things, but none work.

Error message being those props don’t exist on the defined types.

Function which increments a value by 125 from based on an array Index – javascript

I want to generate a number in increments of 125 from index 1 based on the index while looping over an array. If the index is 0, it should print 100. If the index is 1, 100 + 125 = 225, index is 2, 225 + 125 = 350 and so on. How do I do this? This is what I have.

const rows = 5;

const rowArray = new Array(rows).fill(' ');

const result = rowArray.map((i, index) => {
  if (index === 0) {
    return 100
  }
  if (index === 1) {
    return 225
  }
  return index * 100 + 125

})

console.log(result)

Expected output:

[100, 225, 350, 475, 600, 725]

Can someone help me out with this math? Thanks.

Failed to load resource: the server responded with a status of 404 () – React deploy can’t find files and i18 translate

I am having troubles deploying my portfolio.
I used the i18-reactnext library to translate the code and everything works fine in development server, but when i do the build i get the errors.
i tried deploying in git hub pages, in vercel and even in the preview i got the same errors.

Error i got in the console.

    import React from 'react';
import ReactDOM from 'react-dom/client';
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import HttpApi from 'i18next-http-backend';

import App from './views/App';
import './reset.css';
import './index.css';
import 'bootstrap-icons/font/bootstrap-icons.css';
import 'flag-icon-css/css/flag-icons.min.css';

i18n
   .use(initReactI18next)
   .use(LanguageDetector)
   .use(HttpApi)
   .init({
      supportedLngs: ['pt', 'en'],
      fallbackLng: 'pt',
      detection: {
         order: ['cookie', 'localStorage', 'htmlTag', 'path', 'subdomain'],
         caches: ['cookie'],
      },
      backend: {
         loadPath: '../assets/locales/{{lng}}/translation.json',
      },
   });

ReactDOM.createRoot(document.getElementById('root')).render(
   <React.StrictMode>
      <App />
   </React.StrictMode>
);

Can you convert each element in an array as its own individual string? [duplicate]

const removeDuplicates = arr => {
    for (let i = 0; i < arr.length; i++) {
        if (typeof arr[i] === "string") {
            let lowerCaseArr = arr.toString().toLowerCase().split(" ");
            return lowerCaseArr;
        }
    }
}

console.log(removeDuplicates(["Hello", "Hi", "How are you", "Hi", "Hello"]));

My goal is to convert the passed array into a string for each element that is lower-cased. But when .toString is called on the array, the array is returned as one whole string like this:

"Hello,Hi,How are you,Hi,Hello"

I want it returned like this, as each individual string:

"hello", "hi", "how are you", "hi", "hello",

So that when I convert it back to an array, it has its same structure as before but lower cased:

["hello", "hi", "how are you", "hi", "hello"]

The current methods that I use get this result:

[
“hello,hi,how”,
“are”,
“you,hi,hello”
]

Is it possible to do this?

passing value from one page to another using input “type=text” element in javascript

page name 3.html

<html>
    <body>
<form action="4.html" onSubmit="cal()">
    <table>
        <tr>
            <td><input type="text" id="sen"/></td>
            <td><input type="submit" value="tap me"/></td>
        </tr>
    </table>
</form>
</body>
<script>
    function call(){
        var a = document.getElementById("sen").value;
        localStorage.setItem("a",a);
    }
</script>
</html>

page name 4.html

<html>
    <body>
        <table>
    <tr>
        <td><p id="r"></p></td>
    </tr>
</table>
</body>
<script>
    var get = localStorage.getItem('sen');
    alert(get);
    document.getElementById("r").innerHTML=get;
</script>
</html>

i am trying to pass value from 3.html to 4.html but it is passing null value.
why is it passing the null value?
how to resolve this error?

Chrome Extension – Function to swap domain in URL

I’m totally new to javascript and chrome extensions, I’m sorry for any stupid questions.

I’m building a simple chrome extension (no UI) that will replace api.website.com with test.website.com, anytime a link is clicked or url is entered containing api.website.com.

I’m trying to maintain any additional text or slugs after api.website.com too.

For example:

  • api.website.com/testing/slug

becomes

  • test.website.com/testing/slug

I’m trying to use chrome.webRequest.onBeforeRequest.addListener from this page because it seems quick and efficient.

I’m also trying to use parts from each of these pages:

manifest.json

    {
      "name": "Domain Redirect",
      "description": "Replace domain in urls",
      "version": "1.0.0",
      "minimum_chrome_version": "9",
      "manifest_version": 2,
      "background": {
        "scripts": ["background.js"]},
      "permissions": [
        "webRequest",
        "*://api.website.com/"
      ]
    }

background.js

var host = "api.website.com";
chrome.webRequest.onBeforeRequest.addListener(
    function(details) {
         return {redirectUrl: host + details.url.match(/^https?://[^/]+([Ss]*)/)[1]};
    },
    {
        urls: [
            "*://api.website.com/"
        ],
        types: ["main_frame", "sub_frame", "stylesheet", "script", "image", "object", "xmlhttprequest", "other"]
    },
);

I’m not sure where to put test.website.com in the code or how to proceed with the redirect after replacing the domain in the url. I appreciate any insight anyone’s willing to offer.

MathJax layout adjustments still going on when subsequent scripts are executed – How to run them after the rendering is really fixed?

My Android app loads an XHTML file into a WebView.

When the page is finished loading some scripts are called.

The HTML page contains MathML or other math code that is to be precessed by an injected MathJax script.

String scriptText=
                    "MathJax.Hub.Config({ "
                    + "showMathMenu: false, "
                    + "jax: ['input/TeX','output/HTML-CSS'], "
                    + "showProcessingMessages: false, "
                    + "messageStyle: 'none', "
                    + "extensions: ['tex2jax.js'], "
                    + "TeX: { extensions: ['AMSmath.js','AMSsymbols.js',"
                    + "'noErrors.js','noUndefined.js'] } "
                    + "});";

            
String js_command = "var newScript = document.createElement("script");"
+"newScript.setAttribute('type','text/x-mathjax-config');"
+"var inlineScript = document.createTextNode(""+scriptText+"");"
+"newScript.appendChild(inlineScript);"
+"document.body.appendChild(newScript);"

+"newScript = document.createElement("script");"
+"newScript.setAttribute('type','text/javascript');"
+"newScript.setAttribute('src','file:///android_asset/MathJax/es5/tex-mml-svg.js');"
+"document.body.appendChild(newScript);";

The injection of MathJax code is successful and the code is execute, rendering the math symbols correctly.

Also refer to My other question about the MathJax script injection

The fact is that other scripts have to be executed and they have to run after the MathJax rendering.

The MathJax script has neither the async or the defer attribute because I need that the subsequent scripts are executed after the real rendering of the math symbols. But I tried adding the defer condition and nothing changes.

Indeed I noticed that when the script has finished running, so the next JavaScript is going to be executed, the rendering still goes on for some elements, some of which can slightly change size, for example. This leads to some issues in my app, that is heavily based on exact positioning.

I browsed the JavaScript file that is used in my app as MathJax code and I saw that it is all on one line, and nothing can be understood because it is full of boiler-plate instructions.

Also I did not find the corresponding source code in a plain form in the github repository, although the folder is there.

My question:
I would like to know how to execute the MathJax operations in a real sync fashion, so that the subsequent JavaScript code is executed when all the real rendering is fixed as to positions and dimensions.

I am also eager to edit the MathJax script inserting calls to other scripts inside a specific function so to be sure they are executed at the end.

Construct a new array based on filter results of an API [duplicate]

I have an API that returns a list of brands which is an array of objects. I tried to filter out and kept only specific ones. I can see that it ran twice on the console, but when I tried to push those found brands to the brandNames array, I can’t.

let brandNames = []
for (let j = 0; j < brands.length; j++) {

    let code = brands[j]

    let brands = {
        api: 'brands',
        filters: [`code:${code}`],
    }

    axios.post(window.URL, brands).then((response) => {
 
        let brand = response.data.groups.filter((item) => {
            return item.brands[0].code == code
        })

        console.log('brand', brand) //ran 2 times 

        if (brand) {
            brandNames.push(brand[0].brands[0].name) // push into array 
        }
    })
}

console.log(brandNames) // got [] empty 

enter image description here

I have a feeling that things went out of context somewhere, but I have no idea where it is ….