How can I save radio button values to local file for a video gallery?

I’m building a video gallery which spans over 15 pages so far. My pages consists of a thumb for each video clip. Each page contains between 200 to 300 thumbs. When the thumb it selected, it opens a modal with pic, description & play button to view video. I’m using a star rating module called StarRate which gives each thumb a set of 5 stars to rate the video. Each star is a radio button which you can select to give each thumb the desired rating. All works as intended, but I need ability to load the values of the radio buttons when the page loads from a local file. I also need it to save all values whenever a rating is changed, overwriting the original file so it will be updated when the page is opened later. This runs on local machine and isn’t on a server and only runs locally, so I have no database available to store and retrieve the values. I am a beginner so any help you can provide would be greatly appreciated 🙂

This is an example of my code:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1"/>

<title>Video Gallery</title>
    
    <link rel="stylesheet" type="text/css" href="assets/css/bootstrap.min.css" />
    <link type="text/css" href="assets/StarRate/jquery-ui.min.css" rel="stylesheet" />
    <link rel="stylesheet" type="text/css" href="assets/css/styles.css" />
    <link rel="stylesheet" type="text/css" href="assets/css/thumbs_new.css" />
    <link href='assets/StarRate/jquery.rating.css' type="text/css" rel="stylesheet"/>

    <script type="text/javascript" src="assets/js/jquery-3.5.1.min.js"></script>
    <script type="text/javascript" src="assets/js/bootstrap.bundle.min.js"></script>
    <script type="text/javascript" src="assets/StarRate/jquery-ui.min.js"></script>
    <script type="text/javascript" src="assets/js/pre_load_img.js"></script>
    <script type="text/javascript" src="assets/js/rdm_bg_imgV2.js"></script>
    <script type="text/javascript" src="assets/StarRate/jquery.MetaData.js"></script>
    <script type="text/javascript" src="assets/StarRate/jquery.rating.js"></script>

</head>
<body>
<div id="wrapper">

!--   Page Header   -->
<a name="pagetop" ></a>
<div id="banner" align="center"><img src="images/banner.png" width="75%" /></div>

<!--   Menu -->  
<div align="center"><script type="text/javascript" src="assets/js/navmenu.js"></script></div>

<div id="content">
<div class="thumbContainer">
    <button class="btn-thumb" id='pic10' href="#M1"></button>
    <div class="starContainer">
        <input class="hover-star" type="radio" name="m1" value="1" title="Very poor"/>
        <input class="hover-star" type="radio" name="m1" value="2" title="Poor"/>
        <input class="hover-star" type="radio" name="m1" value="3" title="OK"/>
        <input class="hover-star" type="radio" name="m1" value="4" title="Good"/>
        <input class="hover-star" type="radio" name="m1" value="5" title="Very Good"/>
    </div>
</div>
<div class="thumbContainer">
    <button class="btn-thumb" id='pic20' href="#M2"></button>
    <div class="starContainer">
        <input class="hover-star" type="radio" name="m2" value="1" title="Very poor"/>
        <input class="hover-star" type="radio" name="m2" value="2" title="Poor"/>
        <input class="hover-star" type="radio" name="m2" value="3" title="OK"/>
        <input class="hover-star" type="radio" name="m2" value="4" title="Good"/>
        <input class="hover-star" type="radio" name="m2" value="5" title="Very Good"/>
    </div>
</div>

<div id="M1"class="modal"><div class="modal-content">
<div class="modal-header"><span class="close">×</span><h2>video 1</h2></div>
<div class="modal-body">
    <div class="popupDivPic"><img src="images/posters/video1.jpg" /></div>
    <div class="popupDivTxt">
        <div class="genreBox">Educational</div>
        <div class="DivTxtContainer">
            <div class="DivTxtColumn1">Rating :<span class="ratingNUM">7.5</span></div>
            <div class="DivTxtColumn2">Runtime :<span class="runtimeNUM">53min</span></div>
        </div>
        <a href="file:///O|videos/video1.mkv" title="Start video"><img src="images/playBTN2.gif" /></a><br/>
        <p>description</p><br/>
    </div>
</div>
<div class="modal-footer"></div>
</div></div>

