Javascript Interactjs – Delete div item on drop in dropzone

I’m trying to delete an item when being dropped in the dropzone that serves as bin. The tricky part here is that the dropzone must be in position:fixed and initially the draggable item is in position:relative. I think this causes the dropzone not to be able to detect when something is being dropped when the draggable is in a different position. I tried to fix this by changing position:absolute to draggable when item is being dragged but inevitably, the draggable overlaps the dropzone. How do I make this work?

/**
* 
* 
* ineracjs
* drag and drop
* 
* 
*/
function interactJs(){

var element = document.querySelector('.draggable');

var x = 0; var y = 0

interact(element)
.resizable({
// resize from all edges and corners
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)

// update the element's style
target.style.width = event.rect.width + 'px'
target.style.height = event.rect.height + 'px'

// translate when resizing from top or left edges
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)
target.textContent = Math.round(event.rect.width) + 'u00D7' + Math.round(event.rect.height)
}
},
modifiers: [
// keep the edges inside the parent
interact.modifiers.restrictEdges({
outer: 'parent'
}),

// minimum size
interact.modifiers.restrictSize({
min: { width: 100, height: 50 }
})
],

inertia: true
})
.draggable({
modifiers: [
interact.modifiers.snap({
targets: [
interact.snappers.grid({ x: 30, y: 30 })
],
range: Infinity,
relativePoints: [ { x: 0, y: 0 } ]
}),
interact.modifiers.restrict({
restriction: element.parentNode,
elementRect: { top: 0, left: 0, bottom: 1, right: 1 },
endOnly: true
})
],
inertia: true
})
.on('dragmove', function (event) {
x += event.dx
y += event.dy

event.target.style.transform = 'translate(' + x + 'px, ' + y + 'px)';
event.target.style.position = 'absolute';
})


/**
* 
* 
* delete
* dropzone
* 
*/
var bin = document.querySelector('.element-trash');

