I have to change Jquery Ajax Imagecrop System

I found on internet this imagecrop system.

This System normaly image upload and crop system. If i try code is working. But if i try change the function it doesnt work.

I have to change system.

I already uploaded image. And i wanna crop uploaded image.

Jscript


    var $modal = $('#modal');
    var image = document.getElementById('sample_image');
    var cropper;

    //$("body").on("change", ".image", function(e){
    $('#upload_image').on("change", function(event){
        var files = event.target.files;
        var done = function (url) {
            image.src = url;
            $modal.modal('show');
        };
        //var reader;
        //var file;
        //var url;

        if (files && files.length > 0)
        {
            /*file = files[0];
            if(URL)
            {
                done(URL.createObjectURL(file));
            }
            else if(FileReader)
            {*/
                reader = new FileReader();
                reader.onload = function (event) {
                    done(reader.result);
                };
                reader.readAsDataURL(files[0]);
            //}
        }
    });

    $modal.on('shown.bs.modal', function() {
        cropper = new Cropper(image, {
            aspectRatio: 1,
            viewMode: 3,
            preview: '.preview'
        });
    }).on('hidden.bs.modal', function() {
        cropper.destroy();
        cropper = null;
    });

    $("#crop").click(function(){
        canvas = cropper.getCroppedCanvas({
            width: 1600,
            height: 400,
        });

        canvas.toBlob(function(blob) {
            //url = URL.createObjectURL(blob);
            var reader = new FileReader();
            reader.readAsDataURL(blob); 
            reader.onloadend = function() {
                var base64data = reader.result;  
            
                $.ajax({
                    url: "upload.php",
                    method: "POST",                 
                    data: {image: base64data},
                    success: function(data){
                        console.log(data);
                        $modal.modal('hide');
                        $('#uploaded_image').attr('src', data);
                        //alert("success upload image");
                    }
                });
            }
        });
    });
    

If you choice file from computer this system work and start image crop system.. But i dont want upload image.
I have a button like this :

<div><a href="#" class="cropimage" data="/images/resimler/testimage.jpg">Crop Image</a></div>

When I click on this a, I want to take the data of a and do the image crop on that image.

Thanks for help..

Updating a value in a observable array in knockout.JS

I am new to knockout and facing problems updating a value in a KnockoutObservableArray,
My property in the viewModel is as below
public images: KnockoutObservableArray = ko.observableArray([]);

ImageViewModel.ts looks like this


class ImageViewModel {

    public dateCreated: KnockoutObservable<string> = ko.observable<string>(undefined);
    public base64: KnockoutObservable<string> = ko.observable<string>('');
    public url: KnockoutObservable<string> = ko.observable<string>('');

    public readerFriendlyDate: KnockoutComputed<string>;
    public imgSrc: KnockoutComputed<string>;
    public isDataUrl: KnockoutComputed<boolean>;

    constructor(image: IRoadPostImage) {
        this.dateCreated(image.CreatedDate);
        this.base64(image.Base64);
        this.url(image.Url);
        this.readerFriendlyDate = ko.computed<string>((() => {
            return new Date(this.dateCreated()).toLocaleDateString('sv-SE');
        }).bind(this));
        this.imgSrc = ko.computed<string>((() => {
            return (this.url() && this.url().length > 0) ? this.url() : this.base64();
        }).bind(this));
        this.isDataUrl = ko.computed<boolean>((() => {
            return this.imgSrc().startsWith("data:");
        }).bind(this));
    }


}

my images array will contain multiple objects and each of them will be having base64 property and I want update one of it on the basis of the index of array.

any help will be highly appritiated, thanks in advance!

I tried below code but no luck