<div id="M2"class="modal"><div class="modal-content">
<div class="modal-header"><span class="close">×</span><h2>video 2</h2></div>
<div class="modal-body">
    <div class="popupDivPic"><img src="images/posters/video2.jpg" /></div>
    <div class="popupDivTxt">
        <div class="genreBox">Educational</div>
        <div class="DivTxtContainer">
            <div class="DivTxtColumn1">Rating :<span class="ratingNUM">5.5</span></div>
            <div class="DivTxtColumn2">Runtime :<span class="runtimeNUM">45min</span></div>
        </div>
        <a href="file:///O|videos/video2.mkv" title="Start video"><img src="images/playBTN2.gif" /></a><br/>
        <p>description</p><br/>
    </div>
</div>
<div class="modal-footer"></div>
</div></div>


</div><!--   content closed  -->
</div><!--   wrapper closed  -->
<script type="text/javascript" src="assets/js/open_modal.js"></script>
<div class="footer"><h1><a href="#pagetop" >Back to top</a></h1></div> 
<script type="text/javascript"> ChangeIt(); </script> 

</body>
</html>

I’m able to retrieve the selected value of each selected star radio button using this code:

<!--   Submit button   -->
    <button type="button" onclick="displayRadioValue()">
        Submit
    </button>
    <br>
    <div id="result"></div>
<script>
    function displayRadioValue() {
        document.getElementById("result").innerHTML = "";
        var ele = document.getElementsByTagName('input');
        for (i = 0; i < ele.length; i++) {
            if (ele[i].type = "radio") {
                if (ele[i].checked)
                    document.getElementById("result").innerHTML
                    += ele[i].name + " Value: "
                    + ele[i].value + "<br>";
            }
        }
    }
</script>

I can set the value on page load of a star radio button using this code:

<script>
$(function() {
        var $radios = $('input:radio[name=m2]');
        if($radios.is(':checked') === false) {
            $radios.filter('[value=2]').prop('checked', true);
        }
    });
window.onload = function() {
    if(!window.location.hash) {
        window.location = window.location + '#loaded';
        window.location.reload();
    }
}
</script>

ExpressError is not a constructor

ExpressError is not a constructor TypeError: ExpressError is not a constructor at validateCampground (D:YelpCampapp.js:38:15) at Layer.handle [as handle_request]

While running app.js file it keeps showing this

A webpage should run in localhost where i can add places without getting error but now while adding it only shows the following error

Javascript code to count selections in both matrix and singular questions (Qualtrics)

I have made the following code Javascript code to count the number of times 0, 5, or 10 are selected in questions throughout my survey on Qualtrics. I place this code in each question:


Qualtrics.SurveyEngine.addOnload(function() {
    var isCorrect10 = 10;
    var currentCounter10 = Qualtrics.SurveyEngine.getEmbeddedData("Counter10");
    
    if (!currentCounter10) {
        currentCounter10 = 0;
    }
    
    var isCorrect0 = 0;
    var currentCounter0 = Qualtrics.SurveyEngine.getEmbeddedData("Counter0");
    
    if (!currentCounter0) {
        currentCounter0 = 0;
    }
    
    var isCorrect5 = 5;
    var currentCounter5 = Qualtrics.SurveyEngine.getEmbeddedData("Counter5");
    
    if (!currentCounter5) {
        currentCounter5 = 5;
    }
    

    // If it's selected, increment 
    if (isCorrect10) {
        currentCounter10++;
        Qualtrics.SurveyEngine.setEmbeddedData("Counter10",currentCounter10.toString());
    }
    
    if (isCorrect0) {
        currentCounter0++;
        Qualtrics.SurveyEngine.setEmbeddedData("Counter0",currentCounter0.toString());
    }
    
    if (isCorrect5) {
        currentCounter5++;
        Qualtrics.SurveyEngine.setEmbeddedData("Counter5",currentCounter5.toString());
    }
    

});



For this I initialize embedded data for Counter0, Counter5 and Counter10, all at 0.

This works perfectly for questions where it is just one singluar slider. However, I want this to work for matrix questions were there are multiple questions. I want to count every appearance of count in each slider of a matrix, and also be compatible with the non-matrix questions. So each count (0,5,10) should be the total of all selections across all questions. How can I modify the javascript accordingly?

