Edit page for multiple image upload with preview

I am working on a product posting page, which supports up to 5 images. I set the 5 images limit with data-max_length=”5″.

For the Add Page, I use the following:

HTML:

<div class="upload__box">
  <div class="upload__btn-box">
    <label class="upload__btn">
      <p>Upload images</p>
      <input type="file" multiple="" data-max_length="5" class="upload__inputfile">
    </label>
  </div>
  <div class="upload__img-wrap"></div>
</div>

CSS:

html * {
  box-sizing: border-box;
}

p {
  margin: 0;
}

.upload {
  &__box {
    padding: 40px;
  }
  &__inputfile {
    width: .1px;
    height: .1px;
    opacity: 0;
    overflow: hidden;
    position: absolute;
    z-index: -1;
  }
  
  &__btn {
    display: inline-block;
    font-weight: 600;
    color: #fff;
    text-align: center;
    min-width: 116px;
    padding: 5px;
    transition: all .3s ease;
    cursor: pointer;
    border: 2px solid;
    background-color: #4045ba;
    border-color: #4045ba;
    border-radius: 10px;
    line-height: 26px;
    font-size: 14px;
    
    &:hover {
      background-color: unset;
      color: #4045ba;
      transition: all .3s ease;
    }
    
    &-box {
      margin-bottom: 10px;
    }
  }
  
  &__img {
    &-wrap {
      display: flex;
      flex-wrap: wrap;
      margin: 0 -10px;
    }
    
    &-box {
      width: 200px;
      padding: 0 10px;
      margin-bottom: 12px;
    }
    
    &-close {
        width: 24px;
        height: 24px;
        border-radius: 50%;
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        top: 10px;
        right: 10px;
        text-align: center;
        line-height: 24px;
        z-index: 1;
        cursor: pointer;

        &:after {
          content: '2716';
          font-size: 14px;
          color: white;
        }
      }
  }
}

.img-bg {
  background-repeat: no-repeat;
  background-position: center;
  background-size: cover;
  position: relative;
  padding-bottom: 100%;
}

JavaScript:

jQuery(document).ready(function () {
  ImgUpload();
});

function ImgUpload() {
  var imgWrap = "";
  var imgArray = [];

  $('.upload__inputfile').each(function () {
    $(this).on('change', function (e) {
      imgWrap = $(this).closest('.upload__box').find('.upload__img-wrap');
      var maxLength = $(this).attr('data-max_length');

      var files = e.target.files;
      var filesArr = Array.prototype.slice.call(files);
      var iterator = 0;
      filesArr.forEach(function (f, index) {

        if (!f.type.match('image.*')) {
          return;
        }

        if (imgArray.length > maxLength) {
          return false
        } else {
          var len = 0;
          for (var i = 0; i < imgArray.length; i++) {
            if (imgArray[i] !== undefined) {
              len++;
            }
          }
          if (len > maxLength) {
            return false;
          } else {
            imgArray.push(f);

            var reader = new FileReader();
            reader.onload = function (e) {
              var html = "<div class='upload__img-box'><div style='background-image: url(" + e.target.result + ")' data-number='" + $(".upload__img-close").length + "' data-file='" + f.name + "' class='img-bg'><div class='upload__img-close'></div></div></div>";
              imgWrap.append(html);
              iterator++;
            }
            reader.readAsDataURL(f);
          }
        }
      });
    });
  });

  $('body').on('click', ".upload__img-close", function (e) {
    var file = $(this).parent().data("file");
    for (var i = 0; i < imgArray.length; i++) {
      if (imgArray[i].name === file) {
        imgArray.splice(i, 1);
        break;
      }
    }
    $(this).parent().parent().remove();
  });
}

The Add Page works pretty well.

However, after a product is added and the images are uploaded, for the Edit Page, I have a problem.

I use the following code to show the uploaded images’ preview.

HTML and PHP:

