Create new page [closed]

I’m trying to make content management system for blog. How can I make a new page using my template for the page, with a press of button, to generate new post in new page? I’m using HTML, CSS, JavaScript, local storage.

I know how to create, read, update, delete content in the same page. I tried this code in other post, but it doesn’t save on my local storage:

var w = window.open("");
w.document.writeln("<the html you wanted to write>")

Event loop: execution order

I’m having a hard time understanding the execution order of the code that has asynchronous elements in it. Here’s the problematic code:

const promise = new Promise(function(resolve, _){
    resolve('microtask2');
}).then((res)=> {
    console.log(res);
}).catch((err)=> console.error(`caught an ${err}`));

const timer = setTimeout(function(){
    console.log('set timeout');
}, 0);

for(let i = 0; i < 1000; i++){
    console.log(`cicle 1: ${i}`);
}

const result = await new Promise(function(resolve, _){
    try{
        resolve('microtask1');
    }
    catch(err){
        console.error(`caught an ${err}`);
    }
});


for(let i = 0; i < 1000; i++){
    console.log(`cicle 2: ${i}`);
}

At the beginning I thought that event loop executes code in the following order:

  1. all synchronous code
  2. microtask queue
  3. macrotask queue

And it appears to work exactly so if I comment out result promise:

output: loop1 --> loop2 --> microtask2 --> set timeout

But if I keep the result the callback from multitask is printed out in between the loops (where it is defined) without waiting for all the synchronous code to finish:

output: loop1 --> microtask2 --> loop2 --> set timeout

What am I missing here? Is this behaviour somehow related to the blocking nature of await?

How can I make JSDoc/TypeScript understand JavaScript imports?

I have added // @ts-check to a JavaScript file to use JSDoc. Suddenly I get errors in VS Code for functions included with a script tag:

<script src="imported-file.js"></script>

I can silence these by adding a lot of // @ts-ignore (or maybe other ways?). But that would in my case just make JSDoc/TypeScript a burden.

So instead I wonder what types of ES6 includes/imports JSDoc/TypeScript can handle in VS Code. Can it handle module imports like this one below?

<script type="module" src="imported-file.js"></script>

Can it handle dynamic imports?

const myImportedModule = await import("imported-file.js");

Is there any good documentation about this?

Is there a way I can use npm with the direct source code rather than minified/bundled code?

I want to use npm and JavaScript (or TypeScript) 3rd party libraries directly from the source code.

For example, in Python, I can go directly into the source code make changes in them and see it directly reflected in my application. I want the same functionality with JavaScript because this helps me understand what’s going on with my 3rd party dependencies.

Quasar table header selection value always true

I’m working with vuejs and quasar and I find something. In this component Im using quasar table with multiple selection The header selection is not working as expected. I’m trying to exclude rows with a specified value for ‘deleted’, but the ‘selectAll’ value always evaluates to true. So, when I attempt to deselect all the rows, it doesn’t happen. logging selectAll always gives true.

<template>
  <q-table
    class="invoices-sticky-header-table"
    :rows="filteredInvoices"
    :columns="columns"
    row-key="invoiceId"
    :rows-per-page-options="rowsPerPageOptions"
    :selected-rows-label="getSelectedString"
    :pagination="pagination"
    binary-state-sort
    selection="multiple"
    v-model:selected="selectedRows"
    @update:selected="OnSelectedRowsChangedHandler"
  >
    <template v-slot:header-selection="props">
      <q-checkbox
        :model-value="props.selected"
        @update:model-value="
          (val, evt) => {
            props.selected = val;
            selectFilteredInvoices(val, evt);
          }
        "
      />
    </template>
  </q-table>
</template>
<script lang="ts">
import { type PropType, ref, defineComponent } from "vue";
import type { Invoice, VendorBasic } from "../../interfaces";

