JavaScript how to log the value a user has put in? [closed]

The problem given was:

When the user clicks the button with the ID of generate-message, log the value the user has typed into the input field.

Here is the HTML provided:

 <input type="text" id="message">
 <button id="generate-message">Express Yourself!</button>

I have tried multiple things, my most recent attempt was:

 const button = document.getElementId("generate-message")
 button.addEventListener("click", function(){
 })

Register shiny checkboxInput value by text

I follow this question Register shiny checkboxInput value on DT, but I couldn’t figure out how to use text “Included” for TRUE and “Excluded” for FALSE in column value.

library(shiny)
library(DT)

js <- c(
  "$('[id^=check]').on('click', function(){",
  "  var id = this.getAttribute('id');",
  "  var i = parseInt(/check(\d+)/.exec(id)[1]);",
  "  var value = $(this).prop('checked');",
  "  var cell = table.cell(i-1, 2).data(value).draw();",
  "})"
)

df <- data.frame(item = c("a", "b", "c"), value = c(TRUE, TRUE, TRUE))

shinyInput <- function(FUN, len, id, ...) {
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(FUN(paste0(id, i), label = NULL, ...))
  }
  inputs
}

## obtaining checkbox value
shinyValue = function(id, len) { 
  unlist(lapply(seq_len(len), function(i) { 
    value = input[[paste0(id, i)]] 
    if (is.null(value)) FALSE else value 
  })) 
} 

shinyCheckboxes <- function(len, id, checked){
  inputs <- character(len)
  for (i in seq_len(len)) {
    inputs[i] <- as.character(checkboxInput(paste0(id, i), label=NULL, 
                                            value = checked[i]))
  }
  inputs
}

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

  
  output$tbl <- renderDT(server = FALSE, escape = FALSE, editable = TRUE, 
                         callback = JS(js),
                         options = list(
                           dom = 't', paging = FALSE, ordering = FALSE,
                           preDrawCallback = JS('function() { Shiny.unbindAll(this.api().table().node()); }'),
                           drawCallback = JS('function() { Shiny.bindAll(this.api().table().node()); } ')
                         ), {
                           checked <- sapply(df$value, isTRUE)
                           df$value_check <- shinyCheckboxes(nrow(df), "check", checked)
                           #df$value_check <- shinyInput(checkboxInput, nrow(df), "check")
                           df
                         }
  )
  
  
  observeEvent(input$tbl_rows_selected,{
    print(input$tbl_rows_selected)
  })
}

ui <- fluidPage(
  DTOutput("tbl")
)

shinyApp(ui, server)

Desired output:

enter image description here

How we can use “Included” for TRUE and “Excluded” for FALSE in column value?

how to add to card and fetch data checkout card

Data Fetching:
I have integrated an API call to fetch dynamic product or item data from the backend. The fetched data is then displayed on each individual card component in the UI, allowing for real-time updates and ensuring seamless user interaction. The fetching process is optimized with the use of useEffect and axios to ensure efficient and scalable data handling.

enter image description here

PDF Flipbook not re rendering upon window resize of turnjs

I’m using turnjs 4 and pdfjs to create a pdf flipbook. Currently it’s working fine on initial rendering. But the problem is upon window resize or at the time of checking responsive of the page in browser causing flipbook break which automatically disappears by leaving blank space.

How to handle this problem specially on window resize event occurs.

I’m providing the implementation code below

class PDFFlipbook {
    constructor(pdfUrl, containerClass) {
        this.pdfUrl = pdfUrl;
        this.container = document.querySelector(containerClass);
        this.zoomLevel = 1.5; // Default zoom level
        this.isZoomedIn = false; // Track zoom state
        this.init();
    }

    async init() {
        // Prepare the flipbook container
        this.container.innerHTML = '';
        const flipbook = document.createElement('div');
        flipbook.className = 'flipbook';
        this.container.appendChild(flipbook);

        // Render each page of the PDF and add to flipbook
        await this.renderPages(flipbook);

        // Initialize the flipbook
        this.initializeFlipbook();

        // Setup click zoom control
        this.setupClickZoom();
    }