Puppeteer PDF generation race condition with front-end event dispatch

I’m working on a web application that generates PDFs using Puppeteer on the back-end, based on content rendered by a front-end Lightning Web Component (LWC). I’m encountering a timing issue where Puppeteer might be trying to generate the PDF before the front-end has finished rendering.

Back-end code (Node.js with Puppeteer):

async function generatePdf(url, footerInfo) {

    const browser = await puppeteer.launch({headless: true, args: ['--no-sandbox']});
    const webPage = await browser.newPage();
    webPage.on('console', msg => {
        console.log(msg.text());
        for (let i = 0; i < msg.stackTrace().length; ++i) {
            console.log(
                `  Line: ${msg.stackTrace()[i].lineNumber} Column: ${msg.stackTrace()[i].columnNumber} File: ${msg.stackTrace()[i].url}`);
        }
    });
    webPage.on('pageerror', ({message}) => console.log(message));

    await webPage.goto(url, {waitUntil: 'networkidle0'});

    //await webPage.waitForTimeout(10000);
    
    // custom event
    await webPage.evaluate(() => {
        return new Promise((resolve) => {
            console.log('dispatching pdfrendered event');
            window.addEventListener('pdfrendered', resolve, { once: true });
            // a timeout is addedd in case the event is never fired
            setTimeout(resolve, 30000);
        });
    });

    const footerHtml = footerHelper.generateFooterHtml(footerInfo);
    const pdfFileStream = await webPage.createPDFStream({
        printBackground: true,
        format: 'A3',
        margin: {
            top: '48px',
            bottom: '84px',
            left: '48px',
            right: '48px',
        },
        displayHeaderFooter: true,
        headerTemplate: '<div/>',
        footerTemplate: footerHtml
    });

    return {
        browser: browser,
        pdfFileStream: pdfFileStream,
    };
}

Front-end code (LWC):

import { api, LightningElement } from 'lwc';

export default class PeRelatedListItem extends LightningElement {
  @api relatedList;
  @api headerBackgroundColor;
  @api textColor;
  @api showBorder;
  pdfRendered = false;

  get headerStyle() {
    const backgroundColor = this.headerBackgroundColor || this.relatedList.subsectionBackgroundColor;
    const textColor = this.textColor || this.relatedList.subsectionTextColor;
    return backgroundColor || textColor ?
        `background-color: ${backgroundColor} !important;` : '';
  }

  get cellStyle() {
    return this.textColor ? `color: ${this.textColor} !important;` : '';
  }

  get hasRelatedRecords() {
    return this.relatedList.relatedRecords && this.relatedList.relatedRecords.length > 0;
  }

  get tableClass() {
    return this.showBorder
        ? 'slds-table slds-table_cell-buffer slds-table_bordered slds-table_col-bordered'
        : 'slds-table slds-table_cell-buffer slds-table_bordered';
  }

  renderedCallback() {
    if (this.headerStyle) {
      const headerCells = this.template.querySelectorAll('th');
      headerCells.forEach(cell => {
        cell.style.cssText = this.headerStyle;
      });
    }
    if (this.cellStyle) {
      const dataCells = this.template.querySelectorAll('td');
      dataCells.forEach(cell => {
        cell.style.cssText = this.cellStyle;
      });
    }

    if (this.isPdfRelatedList && !this.pdfRendered) {
      console.log('PDF related list detected');
      if (window['pdfjs-dist/build/pdf']) {
        this.renderPdf();
      } else {
        this.addEventListener('pdfjsloaded', this.renderPdf);
      }
      this.pdfRendered = true;
    }
    else {
      console.log('PDF related list NOT detected');
      this.dispatchEvent(new CustomEvent('pdfrendered', { bubbles: true, composed: true }));
    }
  }

  get isPdfRelatedList() {
    return this.relatedList?.type === 'pdfRelatedList' &&
        this.relatedList?.relatedRecords?.some(record => record.pdfDataUrl);
  }