interact(bin)
.dropzone({
accept: '.draggable',
// Require a 75% element overlap for a drop to be possible
overlap: 0.75,
ondrop: function (event) {

$(event.target).remove();// remove from DOM

console.log(event.target);
}
})
.on('dropactivate', function (event) {
event.target.classList.add('drop-activated')
})
}interactJs();
.element-trash{
    height: 100%;
    color: white;
    background: red;
    padding: 1%;
    width: 120px;
    position: fixed;
    z-index: 1;
    top: 0;
    left: 0;
    overflow-x: hidden;
    transition: 0.5s;
    /* padding-top: 60px; */
}
#main{
padding: 0px !important;
margin-left: 120px;
}
#main{
  background-color: #eceef0;
}
#main {
  transition: margin-left .5s;
  height: 100% !important;
  /*padding: 16px;*/
  }
  .draggable {
  width: 10%;
  min-height: 6.5em;
  background-color: #29e !important;
  color: white;
  border-radius: 0.75em;
  padding: 4%;
  touch-action: none;
  user-select: none;
  z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--ineractjs-->
<script src="https://cdn.jsdelivr.net/npm/interactjs/dist/interact.min.js"></script>

<div class='element-trash'>Drop to delete</div>

<div id='main'>

<div class='draggable'>Drag me</div>

</div>

Cannot pass data to PhpMyAdmin by ajax

Index.php

This is part of my Index.php code, I cannot pass data to the file “action/viewupdate.php” using ajax.

                                    <tr>
                                        <td><?php echo $row['word'] ?></td>
                                        <td><?php echo $row['comment'] ?></td>
                                        <td><?php echo $row['viewno'] ?>
                                            <Span id="view_update<?php echo $count; ?>" style="display:none;font-weight:1000;color:green;font-size:12px"></Span>
                                        </td>
                                        <form action="" method="post" id="viewupdate<?php echo $count; ?>">
                                            <td><input type='button' name='viewupdate' value='Update' data-action="viewupdate<?php echo $count; ?>" class="button" /></td>
                                            <input type="hidden" id="userselectchannel<?php echo $count; ?>" name="userselectchannel<?php echo $count; ?>" value="<?php echo $row['videoline'] ?>">
                                            <input type="hidden" id="updateno<?php echo $count; ?>" name="updateno<?php echo $count; ?>" value="">
                                            <td style="display:none" id="saveupdateclm<?php echo $count; ?>"><input id="saveupdatebtn<?php echo $count; ?>" type='button' name='saveupdate<?php echo $count; ?>' value='Save**strong text**' data-action="saveupdate<?php echo $count; ?>" class="confirmbutton" /></td>
                                        </form>
                                    </tr>
                                    <script>
                                        $('#saveupdatebtn<?php echo $count; ?>').click(function() {
                                            var updateno1 = $('#updateno<?php echo $count; ?>').val();
                                            var userselectchannel1 = $('#userselectchannel<?php echo $count; ?>').val();
                                            var username1 = "<?php echo $_SESSION['nick_name']; ?>";
                                            /* alert(updateno + "n" + userselectchannel + "n" + username); */
                                            $.ajax({
                                                url: 'action/viewupdate.php',
                                                type: 'POST',
                                                data: {
                                                    "updateno": updateno1,
                                                    "userselectchannel": userselectchannel1,
                                                    "username": username1
                                                },
                                                cache: false,
                                                success: function(msg) {
                                                    console.log(data);
                                                    var x = document.getElementById("errorpopup2");
                                                    x.innerHTML = "<div style='color:#21ff21;'>Video <?php echo $count ?>Views update successfully</div>";
                                                    x.className = "show";
                                                    setTimeout(function() {
                                                        x.className = x.className.replace("show", "");
                                                    }, 3000);

                                                    $("#saveupdatebtn<?php echo $count; ?>").attr("disabled", "disabled");
                                                    $('#saveupdatebtn<?php echo $count; ?>').css('cursor', 'not-allowed');
                                                    return false;
                                                },
                                                error: function(msg) {
                                                    var x = document.getElementById("errorpopup2");
                                                    x.innerHTML = "Unknown Error Occured";
                                                    x.className = "show";
                                                    setTimeout(function() {
                                                        x.className = x.className.replace("show", "");
                                                    }, 3000);
                                                    return false;
                                                }

                                            });
                                        });

Viewupdate.php

<?php 
include_once "../../system/connect.php";
$updateno=$_POST['updateno'];
$userselectchannel=$_POST['userselectchannel'];
$username=$_POST['username'];
$time = date('Y-m-d H:i:s');
$updatetitle = $updateno;
$sql = "INSERT INTO `pagecontent_update`(`update-user`, `update-time`, `update-info`) 
VALUES ('$username','$time','$updatetitle')";
if (mysqli_query($link, $sql)) {
    echo json_encode(array("statusCode"=>200));
} 
else {
    echo json_encode(array("statusCode"=>201));
}
?>

PhpMyAdmin Screenshot
https://drive.google.com/file/d/1NcTYZNWhFMSQZMCZiNrTcfX-MPN4UGnT/view?usp=sharing

As the picture shown, data cannot pass to Viewupdate.php using ajax. As I wish that when user press the submit button, the data will stored into the database without refresh. Thx a lot.
If you need more information, please contact me at any time.

How to Call Page JS Function with Arguments from Chrome Extension V3?

This is my 1st attempt at a Chrome Extension. What I want to accomplish is to call a global javaScript function with arguments from my extension (content.js) which exists in the web app, in the tab. I would be making multiple calls to the function with different arguments based on the interaction with the extension. The extension is a form-based auditing tool.
When the submit button is clicked, a function getTestValues() is called in my content.js

SUBMIT_BUTTON.onclick = evt => getTestValues();

Within getTestValues() I want to call the global JS function with arguments, pixelAudit.staticPixels([arg1],[arg2])

pixelAudit.staticPixels(statusSelVal, outputModeVal);

I’m having issues finding much info on this? There is a ton for V2 but not much for V3. Is it even possible to do this? Any info, advice, or links are much appreciated.

Thank you!

Getting the same javascript image to populate HTML table multiple times

I am learning how to incorporate JavaScript into HTML and am trying to build a very simple web game based off a class project. (This is a sidebar, I successfully completed the project itself.)

I need two specific images to randomly populate the entire table. My code successfully creates the array of appropriate length and translates that correctly to the HTML, but the image sources don’t seem to populate correctly. One image of each always shows up so I am confident my source paths are correct, and one of the images is always in the lower right hand corner, but the rest of the field is blank. When examining DevTools the array is there with appropriate img attributes but there is no source, except obviously on the img‘s that have a visible image.

class Field {

    static generateField(h, w, pct = .2) {
        let board = [];
        let tempArray = [];
        while (board.length < h) {
            while (tempArray.length < w) {
                const random = Math.random();
                if (random < pct) {
                    tempArray.push(imageB);
                } else {
                    tempArray.push(imageA);
                }
            }
            board.push(tempArray);
        }

        for (let a = 0; a < h; a++) {
            let row = document.createElement("tr");
            for (let b = 0; b < w; b++) {
                let cell = document.createElement("td");
                let img = document.createElement("img");
                img = board[a][b];
                img.style.width = "100%";
                img.style.height = "100%";
                cell.appendChild(img);
                row.appendChild(cell);
            }
            tblBody[0].appendChild(row);
        }
    }
}

The tblBody is defined outside the class. Originally my code was nested for loops and gave the exact same result.

Where am I going wrong?

How to use reduce() function in Vue 3 Composition API

I am building Pokemon filtered search app using Vue 3 with Composition API, based on the following tutorial: https://www.youtube.com/watch?v=QJhqr7jqxVo. The Home view in the app uses a fetch method to fetch Pokemon from the PokemonAPI:

    fetch('https://pokeapi.co/api/v2/pokemon?offset=0')
    .then((res)=> res.json())
    .then((data)=> {
      console.log(data)
      state.pokemons = data.results;
      state.urlIdLookup = data.results.reduce((acc, cur, idx)=> 
      acc = { ...acc, [cur.name]:idx+1 }
      ,{})
    })

Each Pokemon in the JSON response includes an index number. The second promise uses a reduce method to handle urlIdLookup. urlIdLookup is then passed into the router-link path used to redirect to Pokemon about/details page:

    <div class="ml-4 text-2x text-blue-400" 
    v-for="(pokemon, idx) in filteredPokemon" :key="idx">
      <router-link :to="`/about/${urlIdLookup[pokemon.name]}`">
        {{ pokemon.name }}
      </router-link>
    </div>

The tutorial, however, does not explain why it is necessary to create a new accumulator object (“acc”) inside the reduce method, and then deconstruct the accumulator (“…acc”). Could someone perhaps explain why it’s necessary to create that object, then deconstruct it? Also, is there perhaps a better method for retrieving the id and passing it into the router link?

Here is the full component:

<template>
  <div class="w-full flex justify-center">
    <input type="text" placeholder="Enter Pokemon here" 
    class="mt-10 p-2 border-blue-500 border-2" v-model="text"/>
  </div>
  <div class="mt-10 p-4 flex flex-wrap justify-center">
    <div class="ml-4 text-2x text-blue-400" 
    v-for="(pokemon, idx) in filteredPokemon" :key="idx">
      <router-link :to="`/about/${urlIdLookup[pokemon.name]}`">
        {{ pokemon.name }}
      </router-link>
    </div>
  </div>
</template>

<script>
import { reactive, toRefs, computed } from 'vue';

export default {
  name: 'Home',
  setup() {

    const state = reactive({
      pokemons: [],
      urlIdLookup:{},
      text: "",
      filteredPokemon: computed(()=> updatePokemon())
    })

    const updatePokemon = () => {
      if(!state.text) {
        return []
      }
      return state.pokemons.filter((pokemon) => 
        pokemon.name.includes(state.text)
      )
    }

    fetch('https://pokeapi.co/api/v2/pokemon?offset=0')
    .then((res)=> res.json())
    .then((data)=> {
      console.log(data)
      state.pokemons = data.results;
      state.urlIdLookup = data.results.reduce((acc, cur, idx)=> 
      acc = { ...acc, [cur.name]:idx+1 }
      ,{})
    })

    return { ...toRefs(state), updatePokemon }
  }
}
</script>

firestore: UNAUTHENTICATED: Failed to retrieve auth metadata with error

The Full error msg: UNAUTHENTICATED: Failed to retrieve auth metadata with error: reason: Client network socket disconnected before secure TLS connection was established.

I created a watcher collection where on create documents in the watcher, it will delete other documents and finally will delete the document itself inside watcher but it manage to delete like 450 out of 500 documents, the rest of the documents can’t be deleted. I have checked the documents, there are in the correct format. I was wondering if there is a issue with Firebase limitation

How can I make a program wait for a modal window to close?

Essentially, I’m trying to recreate the “alert” and “prompt” functions, but in a single function that uses a modal window. I have it set up so that when one of the function’s parameters is set to 1, it adds a text field to the modal window and records that text field’s value when it closes. I’m having trouble making it so that when the window is opened, the program waits until the window is closed again. How can I do this?

Button Tittle Chnage

Button 01

              <Buttons
                  title={
                    !editPasswordState ? "Edit Full Password" : "Cancel"
                  }
                  outline
                  onClick={() => {
                    setEditPasswordState(!editPasswordState);
                  }}
                  class="
                    inline-flex 
                    justify-center 
                    py-2 px-4 border 
                    border-transparent 
                    shadow-sm text-sm 
                    font-medium rounded-sm 
                    text-white bg-red-400 
                    hover:bg-red-400 
                    focus:outline-black
                    focus:ring-2 
                    focus:ring-offset-2 
                    focus:ring-white"/>

Button 02

            <button
                onClick={handlePublishProductList}
                className={"inline-flex justify-center py-2 px-4 border border-transparent shadow-sm text-sm font-medium rounded-sm text-white bg-red-400 hover:bg-white hover:text-red-400 hover:border-red-400 focus:text-black focus:border-black"}>
                Publish
            </button>

I need to add button 01

 title={
!editPasswordState ? "Edit Full Password" : "Cancel"
        }

to Button 02 also, how can I do that? (Button one has a self-closing tag and button two has button start and button stop tags)

How do I show these “Personal Information” data inside the expandable row?

I wanted to try these out where the expandable row data came from the data itself where it will display these data inside the expandable row

  "Personal Information1",
  "Personal Information2",
  "Personal Information 3"

All examples that I’ve seen is that the data of the expandable row is not from the variable data itself.

How do I access the data of the 3 different personal informations in which these will be displayed inside the expandable row?

Codesandbox:
https://codesandbox.io/s/mui-datatables-expandable-rows-forked-ulf34d?file=/src/ExpandableRowTable.js:1378-1467

Codes:

  const options = {
    filter: true,
    onFilterChange: (changedColumn, filterList) => {
      console.log(changedColumn, filterList);
    },
    selectableRows: "single",
    filterType: "dropdown",
    responsive: "scrollMaxHeight",
    rowsPerPage: 10,
    expandableRows: true,
    renderExpandableRow: (rowData, rowMeta) => {
      console.log(rowData, rowMeta);
      return (
        <React.Fragment>
          <tr>
            <td colSpan={6}>
              <TableContainer component={Paper}>
                <Table style={{ minWidth: "650" }} aria-label="simple table">
                  <TableHead>
                    <TableRow>
                      <TableCell>Pesonal Information 1 label</TableCell>
                      <TableCell align="right">
                        Pesonal Information 2 label
                      </TableCell>
                      <TableCell align="right">
                        Pesonal Information 3 label
                      </TableCell>
                    </TableRow>
                  </TableHead>
                  <TableBody>
                    {rows.map((row) => (
                      <TableRow key={row.name}>
                        <TableCell component="th" scope="row">
                          {row.name}
                        </TableCell>
                        <TableCell align="right">{row.calories}</TableCell>
                        <TableCell align="right">{row.fat}</TableCell>
                      </TableRow>
                    ))}
                  </TableBody>
                </Table>
              </TableContainer>
            </td>
          </tr>
        </React.Fragment>
      );
    },
    page: 1
  };

  return (
    <MUIDataTable
      title={"ACME Employee list"}
      data={data}
      columns={columns}
      options={options}
    />
  );
};