    async renderPages(flipbook) {
        flipbook.innerHTML = '';

        // Load the PDF document
        this.pdf = await pdfjsLib.getDocument(this.pdfUrl).promise;

        const canvases = []; // Array to hold canvases for later processing

        for (let pageNumber = 1; pageNumber <= this.pdf.numPages; pageNumber++) {
            const page = await this.pdf.getPage(pageNumber);
            const canvas = document.createElement('canvas');
            canvas.className = 'page';
            const context = canvas.getContext('2d');
            const viewport = page.getViewport({ scale: this.zoomLevel });

            canvas.width = viewport.width;
            canvas.height = viewport.height;

            await page.render({ canvasContext: context, viewport: viewport }).promise;
            canvases.push(canvas); // Store canvas for later
        }

        // Now append all canvases to the flipbook
        canvases.forEach(canvas => {
            flipbook.appendChild(canvas);
        });
    }

    initializeFlipbook() {
        const resizeFlipbook = async () => {
            let screenWidth = window.innerWidth;
            let containerWidth, containerHeight;

            // Get the first canvas to calculate the aspect ratio
            const canvas = this.container.querySelector("canvas");
            if (!canvas) return;

            const aspectRatio = canvas.width / (canvas.height / 2);

            // Adjust width based on screen size
            if (screenWidth <= 480) {
                containerWidth = screenWidth * 0.9;
            } else if (screenWidth <= 768) {
                containerWidth = screenWidth * 0.8;
            } else {
                containerWidth = screenWidth * 0.6;
            }

            containerHeight = containerWidth / aspectRatio;

            const flipbookElement = $(this.container.querySelector('.flipbook'));

            if (flipbookElement.data('done')) {
                flipbookElement.turn('destroy');
            }

            // Set the container dimensions
            flipbookElement.css({
                width: containerWidth,
                height: containerHeight,
            });

            flipbookElement.turn({
                width: screenWidth <= 768 ? containerWidth / 2 : containerWidth,
                height: containerHeight,
                autoCenter: true,
                duration: 1000,
                elevation: 50,
                gradients: true,
                display: screenWidth <= 768 ? 'single' : 'double',
            });

            // Add CSS transitions for smooth zoom
            flipbookElement.css({
                transition: 'transform 0.5s ease-in-out',
                transformOrigin: 'center center',
            });
        };

        resizeFlipbook();
        window.addEventListener('resize', () => {
            clearTimeout(this.resizeTimeout);
            this.resizeTimeout = setTimeout(() => {
                resizeFlipbook();
            }, 250);
        });
    }

    setupClickZoom() {
        const flipbookElement = this.container.querySelector('.flipbook');
        flipbookElement.addEventListener('click', async (event) => {
            event.preventDefault();
            event.stopPropagation();                    
            const { left, top, width, height } = flipbookElement.getBoundingClientRect();
            const centralXStart = left + (width * 0.2);
            const centralXEnd = left + (width * 0.8);
            const centralYStart = top + (height * 0.2);
            const centralYEnd = top + (height * 0.8);

            const clickX = event.clientX;
            const clickY = event.clientY;

            if (clickX >= centralXStart && clickX <= centralXEnd && clickY >= centralYStart && clickY <= centralYEnd) {
                if (this.isZoomedIn) {
                    this.zoomLevel = 1.5;
                    flipbookElement.style.transform = 'scale(1)'; // Zoom out
                } else {
                    this.zoomLevel = 2.5;
                    flipbookElement.style.transform = 'scale(1.5)'; // Zoom in
                }

                this.isZoomedIn = !this.isZoomedIn;
            }
        });
    }
}

document.addEventListener('DOMContentLoaded', () => {
    const pdfUrls = [
        '../assets/improve-everyday.pdf',
        '../assets/sample1.pdf',
    ];

    new PDFFlipbook(pdfUrls[0], 'section[data-component-variant="pdfBook-v1"] div.container div.grid div.page div.flipbook-container');
    new PDFFlipbook(pdfUrls[1], 'section[data-component-variant="pdfBook-v1 topBar"] div.container div.grid div.page div.flipbook-container');
});

this is the html snippet