  async renderPdf() {

    const pdfContainer = this.template.querySelector('.pdf-container');
    //pdfContainer.innerHTML = '';

    for (const record of this.relatedList.relatedRecords) {
      const pdfData = record.pdfDataUrl;
      if (!pdfData) {
        console.error('PDF data not loaded for record:', record.id);
        continue;
      }

      const pdfjsLib = window['pdfjs-dist/build/pdf'];
      let pdfDoc;
      try {
        if (pdfData instanceof Blob) {
          pdfDoc = await pdfjsLib.getDocument({data: await pdfData.arrayBuffer()}).promise;
        } else if (pdfData instanceof ArrayBuffer || pdfData instanceof Uint8Array) {
          pdfDoc = await pdfjsLib.getDocument({data: pdfData}).promise;
        } else {
          console.error('Unsupported PDF data type');
          continue;
        }

        const numPages = pdfDoc.numPages;

        for (let pageNum = 1; pageNum <= numPages; pageNum++) {
          const page = await pdfDoc.getPage(pageNum);
          const scale = 1;
          const viewport = page.getViewport({scale: scale});

          const canvas = document.createElement('canvas');
          const context = canvas.getContext('2d');
          canvas.height = viewport.height;
          canvas.width = viewport.width;

          const renderContext = {
            canvasContext: context,
            viewport: viewport
          };

          await page.render(renderContext).promise;
          pdfContainer.appendChild(canvas);

          // Add some space between pages
          if (pageNum < numPages) {
            const spacer = document.createElement('div');
            spacer.style.height = '20px';
            pdfContainer.appendChild(spacer);
          }
        }

        // Add a larger spacer between different PDFs
        const pdfSpacer = document.createElement('div');
        pdfSpacer.style.height = '40px';
        pdfContainer.appendChild(pdfSpacer);

      } catch (error) {
        console.error('Error rendering PDF:', error);
        const errorMessage = document.createElement('p');
        errorMessage.textContent = `Error rendering PDF: ${error.message}`;
        pdfContainer.appendChild(errorMessage);
      }
    }

    // Emit custom event indicating all PDFs have been rendered
    this.dispatchEvent(new CustomEvent('pdfrendered', { bubbles: true, composed: true }));
  }
}

The issue:
When this.isPdfRelatedList is false, the front-end immediately dispatches the ‘pdfrendered’ event. However, this event might be dispatched before Puppeteer has a chance to set up the event listener in webPage.evaluate().
Questions:

How can I ensure that Puppeteer doesn’t miss the ‘pdfrendered’ event when it’s dispatched immediately?
Is there a better way to synchronize the front-end rendering completion with the back-end PDF generation process?
Should I use a different approach altogether for non-PDF content?

Any insights or best practices for handling this kind of front-end/back-end synchronization with Puppeteer would be greatly appreciated.

I initially expected the ‘pdfrendered’ event to be captured by Puppeteer regardless of when it was dispatched. However, I found that when this.isPdfRelatedList is false, the event seems to be missed entirely.
I tried increasing the timeout in the Puppeteer evaluate function from 30 seconds to 60 seconds, thinking it might give more time for the event to be dispatched and captured. This didn’t solve the issue and only resulted in longer wait times for non-PDF content.

Session stored in database, but not in browser

I am a bit rusty with sessions and authentication so bear with me. I am attempting to make a simple login function for my site, users can sign up successfully and their information gets stored within MongoDB. When trying to have a user login, and create a session ID, i can see the session get stored in my ‘sessions’ collection, but not within the ‘cookies’ on the browser, I also cannot access the “logged in” users data once they get past the login page.

Using mongoose, express-session, and connect-mongo

Users.js

router.post('/login', async (req, res, next) => {
    const { username, password } = req.body
    const user = User.findOne({ username: username })
        .then(async (response) => {
            if (!user) {
                return res.send('User not found')
            }
            bcrypt.compare(password, response.password, function (err, result) {
                if (result !== true) {
                    return res.status(500).json(err)
                }
                req.session.user = {
                    username,
                    password,
                    isLoggedIn: true
                }
                req.session.save()
                res.status(200).send()
            })
        })
        .catch((err) => {
            console.error(err)
            res.status(400).json({ error: 'Internal Error' })
            return
        })
})

server.js