public rotateImages(ivm: ImageViewModel) {
        debugger;
        var index = this.images.indexOf(ivm);
        console.log("1", this.images()[index].base64);
        
        console.log("2",this.images().map(iv => <IRoadPostImage>{
            Base64: iv.base64(),
            CreatedDate: iv.dateCreated(),
            Url: iv.url()
        }))

        const callbackFn = (newBase64Url) => { 
            this.images()[index].base64 = (newBase64Url as KnockoutObservable<string>)
        }

        console.log("3", this.images()[index].base64);

        this.rotateBase64Image(ivm.base64(), callbackFn);

        this.images.valueHasMutated();
        console.log("4",this.images().map(iv => <IRoadPostImage>{
            Base64: iv.base64(),
            CreatedDate: iv.dateCreated(),
            Url: iv.url()
        }))
    }
    private rotateBase64Image(base64data, callback) {
        const canvas = <HTMLCanvasElement> document.createElement('CANVAS');
        const ctx = canvas.getContext('2d');
        var image = new Image();
        image.src = base64data;
        image.onload = function() {
            ctx.translate(image.width, image.height);
            ctx.rotate(90 * Math.PI / 90);
            ctx.drawImage(image, 0, 0); 
            callback(canvas.toDataURL());
        };
    }

Double Error Message In Google Sheet Form Made Using App Script

<!-- Button HTML -->
  <div class="container-btn">
    <div id="btnSearch" class="btn" onclick="notifySearch()"> <p> Search </p> </div>
    <div id="btnSave" class="btn" onclick="notifySave()">Save</div>
    <div id="btnUpdate" class="btn" onclick="notifyUpdate()"> <p> Update </p> </div>
    <div id="btnDelete" class="btn" onclick="notifyDelete()"> <p> Delete </p> </div>
  </div>
<!-- Notification CSS -->

This is some button


<style>
  #notification-area
{
    position: fixed;
    top: 0px;
    right: 10px;
    width: 500px;
    height: 100px;
    color: ;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
    z-index: -1;
}

#notification-area .notification
{
    padding: 15px 10px;
    background: #111;
    color: #f5f5f5;
    font-family: 'Courier New', Courier, monospace;
    font-size: 15px;
    font-weight: 600;
    border-radius: 5px;
    margin: 5px 0px;
}

#notification-area .notification.success
{
    background: #389838;
}

#notification-area .notification.error
{
    background: #ff4500;
}

#notification-area .notification.info
{
    background: #00acee;
}
</style>

This is CSS of notification


<!-- Notification HTML-->
<div id="notification-area">
  <!-- <div class="notification success">
      Lorem ipsum, dolor sit amet consectetur adipisicing elit.
  </div>
  <div class="notification error">
      Lorem ipsum, dolor sit amet consectetur adipisicing elit.
  </div>
  <div class="notification info">
      Lorem ipsum, dolor sit amet consectetur adipisicing elit.
  </div> -->
</div>
</body>

This is HTML Of notification


<!-- Save Dữ Liệu JS-->
<script>
  let notificationShown = false;
  const btnSave = document.getElementById("btnSave");
  btnSave.addEventListener("click", attempData);

  function attempData() {
    if (notificationShown)
    {
      return; // Nếu thông báo đã xuất hiện, không thực hiện thêm
    }
    const inputUser = document.getElementById("input-user").value;
    const inputWeek = document.getElementById("input-week").value;
    const inputItemCode = document.getElementById("input-ItemCode").value;
    const inputVendorCutting = document.getElementById("input-VendorCutting").value;
    const inputCuttingNumber = document.getElementById("input-CuttingNumber").value;
    const inputReleaseDate = document.getElementById("input-ReleaseDate").value;
    const inputAssemblingDate = document.getElementById("input-AssemblingDate").value;
    const inputRunningDate = document.getElementById("input-RunningDate").value;
    const inputCompletionDate = document.getElementById("input-CompletionDate").value;
    const inputVendorNote = document.getElementById("input-VendorNote").value;
    if (inputUser.length == 0 || inputWeek.length == 0 || inputItemCode.length == 0)
    {
      notifySave();
      notificationShown = true; // Đánh dấu rằng thông báo đã xuất hiện
    } 
    else
    {
      const data =
      {
        user: inputUser,
        week: inputWeek,
        itemCode: inputItemCode,
        vendorCutting: inputVendorCutting,
        cuttingNumber: inputCuttingNumber,
        releaseDate: inputReleaseDate,
        assemblingDate: inputAssemblingDate,
        runningDate: inputRunningDate,
        completionDate: inputCompletionDate,
        vendorNote: inputVendorNote
      };
      google.script.run.attempData(data);
      clearInputFields();
    }
  }

  function clearInputFields()
  {
    // Hàm xóa trường nhập liệu
    document.getElementById("input-user").value = "";
    document.getElementById("input-week").value = "";
    document.getElementById("input-ItemCode").value = "";
    document.getElementById("input-VendorCutting").value = "";
    document.getElementById("input-CuttingNumber").value = "";
    document.getElementById("input-ReleaseDate").value = "";
    document.getElementById("input-AssemblingDate").value = "";
    document.getElementById("input-RunningDate").value = "";
    document.getElementById("input-CompletionDate").value = "";
    document.getElementById("input-VendorNote").value = "";

    notificationShown = false; // Đánh dấu rằng thông báo đã được xử lý và có thể hiển thị lại
  }