export default ExpandableRowTable;

Is it possible to style grid gap and especially just between columns?

I want to highlight column gaps somehow so it looks like separated.
So e.g. I want the gap be in red color between columns and no color between rows.
Setting borders to each element in grid makes the border lines intermittent.
So I thought there should be a way to style gap itself.

const Grid = styled.div`
  display: grid;
  grid-template-columns:  100px 50px 50px;
  grid-template-rows: 50px 50px 50px;
  grid-gap: 10px;
`;

POST request not posting the value of one property Javascript/jQuery

I am playing with jQuery and Javascript. Working on a TODOs app using li items and with this API: https://jsonplaceholder.typicode.com/todos. I receive 200 items from this API.
I am trying to post a new item created with a click from the button (btn-add) and everything works as expected, with the exception that the post request is leaving in blank one property which is “title”. Here is my HTML and JS 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">
    <link href="/CSS/styles.css" rel="stylesheet">
    <title>TO DO List</title>
    <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
    <script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
    <script src="/JS/index.js"></script>
</head>
<body>
    <div id="inputDIV">
        <input id="input" type="text" placeholder="Enter new item">
    </div>
    <div id="buttons">
        <button id="btn-add">Add List Item</button>
        <button id="btn-update">Update First Item</button>
        <button id="btn-delete">Delete First Item</button>
    </div>
    <div id="ulDIV">
        <ul id="list">
           <!-- Here we will insert the list items via JS-->
        </ul>
    </div>
    