mongoose.connect("mongodb://localhost/BookNest")

app.use(session({
    secret: 'my-secret',
    resave: false,
    saveUninitialized: true,
    store: MongoStore.create({
        mongoUrl: "mongodb://localhost/BookNest"
    })
}));

Ive attempted to console log req.session and req.sessionID both of which return my ‘session id’, but still cannot do account actions once logged in.

req.cookies NEXTJS Middleware undefined on Production

this my next middleware :

export async function middleware(request: NextRequest) {
const token = request.headers.get('token')
console.log(token)
if (!token || token == undefined) {
return NextResponse.redirect(new URL('/login', request.url))
}
}

export const config = {
matcher: ['/admin/:path*']
}

this response from backend express :

  `res.cookie('token', response.token, { 
    maxAge: maxAges,
    httpOnly: false,
    secure: process.env.NODE_ENV === 'production',
    sameSite: 'none'
  })`

in local this methode is work. but if i try to deploy using https for frontend and backend this methode not working.

Got undefined param value in a generated element in antd Tabs -> TabPane

I would like to create a customized TabPane for an Antd tab,
The Tabs definition:

      <Tabs>
        {myTab.map((tab) => (
          <TabPane tab={tab.label} key={tab.label}>
            {tab.children}
          </TabPane>
        ))}
      </Tabs>

The myTab definition:

  const myTab = Object.keys(target.data).map((targetKey) => {
    let hierarchy = [];
    hierarchy = target.hierarchy.filter((i) => i.key === targetKey)[0].children;
    let modeInfo =  {};
    modeInfo = target.data[targetKey];
    return {
      label: targetKey,
      key: targetKey,
      children: (
        <>
          <InfoPage modeInfo={modeInfo} hierarchy={hierarchy} selectedTarget={targetKey}/>
        </>
      ),
    };
  });

The data structure of target looks something like this:

{
   data: {
      XXXXX : {....}
   }
   hierarchy : [ 
      {
         children: [...]
         key: 'XXXXX'
      }
   ]
}

I can get the data of ‘modeInfo’ & ‘hierarchy’ at the root level when initialize the InfoPage element, how ever I keep getting ‘undefined’ for all the input params within InfoPage.

useState isn’t reflecting a change in an onClick callback function

I am new to React, and I am having the following issue:

When I get a value from redux, I am creating a clone of it and saving it to useState so I can modify it without affecting the original value until I press save, which then sends the value to redux to be updated in my store. The problem I am having, is in the function saveProject the value doesn’t change name within the object, as it is still the original value. However, in the effect, the correct value is displayed. I am not sure why, what would be causing this?

// Edit dialog
export default () => {
  // Original value from redux
  const active = useSelector(selectActiveProject);
  // The value I want to track
  const [project, setProject] = useState<Project>(Object.assign({}, active));
  // The value should be the updated value here (but shows the original)
  const saveProject = () => console.log(project);
  // Sets the value when the input is typed into
  const nameChange = (e: BaseSyntheticEvent) => setProject({ ...project, name: e.target.value });

  // Prints the correct value from the input
  useEffect(() => console.log('useEffect', project), [project]);

  return (
    <>
      <input defaultValue={project.name} onChange={e => nameChange(e)} />
      <button onClick={saveProject}>Save</button>
    </>
  );
}

How to add a Flickr API to my current HTML Site – Warning: Beginner

I was currently working on a project for my html, css and javascript web developing class but I have a hit a road block on the very last unit. they provided a bunch of resources to teach you api but most tutorials do not even work… so i selected one of the provided api resources they recommended for use, which was flickr. I selected a testimonial api from flickr but im not sure on how to integrate it as there is little to no direction when yiutubing it or googling it and im currently at my wits end myself as im very burnt out!

I was wondering if anyone can provide a solution or some resources to help me out?

here is the flickr website and code: https://www.flickr.com/services/api/flickr.testimonials.addTestimonial.html


`<rsp stat="ok">
  <testimonial id="72157659275062162" date_create="1491516194" date_approved="0" approved="0" body="great contractor!">
    <by_user nsid="45937598@N01" path_alias="" username="TQ" ispro="1" is_ad_free="0" realname="Tariq Q" 
/>
    <about_user nsid="516314214@N05" path_alias="sidasad" username="Sad" ispro="0" is_ad_free="0" realname="Asad Siddique" />
  </testimonial>
</rsp> `

