Dynamically set div position after closing it

I’m trying to save div position in place that I’m closing it, so after I reopen that div it will appear in place it was when I clicked CLOSE button. I’ve tried set style with js setAttribute() in dragMoveListener function, using props in styled components and passing them to Window styled.div with useState hook and none of it worked Here’s the code:

Dragging.js:

import interact from "https://cdn.interactjs.io/v1.10.11/interactjs/index.js";
import styled from "styled-components";

const Window = styled.div`
  position: fixed;
  width: 500px;
  height: 300px;
  border-radius: 8px;
  border: solid black;
  padding: 20px;
  background-color: white;
  color: black;
  z-index: 10;
  touch-action: none;
  box-sizing: border-box;
  left: 0;
  right: 0;
  margin-left: auto;
  margin-right: auto;
`;

const Dragging = ({ children }) => {
  interact(".resize-drag")
    .resizable({
      edges: { left: true, right: true, bottom: true, top: true },

      listeners: {
        move(event) {
          var target = event.target;
          var x = parseFloat(target.getAttribute("data-x")) || 0;
          var y = parseFloat(target.getAttribute("data-y")) || 0;

          target.style.width = event.rect.width + "px";
          target.style.height = event.rect.height + "px";

          x += event.deltaRect.left;
          y += event.deltaRect.top;

          target.style.transform = "translate(" + x + "px," + y + "px)";

          target.setAttribute("data-x", x);
          target.setAttribute("data-y", y);
        },
      },
      modifiers: [
        interact.modifiers.restrictSize({
          min: { width: 200, height: 200 },
        }),
      ],

      inertia: true,
    })
    .draggable({
      inertia: true,
      autoScroll: true,
      listeners: {
        move: dragMoveListener,
      },
    });

  function dragMoveListener(event) {
    var target = event.target;
    var x = (parseFloat(target.getAttribute("data-x")) || 0) + event.dx;
    var y = (parseFloat(target.getAttribute("data-y")) || 0) + event.dy;

    target.style.transform = "translate(" + x + "px, " + y + "px)";

    target.setAttribute("data-x", x);
    target.setAttribute("data-y", y);
  }

  return <Window className="resize-drag">{children}</Window>;
};

export default Dragging;

DeviceModal.js:

import React, { useEffect, useState } from "react";
import { Loader, Button, Header } from "semantic-ui-react";
import styled from "styled-components";
import DeviceInfo from "./DeviceInfo";
import Dragging from "./Dragging";

const WindowBody = styled.div`
  padding: 10px;
  border-top: 1px solid #eee;
  border-bottom: 1px solid #eee;
`;

const DeviceModal = (props) => {
  const [data, setData] = useState();
  const id = props.id - 1;

  useEffect(() => {
    const fetchDevice = async () => {
      try {
        const response = await fetch(
          `http://localhost:5000/api/v1/devices/${id}`
        );
        const responseData = await response.json();
        setData(responseData);
      } catch (err) {
        if (err.value) {
          console.log(err);
        }
      }
    };

    fetchDevice();
  }, [id]);

  if (!props.show) {
    return null;
  }

  if (data) {
    return (
      <Dragging>
        {
          <>
            <Header>Info:</Header>
            <WindowBody>
              <DeviceInfo data={data} />
            </WindowBody>
            <Button style={{ padding: "2px" }} onClick={props.onClose}>
              CLOSE
            </Button>
          </>
        }
      </Dragging>
    );
  } else {
    return <Dragging>{<Loader />}</Dragging>;
  }
};

export default DeviceModal;

I tried lot of things but none of those worked so please help.

How to use only hover or only focus in SCSS?

I have my Vue input component. This component has such styles:

.basic-input:hover { box-shadow: 0 0 5px $maincolor; }
.basic-input:focus { border: 0.5px solid $maincolor; }

As you can see it has box shadow on hover and border on focus. Here is the problem, if I have focus and hover at the same time, I has box shadow and border.

I want to make it work like this – if it’s hover or focus, it has to be like it is, but If it has focus and hover at the same time, I want to use only border. I was trying to do this like that, but it doesn’t work:

.basic-input:focus .basic-input:hover { border: 0.5px solid $maincolor; }

Error: Cannot find module ‘core-js/modules/es.object.define-property.js’