<section
        data-component-set="basic"
        data-component-group="oneCol"
        data-component-variant="pdfBook-v1"
        data-config-style=" "
        data-config-style-variant=" "
        class="--component full-bleed mediumColorBG">
    <div class="container">
        <div class="grid --oneCol _gap-2">
            <div class="txtBox --textAlign _center">
                <h2 class="title">Demo Title</h2>
                <p class="--ellipsis _3">
                    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ab architecto dolorem eum illo
                    nihil rem soluta? Accusamus alias consectetur debitis earum ex iste perspiciatis quisquam
                    sint tempore, voluptatem. Recusandae, voluptatum.
                </p>
            </div>
            <div class="page">
                <div class="flipbook-container"></div>
            </div>
        </div>
    </div>

</section>

while resizing the the window for checking responsiveness I’m getting the below error which is causing a problem for flipbook which disappears after.

error in console tab

I’m using the below turnjs code from turnjs.com – http://www.turnjs.com/lib/turn.min.js

How to understand that there is a photo in the buffer JavaScript

I want to determine that when I click on the Print Screen button on keyboard, is it written to the console whether it’s a image or not? Needs use buffer like

const checkHaveImageInClipboar = async () => {
        try {
            const clipboardItems = await window.navigator.clipboard.read();
            return clipboardItems[0].types.some(type => /image/.test(type));
        } catch (err) {
            return false;
        }
    };

It is on the button on the keyboard, and not on the button in the DOM . Because there may be a situation where you clicked on the screenshot on the keyboard, but the screen didn’t work, and I just want to check
if there is a photo in the buffer, then output ‘photo’, otherwise output ‘not photo’ . Please help me

How do I make a popstate event work for Shopify?

I have the following conditions for popstate, but the problem is that popstate doesn’t fire when the back button is clicked. This is the code for Shopify. Maybe someone has ideas on how to fix my code so that it works, or you can replace popstate with another event.

window.addEventListener('load', function() {
        if (!window.history.state) {
            history.replaceState({ page: document.URL }, null, document.URL);
        }

        // let popstateTriggered = false; 
        // let popstateTimeout = setTimeout(function() {
        //     if (!popstateTriggered) {
        //         let previousCollectionData = JSON.parse(localStorage.getItem('collectionData')) || [];

        //         if (previousCollectionData.length > 2) {
        //             previousCollectionData = previousCollectionData.slice(0, 2);
        //         }
        //         localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));
        //     }
        // }, 0);

        window.addEventListener('popstate', function(event) {
          let previousCollectionData = JSON.parse(localStorage.getItem('collectionData')) || [];
          console.log('welllllll' + event)
            previousCollectionData = previousCollectionData.slice(0, -1);
            localStorage.setItem('collectionData', JSON.stringify(previousCollectionData));

            if (previousCollectionData.length > 0) {
                window.location.href = previousCollectionData[previousCollectionData.length - 1].url;
            } else {
                window.location.href = "/";
            }
        });
    });

P.S The event is triggered if I click on any random place on the page I want to leave. maybe there is an opportunity to somehow generate some kind of action that the page itself performs and launches popstate

Why do I have this error in production mode in ReactJS App: Uncaught TypeError: Cannot read properties of null (reading ‘useState’)?

I’m encountering an issue in my ReactJS application where the following error appears only in the production build.
And I don’t know how to fix it because it’s so general :
Uncaught TypeError: Cannot read properties of null (reading ‘useState’)
Things I’ve tried:
Ensured that I have React and ReactDOM installed at the correct versions.
Checked my project setup for any invalid React versions or corrupted dependencies.
Verified that I’m correctly importing useState from react.

Does anyone have an idea of what could cause this issue, or how to debug it in a production build?”

switching from chrome:// to http:// protocol