Also here is my current index page where i want to integrate the code.. i was following a tutorial which i very late realized had nothing to do with API inetgration so ive added the code from flickr into a div container as of current.

`<!DOCTYPE html>
<html>
<head>
    <title> MH Construction Concrete Cutting & Coring Ltd.</title>
    <link rel="stylesheet" href="stylesheet.css">
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.13.3/themes/smoothness/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-3.7.1.js"></script>
  <script src="https://code.jquery.com/ui/1.13.3/jquery-ui.js"></script>
    <script src="script.js"></script>
   
        <h1>MH Construction Concrete Cutting & Coring Ltd.</h1>
        <h3><center>Are you looking to enhance your property with precision concrete cutting and coring services? Look no further than MH Construction Concrete Cutting & Coring Ltd!</h3></center>
        <meta charset="utf-8">
</head>
<body>

<div id="tabs">
  <ul>
    <li><a href="#fragment-1"><span>About Us</span></a></li>
    <li><a href="#fragment-2"><span>Our Projects</span></a></li>
    <li><a href="#fragment-3"><span>Our Services</span></a></li>
    <li><a href="#fragment-4"><span>Bookings</span></a></li>
  </ul>
  <div id="fragment-1">
  <h2>About Us</h2>
    <p>MH Construction Concrete Cutting & Coring Ltd. is committed to providing top-quality services with a focus on safety and customer satisfaction. Our team of experts is equipped with the latest tools and technology to ensure precise and efficient results.</p>
        <p><a href="socials.htm">Click Here To Our View Socials Page</a></p>

<div id="testimonialsContainer">
  <h2>Testimonials</h2>
  <ul id="testimonialsList"></ul>
</div>
<rsp stat="ok">
  <testimonial id="72157659275062162" date_create="1491516194" date_approved="0" approved="0" body="great contractor!">
    <by_user nsid="45937598@N01" path_alias="" username="TQ" ispro="1" is_ad_free="0" realname="Tariq Q" />
    <about_user nsid="516314214@N05" path_alias="sidasad" username="Sad" ispro="0" is_ad_free="0" realname="Asad Siddique" />
  </testimonial>
</rsp>
  </div>
  <div id="fragment-2">
     <h2>Our Projects</h2>
       <p>Explore our previous projects to see the quality of our work and get inspired for your next renovation or construction project.</p>
       <p><a href="projects.htm">Click Here To View Our Projects Page</a></p>
  </div>
  <div id="fragment-3">
   <h2>Services</h2>
<p><a href="Our Services.htm">Click Here To Visit Our Services Page</a></p>
     <p>In any of our requested services we abide by Alberta Government Health and Safety Regulations. Please see the attached Alberta Government Safety Website for more.</p>
       <p><a href="https://www.alberta.ca/obligations-work-site-parties">Government of Alberta Safety Website Disclosure</a></p>
  </div>
    <div id="fragment-4">
   <h2>Services</h2>
<p>Ready to book an appointment? Please see our email booking form below and suggest some times and dates you are available and we will get back to you shortly within 4-5 business days. Feel free to use our viewable calendar below to aid in choosing your next appointment date! </p>
       <p><a href="book now.htm">Click Here To Book Now</a></p>
</div>
 
<script>
$( "#tabs" ).tabs();
</script>

</body>
</html>

    <p>Author: Keisha Shah</p>
    <p>Last modified: <span class="date">August 16th, 2024</span></p>`

ive tried the following: So I made a div id section with testimonials following him, and integrated the code to see if it would work. On the index page of my site, only problem was using the code it was not showing up so I used the above source and a variety of other sources to see if I could make it work – I tried using chrome inspect only error detected was : Uncaught Type Error: Cannot set properties of null (setting ‘inner HTML’)

at generate Calendar (script.js:44:24) 

at script.js:50:1  

Hidden Date Input Trigger Calendar OnClick