</script>

This code use for save data and clear form


<!-- Notification JS -->
<script>
function notify(type,message)
{
  (() => 
  {
      let n = document.createElement("div");
      let id = Math.random().toString(36).substr(2,10);
      n.setAttribute("id",id);
      n.classList.add("notification",type);
      n.innerText = message;
      document.getElementById("notification-area").appendChild(n);
      setTimeout(() => 
      {
          var notification = document.getElementById("notification-area").getElementsByClassName("notification");
          for(let i = 0; i < notification.length; i++)
          {
              if(notification[i].getAttribute("id") == id)
              {
                  notification[i].remove();
                  break;
              }
          }
      },6000);
  })();
}

function notifySave() {
  if (!notificationShown) {
    notify("success", "Vui Lòng Nhập ÍT Nhất Trường User, Week And Item Code");
    notificationShown = true;
  }
}
</script>

This is Notification JAva Script

enter image description here

I want a message just show once`

the first time i do it, it appear with 1 message but the data can’t input in google form

when i tried to use browser.messagebox( notthing heppen)

finally, i can iput and show a error messgae but it show two times

This is my google sheet file of code
https://docs.google.com/spreadsheets/d/1qSJcndpa6NKkV0UlX–wfpikBacl0T2MWIY2wLQl6lQ/edit?usp=sharing

Is there a way to load a local resource (CSV file) with vanilla JS?

Essentially, I need to load a CSV file that is located in my project folder, and sometime in the future, I will have to write to it as well. Is there a way to do this using vanilla JS? I’ve tried looking for a solution, but the majority of the results I got were using node JS, uploading the file through and input element and then reading it, or using a http server plugin for chrome. I used the fetch method,

fetch("file:///../db/credentials.txt")
    .then((res) => res.text())
    .then((text) => {
        console.log(text);
    })
    .catch((e) => console.error(e));

but that lead to an access error because it was “blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, isolated-app, chrome-extension, chrome, https, chrome-untrusted.” I need a solution that uses vanilla JS, and do keep in mind that I intend to host this project on github pages as well.

I’ve thought about maybe hosting the csv file on a file hosting site, under the assumption that fetch would work for a remote file. Would that be possible, and if so, what is a good file hosting site for such purposes, or is there a better solution to this?

Toggle button in VSC not working, JavaScript code doesn’t load in the console (downloaded node.js)

I am following a set of instructions from Youtube to build a blog website, this is the Link: https://www.youtube.com/watch?v=Aj7HLsJenVg&t=2621s. I have also copy and pasted the completed HTML, JS, CSS file of it to see if the toggle button is working and it is also not. How do I make the code work? I started noticing there’s something that is not working when I did the console.log to see if the .navbar is going to appear but didn’t. also when the toggle (supposedly hamburger) button did not work.

I tried downloading node.js, I am not sure if the JS file is actually the one that isn’t working, but most functionality that i am expecting to work from its code isn’t working


//Grab elements
const selectElement = (selector) => {
    const element = document.querySelector(selector);
    if(element) return element;
    throw new Error('Something went wrong! Make sure that ${selector} exists/is typed correctly.');
};
//couldn't get the console to work

//Nav styles on scroll
const scrollHeader = () => {
    const headerElement = selectElement('#header');
    if(this.scrollY >= 15){
        headerElement.classList.add('activated');
    }else{
        headerElement.classList.remove('activated');
    }
};

window.addEventListener('scroll', scrollHeader);
//couldn't get the test scroll work and turn red 40.47

//Open menu & search pop-up
const menuToggleIcon = selectElement('#menu-toggle-icon');

const toggleMenu = function () {
    const mobileMenu = selectElement('#menu');
    mobileMenu.classList.toggle('activated');
    menuToggleIcon.classList.toggle('activated');
};

menuToggleIcon.addEventListener('click', toggleMenu);
//When clicked it doesn't change anything

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width", initial-scale="1.0">

    <title>KodoSprout  |  Home</title>

    <!--Tab icon of the site-->
    <link rel="icon" type="image/png" sizes="32x32" href="./assets/Images/kodoutabicon.jpeg">
    
    <!--Site Icons-->
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/fonts/remixicon.css" rel="stylesheet">

    <!--Custom styles-->
    <link rel="stylesheet" href="./assets/css/main.css">
    
    <!--swiper.js styles-->
    <script src="https://cdn.jsdelivr.net/npm/swiper@11/swiper-bundle.min.js"></script>

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
    <!--Header-->
    <header class="header" id="header">

        <!--the container class will limit how wide a particular element is 
        going to stretch inside-->
        <nav class="navbar container">

            <!--logo using an anchor tag which will point/click back to the index-->
            <a href="./kodousproutindex.html">
                <h2 class="logo">KodoSprout</h2>
            </a>

            <!--the menu options, there's a list inside of this div-->
            <div class="menu" id="menu">
                <ul class="list">
                    <li class="list-item">
                        <a href="#" class="list-link current">Home</a>
                    </li>
                    <li class="list-item">
                        <a href="#" class="list-link">Commentaries</a>
                    </li>
                    <li class="list-item">
                        <a href="#" class="list-link">Catalogue</a>
                    </li>
                    <li class="list-item">
                        <a href="#" class="list-link">Foodies</a>
                    </li>
                    <li class="list-item">
                        <a href="#" class="list-link">Community</a>
                    </li>   
                    <li class="list-item">
                        <a href="#" class="list-link">Snapshots</a>
                    </li>
                    <li class="list-item screen-lg-hidden">
                        <a href="#" class="list-link">Contact</a>
                    </li>
                    <li class="list-item screen-lg-hidden">
                        <a href="#" class="list-link">Profile</a>
                    </li>
                </ul>
            </div>

            <div class="list list-right">
                <button class="btn place-items-center" id="theme-toggle-btn">
                    <i class="ri-sun-line sun-icon"></i>
                    <i class="ri-moon-line moon-icon"></i>
                </button>

                <button class="btn place-items-center" id="search-icon">
                    <i class="ri-search-line"></i>
                </button>

                <button class="btn place-items-center screen-lg-hidden menu-toggle-icon" id="menu-toggle-icon">
                    <i class="ri-menu-3-line open-menu-icon"></i>
                    <i class="ri-close-line close-menu-icon"></i>
                </button>

                <a href="#" class="list-link screen-sm-hidden">Contact</a>
                <a href="#" class="list-link screen-sm-hidden btn profile fancy-border">
                    <span>Profile</span>
                    </a>


            </div>

        </nav>



    </header>

Facing issue while running ng test in Angular

I am facing issue while running unit test cases in angular. The terminal is running for infinite and with absurd output.VS code is getting crashed as well.
enter image description here

I checked Karma.conf.js and angular.json but got no flaws in those. I did install node modules using npm i –force as some of peer dependency are not working with the angular version. Though application is running fine but unit test cases are not working.

get beforeunload confirmation value

In my VUE app, I want to write some logic on confirmation of page-refresh. But this does not work properly as it call function on both scenarios when user clicked ok or cancel.

  created() {
    window.addEventListener('beforeunload', (e) => {
      e.preventDefault();
      e.returnValue = '';
      console.log('before-unload');

  //some code logic base on user clicked ok


    });

I tried the above code but it did not work

Get full height of object tag

I need detect the full height of content inside an <object> tag. I’m trying to load external HTML, but it shows me a scrollbar so I want dynamically set the height of the object and avoid showing the scrollbar.

I’ve tried several options, but I only found the height of the object tag, not the content inside the object. Do you know of any solutions?

<object data="https://www.second-domain.com/test.html" type="text/html" style="width:100%;height:100vh"></object>

Typescript: changing a property on window to optional?

The default TS type for window.Notification is Notification, but since the Web Notifications API has only 90% browser support, it should be Notification | undefined. I recently encountered a bug where I used window.Notification without checking if it’s defined.

Is there a way to override properties on window, such as making them optional? I tried this, but it didn’t work:

declare global {
  interface Window {
    Notification?: Notification;
  }
}

Firefox dispatchEvent doesn’t propagate to children

I have an <svg> with a <g> with children, that have pointerdown event handlers, and a <use> referencing the <g>.

In Chrome if I register the event handler before I add the <use>, the <use> handles events like <g> and its children does. However in Firefox it doesn’t.

To solve this, I added an event handler to the <use>, that dispatches a pointerdown event, that has clientX and clientY set (keeping in mind the different position of the <g>), on the <g>.

When I click on the <use>, my test event handler on <g> got called but the event handler of the children didn’t, so apparently it didn’t propagate.

Why is that? If you need more details, please ask me.

How should I place a Github action file so it will correctly run?

I am trying to create a github action that I can add into my build process. I am using javascript action, currently using the helloWorld sample. (https://docs.github.com/en/actions/creating-actions/creating-a-javascript-action) I think I followed the instructions correctly, but alas, things didn’t work out. Here’s what happened:

I created a action.yml file to handle the action and placed it as part of the project in vcbdt/helloWorld/action.yml@master. This was not placed in the .github/workflows subdirectory but in the main directory. I have assumed that actions are special and can be picked up where they are placed provided that they are described properly. After all, I am trying to create the action in someone else’s workflow.

name: 'Hello World'
description: 'Greet someone and record the time'
inputs:
  who-to-greet:  # id of input
    description: 'Who to greet'
    required: true
    default: 'World'
outputs:
  time: # id of output
    description: 'The time we greeted you'
runs:
  using: 'node20'
  main: 'index.js'

I know that there is no “on” tag in the file but my understanding is that there is no need as this is an action that is used as part of someone else’s workflow. That’s where the “on” will be defined.

In the calling work flow, I added to vcbdt/callingWorkflow/.github/workflows/ci.yml the following code

on: [push]

jobs:
  hello_world_job:
    runs-on: ubuntu-latest
    name: A job to say hellodd
    steps:
      - name: Hello world action step
        id: hello
        uses: vc-bdt/delete-HelloWorld/action.yml@master
        with:
          who-to-greet: 'Mona the Octocat'
      # Use the output from the `hello` step
      - name: Get the output time
        run: echo "The time was ${{ steps.hello.outputs.time }}"

When I checked this in I get the error:

"A job to say hellodd
Can't find 'action.yml', 'action.yaml' or 'Dockerfile' for action 'vc-bdt/delete-HelloWorld/action.yml@master'."

I know the file is in the right place and I only have a master version so it should find it.

I changed the location of the action.yml file so it used ” uses: vc-bdt/delete-HelloWorld/.github/workflows/action.yml@master”. This failed with another error

"Error: .github#L1
reusable workflows should be referenced at the top-level `jobs.*.uses' key, not within steps".