error – Error: Cannot find module ‘core-js/modules/es.object.define-property.js’
Require stack:

  • E:JibonvaiPixer-Laraveladminnode_modulesnext-i18nextdistcommonjsindex.js
  • E:JibonvaiPixer-Laraveladmin.nextserverpages_document.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistserverrequire.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistserverload-components.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildutils.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildoutputstore.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildoutputindex.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistclinext-dev.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbinnext
    Error: Cannot find module ‘core-js/modules/es.object.define-property.js’
    Require stack:
  • E:JibonvaiPixer-Laraveladminnode_modulesnext-i18nextdistcommonjsindex.js
  • E:JibonvaiPixer-Laraveladmin.nextserverpages_document.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistserverrequire.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistserverload-components.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildutils.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildoutputstore.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildoutputindex.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistclinext-dev.js
  • E:JibonvaiPixer-Laraveladminnode_modulesnextdistbinnext
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.mod._resolveFilename (E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildwebpackrequire-hook.js:171:28)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:1005:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object. (E:JibonvaiPixer-Laraveladminnode_modulesnext-i18nextdistcommonjsindex.js:3:1)
    at Module._compile (node:internal/modules/cjs/loader:1103:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1155:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12) {
    code: ‘MODULE_NOT_FOUND’,
    requireStack: [
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnext-i18nextdistcommonjsindex.js’,
    ‘E:JibonvaiPixer-Laraveladmin.nextserverpages_document.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistserverrequire.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistserverload-components.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildutils.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildoutputstore.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistbuildoutputindex.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistclinext-dev.js’,
    ‘E:JibonvaiPixer-Laraveladminnode_modulesnextdistbinnext’
    ]
    }

package.json

{
“name”: “@pixer/admin-rest”,
“version”: “1.0.0”,
“private”: true,
“scripts”: {
“dev”: “next dev -p 3002”,
“build”: “next build”,
“start”: “next start -p 3002”
},
“dependencies”: {
“@fontsource/open-sans”: “4.5.2”,
“@headlessui/react”: “1.4.2”,
“@hookform/resolvers”: “2.8.4”,
“@reach/portal”: “0.16.2”,
“@react-google-maps/api”: “2.7.0”,
“@react-pdf/renderer”: “2.0.21”,
“apexcharts”: “3.31.0”,
“axios”: “0.24.0”,
“body-scroll-lock”: “4.0.0-beta.0”,
“camelcase-keys”: “7.0.1”,
“classnames”: “2.3.1”,
“cookie”: “0.4.1”,
“dayjs”: “1.10.7”,
“framer-motion”: “5.3.3”,
“jotai”: “1.4.6”,
“js-cookie”: “3.0.1”,
“lodash”: “4.17.21”,
“next”: “12.0.7”,
“next-pwa”: “5.4.4”,
“next-seo”: “4.28.1”,
“overlayscrollbars”: “1.13.1”,
“overlayscrollbars-react”: “0.2.3”,
“rc-pagination”: “3.1.14”,
“rc-progress”: “3.1.4”,
“rc-table”: “7.21.0”,
“react”: “17.0.2”,
“react-apexcharts”: “1.3.9”,
“react-datepicker”: “4.5.0”,
“react-dom”: “17.0.2”,
“react-dropzone”: “11.4.2”,
“react-hook-form”: “7.20.5”,
“react-laag”: “2.0.3”,
“react-phone-input-2”: “2.14.0”,
“react-query”: “3.34.0”,
“react-scroll”: “1.8.4”,
“react-select”: “5.2.1”,
“react-toastify”: “8.1.0”,
“react-use”: “17.3.1”,
“swiper”: “7.3.1”,
“yup”: “0.32.11”
},
“devDependencies”: {
“@types/body-scroll-lock”: “3.1.0”,
“@types/js-cookie”: “3.0.1”,
“@types/lodash”: “4.14.177”,
“@types/node”: “16.11.11”,
“@types/overlayscrollbars”: “1.12.1”,
“@types/react”: “17.0.37”,
“@types/react-datepicker”: “4.3.2”,
“autoprefixer”: “10.4.0”,
“next-i18next”: “10.0.1”,
“postcss”: “8.4.4”,
“tailwindcss”: “2.2.19”,
“tailwindcss-rtl”: “0.8.0”,
“typescript”: “4.5.2”
}
}

How can I run a JavaScript function when the URI source of an image renders?

Background

My big-picture goal is to display an image such that the following conditions are satisfied:

  • The entire viewport is filled by the image
  • At least one dimension of the image fits within the viewport
  • The image is not stretched