Simple problem but I am not sure if I think it right. I have a project on NextJS and want to make a date input but also have a custom placeholder and the input still be usable.
I have come to a stop, my current setup is that I have my Date Input hidden, and a paragraph displaying the placeholder I want…how do I make an OnClick event or a Ref to make the input usable by the user? Is there a way? Or else what can I do to also have a placeholder and a date input?

TypeScipt:

       <input
            type="date"
            name={label}
            id={label}
            value={date}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => setDate(e.currentTarget.value)}
            tabIndex={tabIndex}
            hidden
        />
        <p className={style.calendarFakeInput}>{placeholder}</p>

SCSS:

    .calendarFakeInput {
     color: $grey2;
     width: 100%;
     cursor: default;
    }
    input[type="date"] {
     position: relative;
     color: $grey2;
    }
    input[type="date"]::-webkit-calendar-picker-indicator {
     background: transparent;
     bottom: 0;
     color: transparent;
     cursor: pointer;
     height: auto;
     left: 0;
     position: absolute;
     right: 0;
     top: 0;
     width: auto;
    }

On the parent component of these I tried this with no luck…

<div className={style.calendarInput} onClick={() => document.getElementById(`${label}`)?.click()}>

TS path alias not resolving

In main/tsconfig.json I have the following path alias

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["./app/*", "./app/src/*"],
      "constants/*": ["./app/src/constants/*"],
    }
  }
}

where main/app/src/constants.js is as follows:

export const test = "abc";

I then try to reference this in main/app/routes/index.tsx as follows:

import {test} from '@constants';

but TS throws the error Cannot find module '@constants' or its corresponding type declarations.

Why is it failing to resolve the type alias and how can I fix this?

Pushing new employee profile pictures via the BambooHR API?

I’m trying to use the BambooHR API to update employee profile pictures through a TypeScript app. This is supposedly possible according to their documentation, however, I keep getting error 400 (Bad request) when even trying the example in their docs.

First, I made sure that my API key has the correct permissions. As an example of the code:

import bamboohr from '@api/bamboohr';

bamboohr.auth('apikey', 'x');
bamboohr.uploadEmployeePhoto({companyDomain: 'Knak', employeeId: 'placeholder'})
  .then(({ data }) => console.log(data))
  .catch(err => console.error(err));

This returns a bad request error. There is apparently no parameter in the function for the actual image data, although the implementation of the function in their API github here says that there apparently is? I’m not really sure how to go about this so any help would be much appreciated.

At what point does JavaScript out perform HTML code? Ever? [closed]

Does there ever come a point when JS is more efficient and less of an overhead than pure HTML/CSS code?

My understanding is HTML and pure CSS are superior to using JavaScript when it comes to performance, but is that always the case: the example I saw was for a glitch animation effect of sorts that changed random letters in a string to create a transition to a new string.

Here is a simple example (keep in mind you would only see one line at a time, so it appears the characters are randomly being replaced):

hello there
h%llo t5ere
ho&l@ there
howla=t1e e
how#ar7 %oe
how are yo*
how are you

when I inspected the code, the developer basically just had:

 <h2>
    <span> hello there </span>
    <span> h%llo t5ere </span>
    <span> ho&l@ there </span>
    <span> howla=t1e e </span>
    <span> how#ar7 %oe </span>
    <span> how are yo* </span>
    <span> how are you </span>
 </h2>

with distinct class names for each “stage1” “stage2” and so on. So my understanding is they just use CSS to hide/show each stage during various keyframes of a CSS animation.

But if I was asked to code this, I would actually make it random (different each time the function is called) using the math rand() function and a for/while loop (with alteration logic inside) to modify the text inside a single h2 tag, instead of creating a bunch of span tags, or even if I did it that way, I’d still use a for loop to generate the various (so-called) “random” span tags/text.

My assumption is they did this to eliminate the JavaScript overhead. But how much overhead is there really? I was thinking larger scale than this example… is it better performance to use JS or to write a bunch of extra html code as this dev did, which then has to be sent over the network (more data) and then each span element has to be added to and controlled by the DOM. assuming the JS code is say 5-10 lines of code, and the HTML method is say 100 span elements (99% of which are always hidden) which method would be better for production deployment performance? this is what prompted the original question at the beginning.