Can anyone provide me assistance in seeing what is going on here? Your help would be much appreciated.

Slow loop long enough to process offsetWidth, or getBoundingClientRect().width

I want to set the caret in the alternate span, so that it has the same left as it did in the original one. The trigger is the up arrow in the below span, or the down arrow in the top span.

To the problem in general, i’ve tried

creating a proxy span, then adding characters from the span the caret’s to be placed and working out the character-position the caret should be placed based on this width (code below)

moving the selection through the characters of the span the caret’s to be placed, and then based on the position

But it seems like the loop doesn’t give time enough to calculate the offsets/getBoundingClientRects. To that issue of the loop moving too fast, i’ve tried

using setTimeouts on the loop condition/position queries/innerText assignments

moving parts of the loop to a function, with/without requesting animation frames

Does anyone have any ideas? I would like to use vanilla javascript. But this just seems to take me a bit out of my depth, to the point i’m a little directionless.

function setCaret8(e) {
    e.preventDefault();
    var selection = window.getSelection().getRangeAt(0);
    var launchLeft = selection.getBoundingClientRect().left - e.target.offsetLeft; // relative to span
    var landing = [name, tag].find(variable => variable !== e.target);

    var proxy = document.createElement('span');
    proxy.id = 'proxy';
    proxy.classList = 'pA vH';

    setTimeout(function () {
        document.body.appendChild(proxy);
    }, 0); // Slow for node attachment

    var i = 0;
    
    var proxWidth = proxy.offsetWidth;

    while (proxy.offsetWidth <= launchLeft && i < landing.innerText.length) {
        proxy.innerText += landing.innerText[i++];
    }

    selection.setStart(landing.firstChild, i);
    selection.collapse(true);
    landing.focus();
}