export default defineComponent({
  name: "InvoiceTable",
  props: {
    filteredInvoices: { type: Object as PropType<Invoice[]>, required: true },
    vendors: { type: Object as PropType<VendorBasic[]>, required: true },
    maxInvoicesForBulkActions: {
      type: Object as PropType<number>,
      required: true,
    },
  },
  emits: ["onPaid", "onApprove", "onDelete", "onSelectedRowsChanged"],
  setup(props, { emit }) {
    const selectedRows = ref<Invoice[]>([]);
    function formatDateTime(dateTimeString: string) {
      if (!dateTimeString) {
        return dateTimeString;
      }
      const newDate = new Date(dateTimeString);
      return (
        newDate.toLocaleDateString("en-GB", {
          day: "2-digit",
          month: "short",
          year: "numeric",
        }) +
        ", " +
        newDate
          .toLocaleTimeString("en-GB", {
            hour: "2-digit",
            minute: "2-digit",
            hour12: true,
          })
          .toUpperCase()
      );
    }
    const onDeleteHandler = (invoiceId: number) => {
      emit("onDelete", invoiceId);
    };

    const onApproveHandler = (invoice: Invoice) => {
      emit("onApprove", invoice);
    };

    const onPaidHandler = (invoice: Invoice) => {
      emit("onPaid", invoice);
    };

    const OnSelectedRowsChangedHandler = (rows: readonly any[]) => {
      emit("onSelectedRowsChanged", rows);
    };

    const getSelectedString = (numberOfRows: number) => {
      let message = `${numberOfRows} rows are selected. Bulk actions are available for maximum 5.`;

      if (numberOfRows > props.maxInvoicesForBulkActions) {
        message = `${message} Please unselect some.`;
      }

      return message;
    };

    const rowsPerPageOptions = ref<number[]>([100, 200, 500]);

    const columns = [
      {
        name: "id",
        align: <"left" | "right" | "center">"center",
        label: "Id",
        field: (row: Invoice) => row.invoiceId,
        sortable: true,
      },
      {
        name: "code",
        align: <"left" | "right" | "center">"center",
        label: "Code",
        field: (row: Invoice) => row.invoiceCode,
        sortable: true,
      },
      {
        name: "url",
        align: <"left" | "right" | "center">"center",
        label: "File URL",
        field: (row: Invoice) => {},
        sortable: true,
      },
      {
        name: "vendorName",
        label: "Vendor",
        align: <"left" | "right" | "center">"left",
        field: (row: Invoice) =>
          props.vendors
            ?.find((v: VendorBasic) => v.vendorId == row.vendorId)
            ?.username.split("(")[0]
            .trim(),
        sortable: true,
      },
      {
        name: "creationDate",
        label: "Creation Date",
        align: <"left" | "right" | "center">"left",
        field: (row: Invoice) => formatDateTime(row.created),
        sortable: true,
      },
      {
        name: "invoiceTotal",
        label: "Total",
        align: <"left" | "right" | "center">"left",
        field: (row: Invoice) => row.invoiceTotal,
        sortable: false,
      },
      {
        name: "approved",
        align: <"left" | "right" | "center">"center",
        label: "Approved",
        field: () => {},
      },
      {
        name: "paid",
        align: <"left" | "right" | "center">"center",
        label: "Paid",
        field: () => {},
      },
      {
        name: "deleted",
        align: <"left" | "right" | "center">"center",
        label: "Deleted",
        field: () => {},
      },
    ];

    const pagination = {
      rowsPerPage: 200,
      sortBy: "id",
      descending: true,
    };

    const selectFilteredInvoices = (selectAll: boolean, evt: any) => {
      console.log(selectAll);
      if (selectAll) {
        selectedRows.value = props.filteredInvoices.filter(
          (row) => !row.deleted
        );
      } else {
        console.log("hello reached");
        selectedRows.value = [];
      }
    };

    return {
      selectFilteredInvoices,
      formatDateTime,
      columns,
      pagination,
      rowsPerPageOptions,
      onDeleteHandler,
      onPaidHandler,
      onApproveHandler,
      getSelectedString,
      OnSelectedRowsChangedHandler,
      selectedRows,
    };
  },
});
</script>

