Can I make a drag-and-drop element’s fields be unchangeable after being dropped?

So I’m trying to make a drag-and-drop menu, where after you fill out a draggable item, you can drag it over to a “drop area”.

The issue I’m having is that due to issues where I can’t change certain items after they’ve been dropped in the drop area, the fastest solution would be to make any “fields” and “buttons” non-interactable to the user when the item has been dropped.

In case it’s relevant, this menu is contained in a HTML5 web page and the drag-and-drop menu is coded with JavaScript.

What options do I have to do this with JavaScript? I still want those “fields” and “buttons” to be interactable before they’ve been dragged.

Please let me know if you have any questions.

Url not available when converting image blob to file? Javascript

I am using react easy crop to cropp images and upload on server. It converts the image to a blob which i then convert to a file but the problem is the url is not specified on the file. I expected the file to be something like the file object created when we upload files from computer with a preview property having the src but that is not present in this file that i am getting. I need the src of the image for further use. Can anyone help how can i get it on the file object?

Blob to file conversion

let convertedFile = new File([file], "croppedImg.png", { type: "image/png", });

Chrome async wait sending content before request completed

I am a complete rookie in programming and JS language, appreciate all the help in advanced.

Below is an attempt to extract some info from a webpage and then display it on a chrome extension page.
The problem I have based on many hours of research seems to be that the sending of variable extracted from webpage to extension page failed as my extractor is asyncronous.
The variable that arrives at my extension page is [object object].
I have tried many fixes from SO answers but I just don’t seem to find a solution..

1.) This code will run on the webpage to extract some information (the async await is needed in original code, below is just a sample).

async function Extractor(document) {
    var item = document.getElementbyId("....");
    await new Promise(r => setTimeout(r, 3000));
    
    return item
}

2.) I assume this code sends the message to the one below telling it to run and retrive extractor results.

chrome.runtime.sendMessage({
    action: "getSource",
    source: Extractor(document)
});

3.) This code is in popup.js, where my intention is to insert the extractor’s result from webpage into a popup.html extension page, under node id = “message”.

chrome.runtime.onMessage.addListener(function(request, sender) {
   if (request.action == "getSource") {
      message.innerText = request.source;
   }
});

Webpack doesn’t resolve imports of JSON files from D3 packages

I have an Angular app built with Webpack that imports locale JSON files from the d3-format package:

import d3Format from "d3-format/locale/en-US.json";

This worked fine with D3 v5. But after upgrading to v7, I get the following error:

Module not found: Error: Can't resolve 'd3-format/locale/en-US.json'

The JSON file is still in the same location (and in fact the IDE resolves it correctly). But Webpack just doesn’t find it when building the app. The main change that broke this import is that the package.json of d3-format now includes this bit (and if I remove it, the build works fine again!):

"exports": {
  ".": {
    "umd": "./dist/d3-format.min.js",
    "default": "./src/index.js"
  },
  "./locale/*": "./locale/*.json"
}

The import also works if I specify an import path like this:

import d3Format from "../../../../node_modules/d3-format/locale/en-US.json";

But this is ugly, I’d rather avoid that.

passing random number to google charts :undefined Error

To learn more, I’m gridding a Java script and experimenting with various projects. I am stuck at passing value. Where I am generating random numbers through the setinterval function, I am able to generate random numbers, and it is working fine. But I want to pass that random number to Google Charts so that charts work like real-time data. So what I was planning was to generate that random number, and through inner html, I will insert it into the span element, and later, through “.value,”, I will get the value of the span element and pass it to the charts. but it was not working so i console.log(output.value ) i am getting the output as undefined so when i console.log(value.output) inside that setinterval function it shows the correct output . 

here’s my code

<!DOCTYPE html>
<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">
    <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
  


    <title>Document</title>
</head>




<body>

<h3>
    Random number from 0 to 9:
    <h1 id="foo"></h1>
</h3>

    <div id="chart_div" style="width: 400px; height: 120px;"></div>
<script>



window.onload = function() {
    var output = document.getElementById('foo');
    setInterval( function ()  {
        output.innerHTML =Math.floor(Math.random() * 100);
        
    }, 500);

}