</body>
</html>

$(document).ready(function(){  
    let inputNew = $('#input');
    let list = $('#list');
    let currentInputValue = "";
    $('#btn-add').click(createTODOItemAtBackend);
    inputNew.on({
        "input": function(e){
            console.log(e.target.value);
            currentInputValue = e.target.value;
        },
        "keyup": function(e){
            if(e.keyCode === 13){
                createTODOItemAtBackend();
            }
        }
    })
    getTODOListFromBackend();
    function clearInputData(){
        inputNew.val("");
        currentInputValue = "";
    }
    function createTODODynamically(id, title){
        let newListElement = document.createElement("li");
        let textNode = document.createTextNode(title);
        newListElement.appendChild(textNode);
        newListElement.id = id;
        return newListElement;
        }
    function getTODOListFromBackend(){
        $.get("https://jsonplaceholder.typicode.com/todos", function(data, status){
            let response = data;
            for(let i=0; i < response.length; i++){
                list.append(createTODODynamically(response[i].id, response[i].title));
            }
        });
    }
    let obj = { 
        "userId": 1,
        "title": currentInputValue,
        "completed": false
    };
    function createTODOItemAtBackend(){
        $.post("https://jsonplaceholder.typicode.com/todos", obj, function(data, status){
            let response = data;
            list.append(createTODODynamically(response.id, currentInputValue));
            console.log("Item Added to the list!");
            clearInputData();
        });
    }
    })

And this is what I see when I read the post information in the web browser:

{userId: "1", title: "", completed: "false", id: 201}
completed: "false"
id: 201
title: ""
userId: "1"

Can somebody help me, why is the property “title” being posted as empty? Thanks in advance

D3 – How can I put an SVG into a DIV via a function?

To reuse code I want to put my SVG into a function and call it as needed. Once I select the DIV what is the appropriate construct to render the SVG inside it?

...

if (intLocations.includes(comm.location)) {
  const intActivities = d3.select('div#intActivities')
  intActivities.append(Pill(comm))
} else {
  const extActivities = d3.select('div#extActivities')
  actActivities.append(Pill(comm))
}

...

function Pill(comm) {
   const svgNode = d3.create('svg')
   svgNode
       .attr('width', 100)
       .attr('height', 100)
       .append('g')
       // More code to draw the figure using comm data.
   return svgNode;
   }