<?php if($row_item["image_1"] != '') { ?>
    <div class='upload__img-box'><div style='background-image: url(./images/<?= $row_item["image_1"] ?>)' data-number='1' data-file='' class='img-bg'><div class='upload__img-close'></div></div></div>
<?php } ?>
<?php if($row_item["image_2"] != '') { ?>
    <div class='upload__img-box'><div style='background-image: url(./images/<?= $row_item["image_2"] ?>)' data-number='2' data-file='' class='img-bg'><div class='upload__img-close'></div></div></div>
<?php } ?>
<?php if($row_item["image_3"] != '') { ?>
    <div class='upload__img-box'><div style='background-image: url(./images/<?= $row_item["image_3"] ?>)' data-number='3' data-file='' class='img-bg'><div class='upload__img-close'></div></div></div>
<?php } ?>
<?php if($row_item["image_4"] != '') { ?>
    <div class='upload__img-box'><div style='background-image: url(./images/<?= $row_item["image_4"] ?>)' data-number='4' data-file='' class='img-bg'><div class='upload__img-close'></div></div></div>
<?php } ?>
<?php if($row_item["image_5"] != '') { ?>
    <div class='upload__img-box'><div style='background-image: url(./images/<?= $row_item["image_5"] ?>)' data-number='5' data-file='' class='img-bg'><div class='upload__img-close'></div></div></div>
<?php } ?>

The problem now is, in the Edit Page, the 5 images limit doesn’t work properly.

For example, let’s say in the Add Page, the user uploaded 2 images. Now, in the Edit Page, the user should only be able to add a maximum of 3 images only. But this doesn’t work.

Also, if the user removed an image, then the user should be allowed to add an additional 4 images.

Please help me, how can I make the Edit Page work?

How can I make a div move as a scrollbar?

I’m currently working on making a website layout that looks like the Window95 desktop with the paint window as the main window for content, and I’m trying to finish up the last (at least, I hope it’s the last…) JavaScript element and I truly have NO idea what I’m doing. What I want is for the scrolling part of the scrollbar I’ve made to, well…scroll. I’ve got the buttons for it working just fine, but the actual scrolling part is a different story. I think I’d need to use mouse events (mouseup, mousedown, and mousemove), something for the wheel aspect, as well as have the scrollbar move the actual content the way a regular scrollbar does, but I have no understanding of how to make it work ๐Ÿ™ I’ve searched DOZENS of different search terms to try and find a similar problem, but I just don’t think most people want to make custom scrollbars anymore so I’ve found NOTHING that can help me.

I don’t know JavaScript at all and am really, really struggling with getting what I want to work.

I have a codepen here showing my layout so far, so I hope you can see what I’m working with. None of my scripts seem to be working in the link and I’m not sure why, but since I don’t have a script yet I’ve tried out, maybe that’s not a big deal?

I asked this question on Reddit and got a lot of responses to making a custom cursor using scrollbar-color and scrollbar-width, but to be clear that doesn’t fix my problem. What I want is to use JavaScript to make a div scroll up and down, while it also moves the content as it scrolls. I will input the code below of my coding for the scrollbar and it’s direct parent that I’m trying to make.

.scrollbarvertical {
display: block;
position: absolute;
float: right;
width: 16px;
height: calc(100% - 18px);
top: 2px;
right: 1px;
border-bottom: black 1px solid;
background-color: #bdbebd;
background-image: url("https://file.garden/ZWlUCY4S7Xz2vypS/themes/windows%2095%20paint/transparent%20bg.gif");
}
.buttonscrollbarupdown {
display: inline-block;
position: relative;
width: 16px;
background-color: #bdbebd;
border-left: #dedfde 1px solid;
border-right: black 1px solid;
border-bottom: black 1px solid;
border-top: black 1px solid;
text-align: center;
left: 0;
top: -1px;
box-shadow: inset 0 1px 0 0 white, inset 1px 0 0 0 white, inset 0 -1px 0 0 #7b7b7b, inset -1px 0 0 0 #7b7b7b;
}

Any help is greatly appreciated!!!

I’ve tried multiple different draggable scripts but none of them do what I want as I don’t want a simple draggable script, but one in which the draggable object also scrolls a text box I’ve created.

How to implement Dijkstra’s algorithm with dynamic edge weight updates?

I’m implementing Dijkstra’s algorithm for shortest paths in a weighted graph, but I also need to handle dynamic updates to the edge weights. The requirements are:

  1. Efficiently update the weight of an edge.
  2. Recalculate the shortest paths after each update.