Use `spyOn` for super class’ getter

In this situation:

class Parent {
  get condition() {
    return true;
  }
}

class Child extends Parent {
  get able() {
    return !this.condition;
  }
}

I’m writing a test code like:

test("`able` returns true if `condition` is false", () => {
  const child = new Child();

  jest.spyOn(child, "condition", "get").mockImplementation(() => false);
                    ^^^^^^^^^^^

  expect(child.able).toBe(true);
});

However, as you know I can’t spyOn condition getter because that is from super class. Is there a way to mock the getter?

splitting and working with parts of array string

I need to do a forEach process for each part of a split string object:

I am trying to create some code for each number character of a split string. An example of my string is as follows:

1,2,3,4;5,6,7;10;23,24

Where:

  • the string does not necessarily start with “1”.

  • the string will only contain number characters.

  • all the numbers after the first number are sorted, but not necessarily consecutive.

  • there are different “teams” in the string, separated by “;”

  • the teams can be as short as 1 character and as long as 31 characters.

The goal is to firstly separate the string into its teams and then iterate through each character of each team.

Here is what I have:

arr = "1,2,3,4;5,6,7;10;23,24";
//the above is a part of a larger string, already split, that is always different.

Now I can access the individual teams by:

arr1 = arr.split(";")[0]; //this should return "1,2,3,4"
arr2 = arr.split(";")[2]; //this should return "10"