I’m setting up a pretty insignificant script to be run from bookmark bar in google chrome. The script is supposed to automatically upload a specified page at a specified interval.
I came up with the main part already, thing is that most of the time the script is going to run in a “new tab” page in google chrome (“chrome://newtab” or “chrome://new-tab-page” to be exact) and the location.href function I set up in the script doesn’t work.
It seems that the script has some difficulties with switching from a chrome:// to http:// protocol, as if location.href didn’t support it.
What can I do? I tried to look into the chrome proprietary functions but I didn’t get much. I already look up for previous topics but didn’t find any, it’s a pretty peculiar subject.

Thanks

here’s the script

javascript: (()=>{location.href="http://PAGE";timer1 = setInterval(
function(){location.href="PAGE"},5*60*1000);})();

HTML2Canvas and Dom-to-Image Not Capturing Scrolled Content Correctly for PDF Export

I am trying to export visible parts of a webpage to PDF using JavaScript. My content includes elements like tables and charts that often have scrolled views. I’ve attempted to use both html2canvas and dom-to-image to capture the content, but both libraries reset scroll positions to the top-left corner (0, 0) instead of capturing the content as it is visible on the user’s screen.What I export
What I get exported

What I Tried:

html2canvas: I tried passing scrollX and scrollY parameters adjusted to match the current scroll position of the content. Despite this, the resulting image still captures the content from the top, ignoring the actual scroll position.

html2canvas(content, {
  scrollX: -content.scrollLeft,
  scrollY: -content.scrollTop,
  width: content.clientWidth,
  height: content.clientHeight
});

dom-to-image: I used dom-to-image with similar parameters, hoping it might handle dynamic content better. However, the issue persisted with similar results.

domtoimage.toPng(content, {
  height: content.clientHeight,
  width: content.clientWidth
});

Full function code:

export const exportAsPDFSingleReport = async (
  content,
  fileName,
  fileType,
  screenWidth
) => {
  const MAX_IMAGE_WIDTH = 2000;
  const MAX_IMAGE_WIDTH_HALF_SCREEN = 1000;
  const IMAGE_WIDTH_OFFSET = 100;

  const childDiv = content.querySelector("div");
  const reportType = childDiv ? childDiv.dataset.reporttype : null;
  let currentWidth;

  if ((reportType !== reportTypes.PieChart && reportType !== reportTypes.CreatedVsResolved) || screenWidth <= 1149) {
    currentWidth = Math.min(MAX_IMAGE_WIDTH, screenWidth - IMAGE_WIDTH_OFFSET);
  } else {
    currentWidth = Math.min(MAX_IMAGE_WIDTH_HALF_SCREEN, screenWidth / 2 - 5);
  }

  content.setAttribute("style", `width: ${currentWidth}px`);

  try {
    const canvas = await html2canvas(content, {
      scrollX: -content.scrollLeft,
      scrollY: -content.scrollTop,
      width: content.clientWidth,
      height: content.clientHeight,
      windowWidth: content.scrollWidth,
      windowHeight: content.scrollHeight,
      backgroundColor: null,
      useCORS: true
    });
    const imgData = canvas.toDataURL("image/png");

    const img = new Image();
    img.src = imgData;
    img.onload = function () {
      const imageWidth = img.width;
      const imageHeight = img.height;
      const orientation = imageHeight > imageWidth ? "p" : "l";
      const pdf = new jsPDF({
        orientation,
        unit: "px",
        format: [imageWidth, imageHeight]
      });
      pdf.addImage(imgData, "PNG", 0, 0, imageWidth, imageHeight);
      pdf.save(`${fileName}.${fileType}`);
    };
  } catch (error) {
    console.error("Error exporting as PDF:", error);
  } 
};

Expected Results: The libraries should capture the part of the webpage that is currently visible to the user, respecting the current scroll position in both vertical and horizontal directions.

Actual Results: The captured image resets to the top-left corner of the content area, ignoring any user-applied scroll, thus not reflecting the visible area intended for export.

Creating a Standalone Full-Stack App with Vanilla JS and MongoDB without Libraries, can it be done? [closed]

I know my way in HTML, CSS, and JS; I have mongoDB and I want to build a full stack application without any additional library, plain vanilla JS, this app will run offline on a stand alone computer with no internet access, I want to be able to connect to the back end, send, request, delete and modify data if necessary. And as context this will be an app that will allow an admin person to keep track of students, classes, projects, completion, events, notifications and more. But I have an error accessing XMLHttpRequest between my localhost server and my localhost client, and obviously I’m not able to POST new data in my server side.


//App.js
const serverURL = 'https://localhost:3031';

function sendData(data) {
  const xhr = new XMLHttpRequest();
  xhr.open('POST', serverURL, true); 
  xhr.setRequestHeader('Content-Type', 'application/json');

  xhr.onload = function() {
    if (xhr.status === 200) {
      const response = JSON.parse(xhr.responseText);
      console.log(response);  
      document.getElementById('response').textContent = 'Data saved successfully';
    } else {
      console.error('Error: ' + xhr.status);
      document.getElementById('response').textContent = 'Error sending data';
    }
  };

  xhr.onerror = function() {
    console.error('Network error');
    document.getElementById('response').textContent = 'Network error';
  };

  xhr.send(JSON.stringify(data));
}


//Server.js
const express = require('express');
const mongoose = require('mongoose');

const app = express();
const port = 3031; 

mongoose.connect('mongodb://localhost:27017/testingDB', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => console.log('MongoDB connected'))
  .catch(err => console.error(err));   

app.use(express.json());

app.post('/data', (req, res) => {
  const data = req.body; 
  console.log(data);

  const newData = new YourDataModel(data);
  newData.save()
    .then(savedData => {
      res.json({ message: 'Data saved successfully', data: savedData });
    })
    .catch(err => {
      res.status(500).json({ error: 'Error saving data', message: err.message });
    });
});

app.listen(port, () => {
  console.log(`Server listening on port ${port}`);
});

// I expected to be able to post my data in my newly created schema(omitted code)`

How to extract value that is thrown from an error object [closed]

I am using typescript. The code is as follows

if (!response.ok)  {
      const errorData = (await response.json());
      throw {
        foo: "bar",
        error: errorData
      };
}

When i try to parse the object it is displayed as follows

catch (error: any) {
        console.log(error) //returns Error: {foo: "bar", error: ..., digest: ...}
        console.log(error.message); // returns {foo: "bar", error: ..., digest: ...}
        console.log(error.foo); //undefined
        console.log(error.message.foo); // undefined

    }

How do i extract the value of foo from the error data?

Next.js – Error: The default export is not a React Component in page: “/”

I’m hoping you can help me because this is driving me mad. Making a react redux web app that I’ve set up using Next.js app-router with javascript. I feel like I have exhausted all troubleshooting suggestions. Is there something that has worked for one of you?

(see below for what I tried)

layout.js:

import './globals.css';
import { Provider } from 'react-redux';
import { store } from '@/store/store';

export const metadata = {
  title: "Hall of Game",
  description: "Generated by create next app",
};

export const RootLayout = ({ children }) => {
  return (
    <html lang="en">
      <body>
        <Provider store={store}>
          {children}
        </Provider>
      </body>
    </html>
  );
}

page.js:

"use client";
import React from "react";
import { useSelector } from "react-redux";
import Header from "@/features/Header/Header";
import Filters from "@/features/Filters/Filters";
import GamesList from "@/features/Games/GamesList/GamesList";
import GameDetails from "@/features/Games/GameDetails/GameDetails";
import { selectCurrentGame } from "@/features/Games/gamesSlice";

const Home = () => {
  const selectedGame = useSelector(selectCurrentGame);
  return (
    <div>
      <Header />
      <main>
        <section>
          <Filters />
        </section>
        <section>
          {selectedGame ? <GameDetails game={selectedGame}/> : <GamesList />}
        </section>
      </main>
    </div>
  );
};

export default Home;

I’ve got export default Home at the bottom of page.js. I’ve removed node modules then re-installed. I have all the latest for next, react & react-rom in package.json. I even tried reverting to the out of the box code for layout.js & page.js that I saw render initially but it’s still returning the error.

Have an audio with other photo and paragraph on the page when i scroll to that section where the audio player is how can i activate autolay?

instead of the audio player playing right when the browser loads only during the scroll view. i put psdeu class of hover but it didnt work for autoplay

                      <style>
                      #musicPla:hover {
                  autoplay;
                      }

                   </style>

              
                     
                <body>
                <img src="pic1.jpg">
                 <p> my mom has a house on the hills with hot girls </p>


                    <img src="pic2.jpg">
             <p>my bestfriends birthday party last year </p>

                 <!-- not visible on the page at first due to photos-->
                 <audio controls  id="musicPla" <source src="dog.mp3" 
                  type="audio/mp3"> </audio>
                  </body>
                  </html>

 

so i was creating a html page. had a audio player with ophotos before that on the page and wanted the audio player to autoplay during scroll back

js : drop down menu keep drop and collapse [closed]

i am working on demo website https://byetna.com/ismailia/

drop down window works fine ..
drop down menu

if i got user defined error : like add more than 3 products in cart, i got error message not allowed to add > 3 products

after this message ,when click it again, the menu keeps drop and collapse

refresh the page it works normally again.
here

tried not working:
padding-bottom: 300px;
position: absolute;