What is the best approach to handle dynamic edge updates while maintaining good performance? Are there any specific data structures or optimizations that can help with this problem? Code examples or detailed explanations would be appreciated.

I’ve implemented Dijkstra’s algorithm for finding the shortest paths in a weighted graph. The implementation works fine for static graphs where the edge weights do not change.

Why am I getting error ReferenceError: Audio is not defined in NextJs?

So I got this Next component where it can play or stop the music (just like the MP3 player). It works perfectly fine when I run it on local server, when I click the button, the audio will play or stop. But however, I’am getting an error in the terminal, it says

srccomponentsbgmAudio.tsx (6:31) @ Audio
 โจฏ ReferenceError: Audio is not defined
    at BgmAudio (./src/components/bgmAudio.tsx:13:72)
digest: "2253870762"

  4 | export default function BgmAudio() {
  5 |   const [isPlaying, setIsPlaying] = useState(false);
> 6 |   const audioRef = useRef(new Audio("/audio/bgmAmbient.MP3"));
    |                               ^

And here’s my full source code:

"use client";
import { useEffect, useState, useRef } from "react";

export default function BgmAudio() {
  const [isPlaying, setIsPlaying] = useState(false);
  const audioRef = useRef(new Audio("/audio/bgmAmbient.MP3"));

  const bgmPlay = () => {
    if (!isPlaying) {
      setIsPlaying(true);
      audioRef.current.play();
    } else {
      setIsPlaying(false);
      audioRef.current.pause();
    }
  };

  return (
    // Play or stop the audio button
    <div className="w-8 fill-textBase active:scale-90s" onClick={() => bgmPlay()}>
      {isPlaying && (
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 576 512">
        </svg>
      )}
      {!isPlaying && (
        <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512">
        </svg>
      )}
    </div>
  );
}

How do I fix this problem? I’m using Typescript ๐Ÿ˜€

Typescript – Activating a class method in a separate class

I am working on a school assignment where I have to modify a vehicle selection interface to include a truck that can tow other vehicles. Vehicles that are not trucks cannot tow other vehicles. I created the Truck class in Truck.ts and created a method called tow.

In the Cli (I did not chose the names for these files and notified the admin about the inappropriate file name pun) there is a method called findVehicleToTow where the tow method is called when the vehicle of type Truck towing any vehicle besides itself.

I tried several methods to call tow, but I frequently get “property tow does not exist on type of Truck.

My teacher said to pass an array through the vehicles array and find the truck class. I can do that with a for and if, but I do not know what to do within the if statement to declare the class as a variable or string so I can call the tow method.

let towTruck = this.vehicles.filter((Truck) => {
          if (towTruck === Truck) {
            return true;
          }
        }
      )
towTruck.tow(answers.vehicleToTow.vin);

I am super new to this and need the most basic explanation.

https://github.com/sketchyTK/Module-8-Challenge-Vehicle-Builder/blob/main/src/classes/Cli.ts

Typescript: type narrowing on an object array

I have this code:

const f = (x: unknown) => {
  if (!x || !Array.isArray(x)) {
    throw new Error("bad");
  }

  for (const y of x) {
    if (!y || typeof y !== "object") {
      throw new Error("bad");
    }

    y // y does intellisense think this has type `any`
  }
};

In my VS Code, intellisense thinks the final y has type any. I would expect it to have type object. Why is this? And how should I structure my code so that intellisense recognizes the second y has type object?

How does the parameter const v8::FunctionCallbackInfo& args get its value at the C++ level?

Reading the source code and finding different functions that can be called from the js code, for example new TCP, it is not entirely clear how the C++ level accepts arguments to its level for a specific bound function.

For example, this js call is bound

new TCP(TCPConstants.SERVER)

with the following code on ะก++

void TCPWrap::New(const FunctionCallbackInfo<Value>& args) {
  // This constructor should not be exposed to public javascript.
  // Therefore we assert that we are not trying to call this as a
  // normal function.
  CHECK(args.IsConstructCall());
  CHECK(args[0]->IsInt32());
  Environment* env = Environment::GetCurrent(args);

  int type_value = args[0].As<Int32>()->Value();
  TCPWrap::SocketType type = static_cast<TCPWrap::SocketType>(type_value);

  ProviderType provider;
  switch (type) {
    case SOCKET:
      provider = PROVIDER_TCPWRAP;
      break;
    case SERVER:
      provider = PROVIDER_TCPSERVERWRAP;
      break;
    default:
      UNREACHABLE();
  }

  new TCPWrap(env, args.This(), provider);
}

That is, I want to understand how the C++ level const FunctionCallbackInfo<Value>& args is initialized for the bound function, thanks.

Issue with module imports and exports: (TypeError: featureCore is not a function)

I have a node project with the following format:

structures/extendedClient.js

utils/feature.js

tests/feature.test.js

In extendedClient.js I have the following:

class extendedClient extends Client {
    constructor(props) {
   // constructor stuff
   }

   runFeature() {
       require("../util/feature")(this);
    }
   }

   module.exports = extendedClient;

In my feature.js I have the following:

module.exports = (client) => {
    /**
     *
     * @param {require("../structures/extendedClient")} client
     */
  function featureCore() {
  // stuff (requires client variable)
  }

  featureCore();
}

I tried calling featureCore() from another location but it wouldn’t import properly so I temporarily put it here. However, now I can’t reference the function in any unit tests (Jest).

my feature.test.js file:

const  { anotherFunction, featureCore } = require("./util/feature");


test('expect birthday core to be read', () => {
    expect(birthdayReminderCore().toBe(3))
})

My test suite is throwing “TypeError: featureCore is not a function”.

I’m sure that I’m missing something glaringly obvious, was just hoping someone could point me in the right direction. Thanks!

Twincat 3 HMI translate animation with variable point of destination

I an new to Twincat3 and Javascript. Would like to create translate animation for image.
The layout can refer to below image. The location of orange cubes are fix, while green cube is the moving image.
enter image description here

Below are the concept for the animation.
1.Moving of green cube is triggered by moving bit from PLC, while the moving destination is send by the integer variable (1-10) from PLC
2.The script shall be able to read current location of green cube and location of destination (orange cube), and calculate the movement px for animation to reach destination.

Currently I having difficulties in getting below info for javascript execution:

  1. Get current location of green cube and destination
  2. Bind PLC variable to javascript and get the value inside the PLC variable
  3. Declare function in javascript

Below is the script i edited from the sample get from Beckhoff Infosys:

var data = TcHmi.Symbol.readEx2('%s%PLC1.MAIN.yardGate.x2%/s%', function (data) {
    if (data.error === TcHmi.Errors.NONE) {
        // Handle result value... 
        var value = data.value; 
        console.log(value); 
    } else {
      // Handle error... 
  }
});

But when go to live view, show error data is not define.
Hope can get advice from members.

Thanks

Below are the concept for the animation.
1.Moving of green cube is triggered by moving bit from PLC, while the moving destination is send by the integer variable (1-10) from PLC
2.The script shall be able to read current location of green cube and location of destination (orange cube), and calculate the movement px for animation to reach destination.

Currently I having difficulties in getting below info for javascript execution:

  1. Get current location of green cube and destination
  2. Bind PLC variable to javascript and get the value inside the PLC variable
  3. Declare function in javascript

Below is the script i edited from the sample get from Beckhoff Infosys:

var data = TcHmi.Symbol.readEx2('%s%PLC1.MAIN.yardGate.x2%/s%', function (data) {
    if (data.error === TcHmi.Errors.NONE) {
        // Handle result value... 
        var value = data.value; 
        console.log(value); 
    } else {
      // Handle error... 
  }
});

Is it Possible to Clone an App From Chrome Sources if it shows most Files But no Package.json?

I found a react platform that I wanted to break down to further understand it more, and redesign it for a future idea, and it seems to have all required files but I’m not sure, so I’m hoping someone might be able to help, or if I’m missing something.

Under inspect sources:
“Authored” has 2 folders, one is “static” that has all Components, Contexts, Hooks, Pages, Node Modules, App.js, and Index.js in normal react code.

In the src folder, about half the .TS files have code normal code while others show this calling main.js

"<!doctype html><html lang="en"><head><meta charset="UTF-8......src="/static/js/main.8d0aabed.js"

The main.8d0aabed.js consists of a long line of code, when beautified looks like this:

74207: (e,t,n)=>{
"use strict";
Object.defineProperty(t, "__esModule", {
value: !0
}),
t.createMintWithAssociatedToken = void 0;
const r = n(82021)
, i = n(47026)
, o = n(76310)
, a = n(33087);
t.createMintWithAssociatedToken = function(e, t) {

The Source Maps all load successfully, is it possible to break down the functions from Main.js to be useable and/or am I able to use the existing Node Modules & code to create something similar?
Same with Package.js, is it possible to use the Node Modules to create one?

Under “Deployed” it has the CSS, Fonts, main.8d0aabed.js, and main.8d0aabed.css

This is the site, if more info is needed: https://solana.defilaunch.app/

I’m not sure if it’s even possible, I just see 80% of the code and have been trying for awhile now.

Tried downloading entire platform using ResourceSaver and running in VSCode, but the Main.js throws errors.

How to use Go language custom package in react-native?

I want to use Go language in react-native, is there any process to use. I have created my own package I want to use that in react-native JS.

I have searched some online, got that by using react-native packages we can use like bridging between JS and Go. But I don’t know exactly how to use.

How can i use a button within a div created in javascript

let productDetails = document.createElement("div");
productDetails.className = "product_card";

productDetails.innerHTML = `
    <img
      src="${product.image.desktop}"
      alt="${product.name}"
    />
    <div class="button-wrapper">
        <button id="btn_add_to_cart">Add to Cart</button>
    </div>
    <div class="product-details-wrapper">
        <p id="product_category">${product.category}</p>
        <h4 id="product_name">${product.name}</h4>
        <p id="product_price">$${product.price.toFixed(2)}</p>
    </div>`;

productList.appendChild(productDetails);

I created a function to add product to a cart and called it using ‘onclick’ but it’s not working
I also tried to use querySelector to get the button and add an event listener, it also didn’t work

It’s like I’m trying to use something that does not exist… Anyone to help please

Add Action Key Objects based on User Action

I’m working with Angular 18 and reactive forms. When I receive data from the backend, the form gets pre-filled.

Below is the backend response:

InitialResponse =  {
    "FS_Application": {
        "STATUS": "DRAFT",
        "FS_Applicant_Details": [
            {
                "FS_Applicant": {
                    "APPLICANT_NAME": "POTENCY COMMUNICATIONS (PTY) LTD",
                }
            }
        ],
        "FS_RequestType_Details": {
            "FS_RequestType": [
                {
                    "FLOW": "",
                    "SEQUENCE_NUMBER": "",
                    "FS_Beneficiary_Details": {
                        "FS_Beneficiary": [
                            {
                                "ZAR_AMOUNT": "100.00",
                                "FS_Beneficiary_Id": {
                                    "Id": "16422",
                                    "ItemId": "005056A62B4EA1EF8FBFE9478FED8856.16422"
                                }
                            }
                        ]
                    }
                },
                {
                    "FLOW": "",
                    "FS_Beneficiary_Details": {
                        "FS_Beneficiary": [
                            {
                                "ZAR_AMOUNT": "2000.00"
                            }
                        ]
                    }
                }
            ]
        }
    }
}

Users can perform actions like modifying the data, deleting an FS_Beneficiary, or adding a new FS_Beneficiary.

The updated form data is stored in CurrentResponse.

Now, I need to compare the InitialResponse with CurrentResponse and create a payload for the backend API.

I need to add an “OPERATION” key with values such as ‘UPDATE’, ‘DELETE’, ‘CREATE’, or ‘SKIP’ based on the user’s modifications.

For example, if the “STATUS” is modified to “REVIEW”:

newPayLoadRequest = {
    "FS_Application": {
        "OPERATION": "UPDATE",
        "STATUS": "REVIEW"
    }
}

If there is no change in the status:

newPayLoadRequest = {
    "FS_Application": {
        "OPERATION": "SKIP",
        "STATUS": "DRAFT"
    }
}

The “OPERATION” key should be added to all parent objects.

For FS_Beneficiary:

If a new item is added, set “OPERATION”: “CREATE”.
If an existing FS_Beneficiary with an FS_Beneficiary_Id key is deleted, set “OPERATION”: “DELETE”.

"FS_Beneficiary_Details": {
 "OPERATION": "UPDATED",
  "FS_Beneficiary": [{
    "OPERATION": "CREATED",
    "ZAR_AMOUNT": "2000.00"
  }]
}

Can anyone help me create this payload request?

Angular Code,

if (this.data ? .isEdit) {
  this.viewService.viewSubmissionData$.subscribe(res => {
    if (res) {

      const FS_RequestType_Details = res ? .fsApplication ? .fsRequestTypeDetails ? .fsRequestType ? .map((requestType: any) => ({
        Title: {
          Value: requestType ? .title ? .value || ""
        },
        FS_Request_Type_Id: {
          Id: requestType ? .fsRequestTypeId ? .id || "",
          ItemId: requestType ? .fsRequestTypeId ? .itemId || ""
        },

        Flow: requestType ? .flow || "",
        Sequence_Number: requestType ? .sequenceNumber || "",
        FS_Beneficiary_Details: {
          FS_Beneficiary: requestType ? .fsBeneficiaryDetails ? .fsBeneficiary ? .map((beneficiary: any) => ({
            Title: {
              Value: beneficiary ? .title ? .value || ""
            },
            FS_Beneficiary_Id: {
              Id: beneficiary ? .fsBeneficiaryId ? .id || "",
              ItemId: beneficiary ? .fsBeneficiaryId ? .itemId || ""
            },
            Beneficiary_Name: beneficiary ? .beneficiaryName || "",

          })) || []
        }
      })) || [];


      const editApplicationRequestPlayload = {
        "FS_Application": {
          "FS_Application-id": {
            "Id": res ? .fsApplication ? .fsApplicationId ? .id,
            "ItemId": res ? .fsApplication ? .fsApplicationId ? .itemId
          },
          "APPLICANT_NAME": res ? .fsApplication ? .applicantName,

          "FS_Applicant_Details": [

          ],
          FS_RequestType_Details
        }
      };
      console.log('original', editApplicationRequestPlayload);

      this.newApplicationServ.getFinalPayload().subscribe(([reInfo$, stepOne, stepTwo, stepThree, stepFour]) => {
        const FS_RequestType = stepTwo.map((group: any) => {

          const beneficiaries = stepTwo.beneficiaries.map((beneficiary: any) => ({
            "BENEFICIARY_NAME": beneficiary.name,

          }));

          return {
            "FLOW": '',
            "SEQUENCE_NUMBER": '',
            "FS_Beneficiary_Details": {
              "FS_Beneficiary": beneficiaries
            }
          };
        });

        const FS_RequestType_Details = {
          "FS_RequestType": FS_RequestType
        };

        const currentRequestPayload = {
          "FS_Application": {

            "STATUS": "DRAFT",
            "FS_Applicant_Details": [{
              "FS_Applicant": {
                "APPLICANT_NAME": stepOne ? .applicantName,
              }
            }],
            "FS_RequestType_Details": FS_RequestType_Details
          }
        };

        const final = this.comparePayloads(editApplicationRequestPlayload, currentRequestPayload);

      });
    }
  });
}

How to change aria attribute with Jquery?

I have the following code where I would like to change the aria-describedby attribute to match the text in the <h3></h3> contained in that div. I need to identify each div by the .slick-slide class.

  • Note that I typically have 3 – 6 divs in a page with the slick-slide class.
<div class="cards__card cards__card--1 cards__slide section--light slick-slide slick-current slick-active" data-slick-index="0" aria-hidden="false" tabindex="0" role="tabpanel" id="slick-slide00" aria-describedby="slick-slide-control00">
    <div class="cards__slide-wrapper self-center">
        <h3 class="section__header cards__header heading heading--h3 ">--- HEADER ---</h3>
        <div class="cards__item cards__item--copy">
            <p> ---  SAMPLE TEXT ---</p>
        </div>
        <div class="cards__pagination cards__pagination--black">
            <p class="copy--disclaimer">1 / 4</p>
        </div>
    </div>
</div>

I have tried the following to no avail:

$('div .slick-slide').each(function () {
    var h3 = $(this).closest("h3").text(); 
    $(this).attr("aria-describedby", h3);
});

Thank you in advance!