The problem is that I cannot know how many “teams” the string contains, or how many characters each team contains, and I need to do something like the following:

x = 1;
$.each(arr + x, function(i, v){
    if(v!=","){
        //code here
    }
    x++;
});
            

Can someone please guide me in the right direction? Thank you, in advance.

Why is the focus visible when a lightDom element in a web component is clicked?

I’ve created a simple web component that lets you create a custom button.

When clicked, I want the page title to be focused.

I don’t understand why the title is visually focused (which I don’t want it to be), when I click on the lightDom element (e.g. the span). This doesn’t happen when I click on my component directly (the shadowDOM part).

I tried with other tags than button. I expect my title to be focus but not visible-focus, without hiding by forcing.

I tried to look at this thread too: Why is focus-visible applied on page load

// Template web component
const template = document.createElement('template');
template.innerHTML = `
      <style>
        button {
          background-color: lightgreen;
          padding: 10px;
        }
      </style>
      <button>
        <slot></slot>
      </button>`;

// Class web component
class MyBtn extends HTMLElement {
  constructor() {
    super();

    this.attachShadow({
      mode: 'open'
    });

    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

// web component definition
window.customElements.define('my-btn', MyBtn);

// Set focus to title on click
function focusTitle() {
  const h1 = document.getElementById('title');
  h1.setAttribute('tabindex', -1);
  h1.focus();
}

// Add click event listener
document.getElementById('btn1').addEventListener('click', focusTitle);
document.getElementById('btn2').addEventListener('click', focusTitle);
<template id="wc-btn-template">
      <button id="bouton">Générer le scénario sans shadow dom</button>
      <div id="resultat"></div>
    </template>

<h1 id="title">Test redirection focus</h1>
<button id="btn1" style="padding: 10px">
      <span>Span</span>
      Bouton
    </button>

<my-btn id="btn2">
  <span>Span</span> Bouton
</my-btn>