My solution is contained in the function updateRatioSettings, which works as follows:

  1. Determine the aspect ratios of the source image (using naturalWidth and naturalHeight) and the viewport
  2. If the viewport is wider than the image, width = "100%" and height = "auto".
  3. If the image is wider than the viewport, height = "100%" and width = "auto".

This works!

The Problem

Now I just need to get updateRatioSettings to run when either of the aspect ratios changes. I have a working connection to the resize event of window, so now I just need to figure out how to make the function run when I change the image source.

Each of the below code snippets shows a square centered in a horizontal viewport. A working solution will show the entire viewport filled with this nice grey color.

Attempt #1

My first strategy was to call updateRatioSettings immediately after setting img.src. However, I ran into an issue where sourceRatio, which is calculated as img.naturalWidth / img.naturalHeight, printed as NaN.

// function to listen for window size changes and move image accordingly
let img;
let windowWider = false; // assume the screen is some ratio narrower than the image... to start at least
let ratioUpdateReady = true; // debounce variable

function updateRatioSettings() {
    // if the function is running, don't run the function
    if (ratioUpdateReady) {
        ratioUpdateReady = false;
        // begin debounced code
        
        const sourceRatio = img.naturalWidth / img.naturalHeight;
        const windowRatio = window.innerWidth / window.innerHeight;
        console.log("sourceRatio: " + sourceRatio, "windowRatio: " + windowRatio);
        if (windowRatio > sourceRatio != windowWider) { // if something has changed
            windowWider = !windowWider // log the new status
            if (windowWider) {
                // settings for window aspect ratio > source aspect ratio
                img.style.width = "100%";
                img.style.height = "auto";
            } else {
                // settings for source aspect ratio > window aspect ratio
                img.style.height = "100%";
                img.style.width = "auto";
            }
        }
        
        // end debounced code
        ratioUpdateReady = true;
    }
}

document.addEventListener('DOMContentLoaded', function(){
    // identify the element containing the image
    img = document.getElementById("background");
    
    // load an initial image
  (function (){ // this normally executes after sending a request to another part of the chrome extension
    const uri = "data:image/bmp;base64,Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAAAAADDDgAAww4AAAAAAAAAAAAAQEBAAA=="; // this is the string returned by the extension in my test case
        img.src = uri;
        updateRatioSettings(); // this gets a sourceRatio that is NaN
  })()
    
    // set up an event to update the ratio settings when the window resizes
    // commenting out for the purpose of this question, since it doesn't need debugging
    // window.addEventListener('resize', updateRatioSettings);
});
html,body{
    margin:0;
    height:100%;
    overflow:hidden;
}
img{
    height:100%;
    width:auto;
    position:absolute;
    top:-100%; bottom:-100%;
    left:-100%; right:-100%;
    margin:auto;
}
<html>
    <head>
        <title>New tab</title>
    </head>
    <body>
        <img id="background" src="" alt="">
    </body>
</html>

Attempt #2

Here I attempted to use image.onLoad to run updateRatioSettings when the image URI is loaded.

// function to listen for window size changes and move image accordingly
let img;
let windowWider = false; // assume the screen is some ratio narrower than the image... to start at least
let ratioUpdateReady = true; // debounce variable

function updateRatioSettings() {
    // if the function is running, don't run the function
    if (ratioUpdateReady) {
        ratioUpdateReady = false;
        // begin debounced code
        
        const sourceRatio = img.naturalWidth / img.naturalHeight;
        const windowRatio = window.innerWidth / window.innerHeight;
        console.log("sourceRatio: " + sourceRatio, "windowRatio: " + windowRatio);
        if (windowRatio > sourceRatio != windowWider) { // if something has changed
            windowWider = !windowWider // log the new status
            if (windowWider) {
                // settings for window aspect ratio > source aspect ratio
                img.style.width = "100%";
                img.style.height = "auto";
            } else {
                // settings for source aspect ratio > window aspect ratio
                img.style.height = "100%";
                img.style.width = "auto";
            }
        }
        
        // end debounced code
        ratioUpdateReady = true;
    }
}