google.charts.load('current', {'packages':['gauge']});
google.charts.setOnLoadCallback(drawChart);

function drawChart() {

  var data = google.visualization.arrayToDataTable([
    ['Label', 'Value'],
    ['Memory', 34],
    ['CPU', 55],
    ['Network', 68]
  ]);

  var options = {
    width: 400, height: 120,
    redFrom: 90, redTo: 100,
    yellowFrom:75, yellowTo: 90,
    minorTicks: 5
  };

  var chart = new google.visualization.Gauge(document.getElementById('chart_div'));

  chart.draw(data, options);

    console.log(foo.value);

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

In this programme basically number will generate randomly and it will be disaplyed in h1 tag .  So I’m going to get that value from h1 and feed it into Google Charts. But it wont work rather charts get hide. So i just want to pass the output value to ['Memory', {here}], here . As a result, Google Charts operate in real-time because they derive their value from randomly generated random numbers. 

Thank You

How to use variable after jquery ajax function [duplicate]

Help me please, how to get result from jquery function ?

$(document).ready(function(){
    $.ajax({
        url: "http://somemywebsite.com/getdata.php",
        type: 'GET',
        dataType: 'json',
        success: function(res) {
            $( "input[name*='fname']" ).val( res ); /// this code works, fname field was changed to my!
        }
    });


//but how i can get the result of code?
alert(res); /// Doesn't work, empy!

var test = $( "input[name*='fname']" ).val;

alert(test); //Doesn't work too
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

All data got empty status …

Checking same case in JavaScript

I was trying to solve a code wars kata called “Check same case”, and I’m not understanding what is wrong with my solution and why it doesn’t pass.
The function should check:

  • If either of the characters is not a letter, return -1
  • If both characters are the same case, return 1
  • If both characters are letters, but not the same case, return 0

Here’s my solution:

function sameCase(a, b){
    if (!a.match(/[A-z]/g) || !b.match(/[A-z]/g)) {
      return -1
    } else if ((a.match(/[A-Z]/g) && b.match(/[A-Z]/g)) || (a.match(/[a-z]/g) && b.match(/[a-z]/g))) {
      return 1 
    } else {
      return 0
    }
  }

The solution passes in all the tests, but when I click on “Attempt” I get these two errors:

  • For sameCase(“^”,”B”): expected 0 to equal -1
  • For sameCase(“]”,”D”): expected 0 to equal -1

there are JavaScript to check text contain includes function what error

<p class="time">
<span>1m ago</span>
<span>2 days ago</span>
</p>
<script>
let time = document.getElementsByClassName("time02");

if (time.textContent.includes("1m ago")) {
    console.log ("you have a message 1 minute before")
}
else {
    console.log ("before 1 days")
}
</script>

showing that error…

Uncaught TypeError: Cannot read properties of undefined (reading ‘includes’)?

FetchError: invalid json response body at reason: Unexpected end of JSON input when using mockfetch with Jest

I am using Mockfest to test a very simple api for unsplash.
The fetch call works very well of course and it looks like this:

test('it makes a fetch call to unsplash', async () => {
        await api.fetchPhoto('wedding')
        expect(fetch).toHaveBeenCalled()
    })

and it shows from the Jest script:

● it makes a fetch call to unsplash

FetchError: invalid json response body at  reason: Unexpected end of JSON input

  4 |
  5 |     const response = await fetch(url)
> 6 |     const data = await response.json(); 
    |                  ^
  7 |     
  8 |     return data;
  9 | }

This is my fetch function:

async function fetchPhoto (event) {

    const url = 'https://api.unsplash.com/photos/random?query='+event+'&per_page=1&client_id=gKEeCzK-8XXRBG8IHbYAGTEUDMN-Dpm9FjxjDS4f2Y0';

    const response = await fetch(url)
    const data = await response.json(); 
    
    return data;
}

module.exports = { fetchPhoto };
 

How can I get past this error, I mean my fetch function works and returns
what its supposed to return.

Set Image URL based on if condtion on ASPX page

As of now this code always works on my local and doesnt acts weird. But when we deploy on server even though if IsEnabled value is set to true it will load isfalse.gif and therafter few days it will start to load correct image based on IsEnabled value.

IsEnabled is an simple property defined in codebehind.

protected bool IsEnabled 
{
    get { return Utility.GetValue(); }
}

ASPX Page :

<asp:Image ID="imgWebcast" ImageUrl='<%#(IsEnabled) ? "../../images/istrue.gif" : "../../images/isfalse.gif" %>'  />

I looked at below areas and all looks good :

  1. Cache precompiled files are deleted prior to deployment
  2. Cached is cleared
  3. IIS is reset

I can easily set it in code behind and resolve the above , but i need to understand the approach i did above is valid or not. Is something i am doing wrong. Does it achievable from the above approach

Escaping JavaScript fetched from a server in PHP

My wordpress plugin uses register_rest_route() to register a route that fetch data from a server. The data is a JavaScript script that will be executed on the page.

function my_route_handler( $request ) {
  // Define URL
  // Define context
  // ...

  // Make an HTTP request to fetch the raw script
  $response  = file_get_contents( $url, false, $context );

  // Return the script contents as the response of this API endpoint
  echo $response
  exit;
}

I am trying to properly escape the output from the server to avoid any malicious attacks. All of the WordPress helpers (like htmlentities()) break the functionality because they escape literal characters. E.g. > -> &gt.

What’s the right approach here to properly validate and return a response from my server? Is there a generally accepted pattern?

Typescript control flow behavior

I am new to JS, TS and Angular…
So I have this angular component:

export class AdminProductsMenuComponent implements OnInit{
    constructor(private productService: ProductService,
                private alertService: AlertService,
                private router: Router) {
                    this.subscribeToDeleteProductEvents();
    }

    productsAdminModel: IGetProductAdminModel[] = [];
    private productId: string;

    ngOnInit(): void {
        this.executeGetAllProductsAsAdmin();
    }

    executeGetAllProductsAsAdmin() {
        this.productService.getAllProductsAsAdmin().subscribe({
            next: (productData) => this.productsAdminModel = productData
        })
    }

    private subscribeToDeleteProductEvents() {
        this.alertService.getSubjectAlertEvent().subscribe({
            next: (isConfirmed) => {

                if (isConfirmed) {
                    this.productService.deleteProduct(this.productId).subscribe({
                        next: () => {
                            this.reloadCurrentResources();
                        }
                    });
                }
            }
        });
    }

    private reloadCurrentResources(): void {
        // save current route first
    this.router.navigateByUrl('/', { skipLocationChange: true }).then(() => {
        this.router.navigate(['/AdminProducts']); // navigate to same route
    }); 
    }

    executeProductDelete(id: string) {
        this.productId = id;
        this.alertService.confirmationAlertProductDelete();
    }
    
}

Brief explanation:
I have subscription in the constructor which listens for events during the lifetime of the component.

An event is fired when the last method is called (through the template) which prompts a SweetAlert confirm dialog. Depending on the selected the event is true or false.

Now here is the tricky part – if I move the executeProductDelete() method above reloadCurrentResources() and subscribeToDeleteProductEvents() and invoke it (executeProductDelete) it will complete the action and throw error
enter image description here

I have a feeling that it executes again the subscribeToDeleteProductEvents() and reloadCurrentResources() .

If I move the executeDeleteProduct() as the last method, no error occurs.
Why is this behavior? I have a feeling that they continue to run synchronously. They are not invoked anywhere else.

Update height and width of image used for dragging using `setDragImage`

I am trying to use an image to show upon dragStart(),
Tried updating the image height and width but no change seen.
Here’s sample code:

 var img = new Image(50, 40);  
 img.src = "https://images.unsplash.com/photo-1579353977828-2a4eab540b9a?ixlib=rb-1.2.1&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=774&q=80"
 ev.dataTransfer.setDragImage(img, 10, 10);

But the width and height, 50 and 40 updated is not reflecting to the image. I would like to fix dimensions for the image while dragging

Here’s the sample link for the program
https://jsfiddle.net/w6qkgc7t/

PS: Any solution without canvas would be better. 😉

Changing an API fetch to a local array fetch in Node.js

I’m very, very new to coding and I’ve been using a template from GitHub to build on my project. On GitHub, there is a function that grabs a random quote from an API and displays it. Instead of it grabbing the quote from this API, I would like it to grab the quote from a list of quotes I’ve already pre-written (possibly stored in an array?)

My apologies if this is a very novice question, but any support is really appreciated! I just need to find a way to switch the quotes from the API to quotes I’ve pre-written. Thanks!!

import React from "react"; import "../styles/Quote.css"; import { useState, useEffect } from "react";

const Quote = () => {   const [hoverQuote, setHoverQuote] = useState(false);   const [quoteData, setQuoteData] = useState([]);   const [quoteLoading, setQuoteLoading] = useState(true);

  //fetch quote from api   const fetchQuote = async () => {
    const res = await fetch("https://quotes15.p.rapidapi.com/quotes/random/", {
      method: "GET",
      headers: {
        "x-rapidapi-key": process.env.REACT_APP_RAPID_KEY,
        "x-rapidapi-host": "quotes15.p.rapidapi.com",
      },
    });
    setQuoteLoading(false);
    const data = await res.json();
    return data;   };

  //shortens the quote if its too long   const shortQuote = (e) => {
    if (e.length > 250) {
      return e.substring(0, 250) + "...";
    }
    return e;   };

  useEffect(() => {
    const getQuotes = async () => {
      const quoteFromApi = await fetchQuote();
      setQuoteData(quoteFromApi);
    };

    getQuotes();   }, []);

  return (
    <div>
      {quoteData && (
        <div className="quoteContainer">
          <div className="blockContainer quoteBlock">
            <div className="hoverQuote" onMouseOver={() => setHoverQuote(true)} onMouseOut={() => setHoverQuote(false)}>
              {quoteLoading === true && (
                <p className="">
                  <i className="fa fa-spinner spinner2 spinLoading" aria-hidden="true"></i>
                </p>
              )}
              <div className={`quote ${hoverQuote ? "slideUp" : ""} ${quoteLoading ? "" : "fadeInAnim"} `}>
                {quoteLoading === false && <p>"{quoteData && quoteData.content && shortQuote(quoteData.content)}"</p>}
              </div>
            </div>
          </div>
          <div>
            <div className="blockContainer authorBlock">
              <div className="hoverQuote" onMouseOver={() => setHoverQuote(true)} onMouseOut={() => setHoverQuote(false)}>
                <div className={`author ${hoverQuote ? "slideDownFadeIn" : ""} ${quoteLoading ? "notLoaded" : ""}`}>
                  <span className={`${hoverQuote ? "TextSlideDownFadeIn" : ""}`}>
                    {quoteData && quoteData.originator && quoteData.originator.name}
                  </span>
                  <a href={quoteData.url} className={`${quoteLoading ? "notLoaded" : ""}`}>
                    <i className={`fa fa-external-link ${hoverQuote ? "TextSlideDownFadeIn" : ""}`} aria-hidden="true"></i>
                  </a>
                </div>
              </div>
            </div>
          </div>
        </div>
      )}
    </div>   ); };

export default Quote;

LocalStorage value resets on a different page

I have multiple pages like Home, Faq and more and I’ve added darkmode function and I want website to remember the choice. If I have pressed darkmode on home and refresh the choice is saved. However when I go to Faq the value is reset even tho I’ve pasted the same code on my other website. Yes I’ve tried connecting same JS file to these 2 websites and didn’t worked.

btw it’s shortened code as example so don’t mind that

button.addEventListener('click', () => {
    if (element.style.color == "wheat") {
        element.style.color = "rgb(33,33,36)";
        window.localStorage.setItem("mode", "White");
    } else {
        element.style.color = "wheat"
        window.localStorage.setItem("mode", "Dark");
    }
});

var ls = localStorage.getItem("mode");

if (ls == "Dark") {
    console.log("it's dark");
} else {
    console.log("it's white");
}

So yeah if I click the button and refresh website it will be “it’s dark” but if I click and go to Faq with same connected js file it will be “it’s white”. Sorry if it’s a stupid question I’m still learning and I’m not sure if it should work with multiple pages maybe I should use different method like cookies? Thanks for any help.