<style lang="sass" scoped>
.button-table
  font-size: 10px
.date-text
  margin: 0px
</style>

Commetting this piece of code concerning filtering the selectedRows make the selectAll change its value so this line is the problem,

selectedRows.value = props.filteredInvoices.filter(
          (row) => !row.deleted

Hide elements with jquery

I would like to hide individual element blocks that are identified by id`s.

I have used a jquery function to do this.


<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name=”apple-mobile-web-app-capable” content=”yes “>
    <script type="text/javascript" src="http://code.jquery.com/jquery-3.7.1.min.js"></script>
    
    <script>

    function changeMenu(menu){
        $('#Slide_home').css({'display':'none'});
        $('#Slide_sub01').css({'display':'none'});
        $('#Slide_sub02').css({'display':'none'});  
        $('#Slide_'+menu).css({'display':'block'});
        }

    </script>

    <style>
    body { 
        margin: 0px; 
        padding: 0px; 
        background-color: rgb(53, 61, 64);  
        color: rgb(255, 255, 255); 
        height: 100%; 
        overflow-x: hidden; 
    } 

    #Menu {
        position: fixed;
        bottom: 0px;
        width: 100%;
        height: 100px;
        background-color: rgb(0, 0, 0);
        
        }
        
    .ButtonWrapper {
    display: flex;
    flex-direction: row;
    justify-content: center;
    text-align: center;
    }      
        
    .ButtonWrapper > div {
    margin-left: 50px;
    margin-top: 10px;  
    }
    </style>
      

</head>


<body>

<div id="Slide_home"> 

home
            
</div>

<div id="Slide_sub01">

01

</div>

<div id="Slide_sub02"> 

02

</div>

<div id="Menu">          
    <div class="ButtonWrapper">
        <div>
            <img class="" style="cursor:pointer" onClick="changeMenu('home');" src="01.png" alt="home"/>
        </div>

        <div>
            <img class="" style="cursor:pointer" onClick="changeMenu('sub01');" src="02.png" alt="sub_01"/>
        </div>

        <div>
            <img class="" style="cursor:pointer" onClick="changeMenu('sub02');" src="03.png" alt="sub_02"/>
        </div>
    </div>
</div>
                         
</body>
</html>

In principle the function works, when I press a button the corresponding other elements are hidden. But at the beginning all elements are visible. How can I display only the elements for home at the beginning?

Best regards
Jens

const data = Object.fromEntries(formData);

How to add an array to the last in this object:

const formElment = document.querySelector(".form");

formElment.addEventListener("submit", (event) => {
  event.preventDefault();

  var array = [];
  var checkboxes = document.querySelectorAll("input[type=checkbox]:checked");

  for (var i = 0; i < checkboxes.length; i++) {
    array.push(checkboxes[i].value);
    console.log(checkboxes[i].id);
  }

  const formData = new FormData(formElment);
  const data = Object.fromEntries(formData);
  
  console.log(data);

});

I used eventlistner for get form data and checkbox=checked. So now I want add those selected checkbox id to the end of the object and send through an API.

Asp.Net MVC -How does Javascript pick up a pasted Url and use it to test the Url via a button click

I’m using an Asp.net 6 MVC driven project. People submitting a video to a show are asked to paste the url and then click a button to test that the url works. This is the code that collects the url:

<label class="control-label" style="font-size:12"><strong>Video Link </strong><small> [Paste link to URl, use Test Video Link to test that link works before </small></label>
<input asp-for ="VideoLink1" id="videolink1" type="url" class="form-control" placeholder="Video Link - URL or Vimeo" style="font-size:medium">
<span asp-validation-for="VideoLink1" class="text-danger"></span>

<i class="fa fa-video"></i> <input name="testvideolink" class="btn btn-group-sm btn-info" id="testvideolink" style="font-size:smaller" value="Test Video Link" onclick="ViewURL()">

This is then picked up by script which should open the url in a separate web page:

function ViewURL() {
var url = document.getElementById('videolink1');
window.open(url, "_blank")

The simplest way to deal with this would be send it to the controller and then get the user to click the test button when it returns from the controller but this seems a bit clunky. However, videolink1 does not have the url without running it through the controller. I’ve tried various ways of trying to get the url name from the unsubmitted asp-for but have not found a way.

Update all dataset source with event listener

I’m trying to update the dataset when I click on a button (btnTest), but the update function updateF2(); is not working when I click on this button. I need to update the entire dataset based on changes that occur. The variable is defined in r with jsonlite::toJSON(…). Full code:

library(shiny)

ui <- HTML(paste0(
  "<head>
  <script src='https://cdn.jsdelivr.net/npm/[email protected]/dist/echarts.min.js'></script>
  </head>

  <div style='display: grid; grid-template-columns: repeat(12, 1fr);'>

  <div style='grid-column: span 12;'>
  <div style='display: grid; grid-template-columns: repeat(12, 1fr); grid-gap: 15px;'>

  <div style='grid-column: span 6; background-color: #ff9000;'>
  <h2>Inputs</h5>
  <hr>
  <input id='input1' type='number' value='30'>
  <input id='input2' type='number' value='12'>
  <input id='input3' type='number' value='45'>
  <input id='input4' type='number' value='58'>
  <button id='btnTest'>Update</button>
  </div>

  <div id='testPlot' style='height: 400px; width: 400px;
  grid-column: span 6; display: block; margin: auto;'>",
  uiOutput(outputId = "outputTest"),
  "</div>

  </div>
  </div>

  </div>"
))

server <- function(input, output, session) {

  output$outputTest <- renderUI({

    x <- jsonlite::toJSON(c("Milk tea", input$input1, input$input2, input$input3, input$input4))

    HTML(paste0(
      "<script>
      const testPlotUse = echarts.init(document.getElementById('testPlot'));

      // Definindo o JSON do dataset com o valor inicial do input value1
      let dataset = {
        source: [",
          x,
        "]
      };

      // update plot function
      function updateF1(dataset) {
        let option = {
          series: [{
            type: 'gauge',
            min: 0,
            max: 60,
            splitNumber: 6,
            data: [
              {value: dataset.source[0][1]},
              {value: dataset.source[0][2]},
              {value: dataset.source[0][3]},
              {value: dataset.source[0][4]},
            ]
          }]
        };
        testPlotUse.setOption(option);
      };

      function updateF2() {
        let dataset = {
          source: [",
            x,
          "]
        };
        updateF1(dataset);
      };

      $('#btnTest').on('click', function() {
        updateF2();
      });

      updateF2();

      </script>"
    ))

  })

}

shinyApp(ui, server)

blank page when try using useState in button with react


const Button = () =>{
    return (
            <button>My Button</button>
    )
}

export default Button
import React from 'react'
import './App.css'
import Button from "./components/button"
import Image from './components/image'
import { useState } from "react"

const [count, setCount] = useState(0)

const handlerClick = () => {
    setCount(count + 1)
}


const App = () =>{
  return (
    <>
      <Button count ={count} onClick ={handlerClick}/>
    </>
  )
}

export default App
import React from 'react'
import ReactDOM from 'react-dom/client'
import App from './App.jsx'
import './index.css'

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
)

i starting to learn react and i try to made button with useState for adding number( i followed the react documentation, but i have create the button with components, import it into the app file, and import the app file into main.jsx for the root. Why my web page is still blank?

How to get a sticky Scrollbar in CSS / Javascript when scrolling inside nested divs

I have a table over which I need to be able to scroll vertically as a whole. In this table there are 2 columns over which I need to be able to scroll horizontally (individually).
But the 2 horizontal scrollbars disappear at the bottom of the table because of the vertical scrollbar.

How do I get those to be visible at all times?

Here’s the fiddle Example: Fiddle Example

enter image description here

#data {
  background: grey;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  
  height: 400px;
  width: 500px;
}

#splitter {
  display: flex;
  flex-direction: row;
  background: darkgrey;
  overflow-x: hidden;
  overflow-y: auto;
  align-items:start;
}

#right-content {
  background: Gainsboro;
  overflow-x: auto;
  overflow-y: hidden;
}

#left-content {
  background: Gainsboro;
  overflow-x: auto;
  overflow-y: hidden;
}

div {
  margin: 10px;
}

p {
  padding: 2px;
  margin: 0px;
}
<div id="data">
  <div id="splitter">
    <div id="left-content">
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
      <p>LeftColumnLeftColumn</p>
    </div>
    <div id="right-content">
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>
      <p>RightColumnWithLongTextThatShouldBeScrollableHorizontally</p>          
    </div>
  </div>
</div>

trouble while reading JS File

HTML code
HTML file Name index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Counter</title>
    <script src="counter_funtions.js"></script>
    <link rel="stylesheet" href="Style.css" type="text/css">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-QWTKZyjpPEjISv5WaRU9OFeRpok6YctnYmDr5pNlyT2bRjXh0JMhjY6hW+ALEwIH" crossorigin="anonymous">
</head>
<body>
    <div class="d-flex flex-row justify-content-center padding">
    <div class="text-center transparent p-4">
        <div>
            <h1 class="heading">Counter</h1>
            <p class="numbers" id="counterValue">0</p>
            <div>
                <button class="button" onclick="onDecrement()">DECREASE</button>
                <button class="button" onclick="onReset()">RESET</button>
                <button class="button" onclick="onIncrement()">INCREASE</button>
            </div>
        </div>
    </div>    
    </div>
</body>
</html>

JS Code
JS file name counter_funtions.js

let counterElement = document.getElementById("counterValue");
console.log(counterElement);

and the output is

[Running] node "d:JavaSciptProject-3 Counter Appcounter_funtions.js"
d:JavaSciptProject-3 Counter Appcounter_funtions.js:1
let counterElement = document.getElementById("counterValue");
                     ^

ReferenceError: document is not defined
    at Object.<anonymous> (d:JavaSciptProject-3 Counter Appcounter_funtions.js:1:22)
    at Module._compile (node:internal/modules/cjs/loader:1369:14)
    at Module._extensions..js (node:internal/modules/cjs/loader:1427:10)
    at Module.load (node:internal/modules/cjs/loader:1206:32)
    at Module._load (node:internal/modules/cjs/loader:1022:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:135:12)
    at node:internal/main/run_main_module:28:49

Node.js v20.12.2

[Done] exited with code=1 in 0.083 seconds

trying to Run JS code expecting 0 as output.

Is it a good practice to use ready() Method inside an If-else block to call a function?

I am tryin to call the test() function onload. This is how I am doing it:

if ($('.partical .sectionA').length) {
    $(document).ready(function(){
        test($(this));
    });
 }
test(something){...}

I find it odd to use a ready() method inside an If Else statement and I am wondering if this is a good practice or is there a better way to call the test function on page load?

backend php e-commerce with gatsby on wordpress

I want to make a small one-page online store. The site implies only a shopping cart with the product and its payment, as well as search. I would still like to implement authorization, but I am ready to give it up. At the front side, I want to use react with ssg from gatsby. Bit i am not good with backend and I want to use wordpress as cms. I had a problem at the architecture construction stage. I don’t understand how to integrate the front with the basket. Do I need to install a default theme? Or do I need to do the layout from scratch and the plugins allow me to integrate the shopping cart?

  1. I found this topic. Perhaps I can use it to implement the necessary functionality? enter link description here
  2. Perhaps it will be easier make it with elemetnor (which I do not want) or basic html+css+js?
    In fact, I have no problems with the layout of the front on the react. But I can’t figure out how to integrate backend into it using plugins. Thanks for the help.