document.addEventListener('DOMContentLoaded', function(){
    // identify the element containing the image
    img = document.getElementById("background");
    
    // load an initial image
  (function (){ // this normally executes after sending a request to another part of the chrome extension
    const uri = "data:image/bmp;base64,Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAAAAADDDgAAww4AAAAAAAAAAAAAQEBAAA=="; // this is the string returned by the extension in my test case
    img.onLoad = updateRatioSettings; // this is the function I want to run when naturalWidth and naturalHeight have updated
        img.src = uri; // updateRatioSettings is not called
  })()
    
    // set up an event to update the ratio settings when the window resizes
    // commenting out for the purpose of this question, since it doesn't need debugging
    // window.addEventListener('resize', updateRatioSettings);
});
html,body{
    margin:0;
    height:100%;
    overflow:hidden;
}
img{
    height:100%;
    width:auto;
    position:absolute;
    top:-100%; bottom:-100%;
    left:-100%; right:-100%;
    margin:auto;
}
<html>
    <head>
        <title>New tab</title>
    </head>
    <body>
        <img id="background" src="" alt="">
    </body>
</html>

Attempt #3

Next, I tried using a MutationObserver to watch for the point at which naturalWidth and naturalHeight actually update, then run updateRatioSettings in repsonse. Like in Attempt #2, updateRatioSettings never actually ran.

// function to listen for window size changes and move image accordingly
let img;
let windowWider = false; // assume the screen is some ratio narrower than the image... to start at least
let ratioUpdateReady = true; // debounce variable

function updateRatioSettings() {
    // if the function is running, don't run the function
    if (ratioUpdateReady) {
        ratioUpdateReady = false;
        // begin debounced code
        
        const sourceRatio = img.naturalWidth / img.naturalHeight;
        const windowRatio = window.innerWidth / window.innerHeight;
        console.log("sourceRatio: " + sourceRatio, "windowRatio: " + windowRatio);
        if (windowRatio > sourceRatio != windowWider) { // if something has changed
            windowWider = !windowWider // log the new status
            if (windowWider) {
                // settings for window aspect ratio > source aspect ratio
                img.style.width = "100%";
                img.style.height = "auto";
            } else {
                // settings for source aspect ratio > window aspect ratio
                img.style.height = "100%";
                img.style.width = "auto";
            }
        }
        
        // end debounced code
        ratioUpdateReady = true;
    }
}

const watchingAttributes = ["naturalWidth", "naturalHeight"];

document.addEventListener('DOMContentLoaded', function(){
  // identify the element containing the image
  img = document.getElementById("background");

  // set up the image resize listener
  function processMutation(mutationRecord) {
    if (watchingAttributes.includes(mutationRecord.attributeName)) {
      updateRatioSettings();
    }
  }
  let watcher = new MutationObserver((mutations) => {
    mutations.forEach(processMutation);
  });
  watcher.observe(img, {
    attributes: true
  });

  // load an initial image
  (function (){ // this normally executes after sending a request to another part of the chrome extension
    const uri = "data:image/bmp;base64,Qk06AAAAAAAAADYAAAAoAAAAAQAAAAEAAAABABgAAAAAAAAAAADDDgAAww4AAAAAAAAAAAAAQEBAAA=="; // this is the string returned by the extension in my test case
    img.src = uri;
  })()
    
  // set up an event to update the ratio settings when the window resizes
  // commenting out for the purpose of this question, since it doesn't need debugging
  // window.addEventListener('resize', updateRatioSettings);
});
html,body{
    margin:0;
    height:100%;
    overflow:hidden;
}
img{
    height:100%;
    width:auto;
    position:absolute;
    top:-100%; bottom:-100%;
    left:-100%; right:-100%;
    margin:auto;
}
<html>
    <head>
        <title>New tab</title>
    </head>
    <body>
        <img id="background" src="" alt="">
    </body>
</html>

Conclusion

So… what do I do now?

Add php into js urlencoded.append [duplicate]

I’m pulling customer session data like so:

get('CustomerModelSession');
    if($customer_session->isLoggedIn()) 
    {
        
echo   "

".$customer_session->getCustomer()->getId();


echo   "

".$customer_session->getCustomer()->getName()";


echo   "

".$customer_session->getCustomer()->getEmail()";


echo   "

".$customer_session->getCustomer()->getGroupId()";

How do I add php variables from the session data above into the urlencoded.apend?

var urlencoded = new URLSearchParams();
urlencoded.append("email", "[email protected]");
urlencoded.append("tag_string", "VP");

urlencoded.append("first_name", "nate");
urlencoded.append("last_name", "davis");
urlencoded.append("addresses[0][address1]", "124 Main");

I’m assuming it’s just like this?

urlencoded.append("first_name", "<?php echo ".$customer_session->getCustomer()->getName()"; ?>");

Any help would be greatly appreciated.

How to watch the content of a div?

I need to watch the content of a div on my “shop” page that is the number of items added to a cart. The content of this div is being populated from third-party javascript and only on one page of my site.

I need to take this value when it’s updated by the third-party script, and place it in another part of my html, in a separate component, that exists on every page. (currently the cart only shows on the shop page, but I want it to show in the header).

What is the best approach to do this?

I believe I will need to make an ajax call to the ‘shop’ page and check the innerHTML of the cart item count div, then populate that value. This allows me to pull it initially, but then I would still need to watch that value as people add items to the cart (only from the shop page).

Thank you for pointing me in the right direction.

How to dewarp fisheye WebRTC streaming in javascript?

I have an AntMedia server with a stream source from a RTSP fisheye camera (Cisco MV32).
I need to consume this broadcast (through WebRTC) from an Angular application, but I need an interactive dewarped view, not the distorted fisheye view.
What are the best practices to accomplish this? What would be the best js plugins?
Thanks in advance.

How to form one string array based on two other arrays using map in ES5?

I am writing a simple js/es5 script to combine all the strings in a CWL. The CWL only supports ES5, so there are many functions/features from ES6 cannot be used. I am not familiar with js in general.

For a minimal example:

var arr1 = ["a", "b"]
var arr2 = ["111", "222"]

Expected result:

["a_111", "b_111", "a_222", "b_222"] // order doesn't matter

I tried this way, but it did not work and returned [null, null]

arr1.map(function(x) {
  arr2.map(function(y) {
    return x + "_" + y;
  });
});

JS – Map/Array choice when both can do the same task

This is probably more of an opinion based question. But recently on a project I have seen that Map is always used over array.

My question is when would you ever use an array over a Map?

Note I mean in cases where an array would work as well as a Map.

i.e. storing data, checking it exists, and deleting it.

example here:

// Array
const teams = [];

if (teams.includes(team.id)) {
  return;
}

teams.push(team.id);

// do stuff

teams = teams.filter(
  (id) => id !== team.id
);


// Map
const teams = new Map();

if (teams.has(team.id)) {
  return;
}

teams.set(team.id, team.id);
// do stuff

teams(team.id);

As I understand Map is more performant, you also get methods like get, set, delete which are useful.

If faced with the task above what would people use and why?

Using JavaScript Variable in Thymeleaf

Lets say for example I have a variable b and c in:

<script th:inline="javascript">
let c = 20;
let b = 30;
document.getElementById("b").innerHTML = b;
        document.getElementById("c").innerHTML = c;
</script>

When I try to print them out on my page with :

 <h1>"The value for b is: " <span id="b"></span></h1>
<h1>"The value for c is: " <span id="c"></span></h1>

This works and the values of these varaibles are shown on the page.
Now that I’m using Thymeleaf and SPring I have a Controller methode like this:

     @GetMapping("/test")
        public String test( double val,  double val2,
                                     @RequestParam double rand, Model model) {
            model.addAttribute("val", val);
            model.addAttribute("val2", val2);
            model.addAttribute("rand", rand);
            model.addAttribute("distance", distance);
     
System.out.println(val);
        System.out.println(val2);
            return "/Test";
        }

I want to input only the rand, val and val2 should have the values from the JavaScript variables(b and c):

<form th:action="@{/test}"  method="get"><br>

    <input type="text" id="b" th:name="val" " th:value="${b}">
    <input type="text" id="c" th:name="val2" " th:value="${c}">



    <label for="rand">rand:</label>
    <input type="number" id="rand" th:name="rand" placeholder="rand" th:default="0"><br>




    <input type="submit" value="Submit" onclick="add()">
    <input type="reset" value="Reset">

</form>

But I am not getting the correct values from the JavaScript code.So I want to assign the variables b and c to the variables val and val2 so that I only need to input the request parameter rand.
Has anyone a solution for this.I looked it up and all the cases were that they wanted to assign the Thymeleaf variable in the script and not the other way around.
Thanks in advance

Trying to filter an object in javascript using lodash

I have some data like this, it’s more complex than this but this is the basic structure.

    {
        "AUDI": {
            "Id": "3",
            "Name": "AUDI",
            "Models": {
            "A1": [
                {
                "Model": "A1",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                },
                {
                "Model": "A1",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                }
            ],
            "A3": [
                {
                "Model": "A3",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                }
            ]
            }
        },
        "BMW": {
            "Id": "6",
            "Name": "BMW",
            "Models": {
            "1 SERIES": [
                {
                "Model": "1 SERIES",
                "TransmissionName": "Manual",
                "FuelTypeName": "Diesel"
                },
                {
                "Model": "1 SERIES",
                "TransmissionName": "Manual",
                "FuelTypeName": "Petrol"
                }
            ]
            }
        }
    }

I’m trying to filter the object down using a number of possible variables.

This is the code I’ve got so far:

    const newObj = _
    .chain(o).pickBy((o) => {
        if (makeId != null) {
            return o.Id == makeId // Corresponding to the Id value
        } else {
            return o
        }

    }).forEach((o) => {
        if (model != null) {
            return o.Models.Model == model // Corresponding to the Model value within the Models array
        } else {
            return o
        }

    }).value()

The first bit works (IE the Make selection), and I know I’m doing something fundamentally wrong on the .forEach part, but it just keeps returning the whole of the Make object, IE all the AUDIs or all the BWMs.

I would like to then be able to go on and filter by Model EG. is it petrol, is it a manual etc.

Would really appreciate some pointers please. Been trying to get this to work all day.

Thanks.

How to generate barcode inside mustache template – React/JS

Need to find a way to display a generated barcode inside a mustache template. Currently working with https://github.com/lindell/JsBarcode to generate the barcodes.

The syntax used for JsBarcode has me a bit confused as to how to pass the completed SVG code into the mustache template.

Using JSBarcode I render this barcode: barcode

via JsBarcode using:

 const data = '1234';

    JsBarcode('#barcode', data, {
      format: 'pharmacode',
      lineColor: '#0aa',
      width: 4,
      height: 40,
      displayValue: false,
    });

Which is rendered from the following HTML in the DOM:

<svg id="barcode" width="172px" height="60px" x="0px" y="0px" viewBox="0 0 172 60" xmlns="http://www.w3.org/2000/svg" version="1.1" style="transform: translate(0px, 0px);"><rect x="0" y="0" width="172" height="60" style="fill: rgb(255, 255, 255);"></rect><g transform="translate(10, 10)" style="fill: rgb(0, 170, 170);"><rect x="0" y="0" width="4" height="40"></rect><rect x="12" y="0" width="4" height="40"></rect><rect x="24" y="0" width="12" height="40"></rect><rect x="44" y="0" width="12" height="40"></rect><rect x="64" y="0" width="4" height="40"></rect><rect x="76" y="0" width="12" height="40"></rect><rect x="96" y="0" width="4" height="40"></rect><rect x="108" y="0" width="4" height="40"></rect><rect x="120" y="0" width="12" height="40"></rect><rect x="140" y="0" width="12" height="40"></rect></g></svg>

But in my code, the svg is just

<svg id="barcode" />

How can I pull this rendered svg’s HTML without going into the browser console and copy/paste?

To summarize, I’m looking for a way to generate this completed HTML and contain it within a variable inside my component to then pass to a mustache template.

How to plus input numbers in HTML with JS

i have the follow code:

<input type="number" name="pree" value="" id="pree" class="form-control">
<input type="number" name="pree1" value="" id="pree1" class="form-control">
<input type="number" name="pree2" value="" id="pree2" class="form-control">
<input type="number" name="pree3" value="" id="pree3" class="form-control">
<input type="number" name="result" value="" id="result" class="result">

I want to do a plus with all inputs, and im new in this process, but i try:

In JS:

<script>

    var num1= document.getElementByID('pree');
    var num2= document.getElementByID('pree1');
    var num3= document.getElementByID('pree2');
    var num4= document.getElementByID('pree3');
    
    var result=document.getElementByID('num1 + num2+ num3+ num4');

</script>

‘m really new to this and would like someone to help me with it, thank you very much in advance

Modify Class Method Definition in TS or JS

I have a class having structure like :

class A {
    constructor() {}
    myMethod() {
      console.log('in my method');
    }
}

I want to make a method that will accept className and methodName like :

modifyClassMethod(className, methodName)

This method should wrap the whole body of methodName specified into a callback during runtime.

So if I do,

modifyClassMethod(A, myMethod)

Now during runtime the body of myMethod of class A should get changed to

myMethod() {
   nr.recordMe('here', {
      console.log('in my method').
   })
} 

Now when I will create a new object of A class, then I will get modified value of myMethod.

How can I achieve this in TS or JS ?.