Convert JQuery Slide Functions To CSS Transitions

I wish to convert my FAQ section that utilizes Jquery to smoothly slide each question up and down into pure Javascript and CSS transitions.

The reason is for optimization and making a page as lightweight as possible. My goal is to remove jquery from my website altogether because it’s unnecessary.

I have uploaded my FAQ section into an HTML page and hosted it on a URL. This way, you can try it for yourself and see it in action. Please check here.

You can click on each title, and it will slide up and down. To have an exact replica of what I currently have is proving to be difficult. I have tried CSS transitions but it seems to require changing the height. Right now, I use display: block or display: none because the height is unknown. translateY(100%) to calculate the height at runtime didn’t seem to work either.

I will insert my current Jquery code here:

<style>

    #sectionFAQWrapper {

        padding-bottom: 30px;

    }
    #sectionFAQWrapper ul {

        padding: 5px 0px 12px 0px;
        margin: 0px;

    }
    #sectionFAQWrapper ul li {

        list-style-type: none;
        font-size: 20px;

    }
    #sectionFAQTopBanner {

        text-align: center;
        padding: 40px 0px;
        background: linear-gradient(90deg, rgb(74 79 177) 0%, rgb(31 32 82) 100%);
        color: #fff;
        margin-bottom: 30px;

    }
    #sectionFAQTopBanner h2 {

        font-weight: 600;
        letter-spacing: -1px;
        font-size: 46px;
        margin: 0;
        font-family: 'Oswald';

    }
    .questionItemWrapper {

        max-width: 1000px;
        margin: 0 auto;

    }
    #sectionFAQWrapper h3 {

        font-size: 30px;

    }
    #sectionFAQWrapper p {

        font-size: 20px;
        padding-bottom: 10px;
        font-weight: 400;
        margin: 0;

    }
    .questionItemBoldBlue {

        color: #4549a5;
        font-weight: 600;

    }
    .questionItemBoldTopBorderBlue {

        border-top: none;

    }
    .questionItemHeader {

        position: relative;
        background-color: rgba(0,0,0,.03);
        padding: 15px;
        margin: 0px 10px;

    }
    .questionItemHeader div {

        display: inline-block;
        font-family: 'Oswald';

    }
    .questionItemToggle {

        position: absolute;
        top: 17px;
        left: 14px;
        content: url(https://cdn.shopify.com/s/files/1/0022/5103/0563/files/doubleDownArrowBlack.png?v=1621284261);
        height: 34px;
        width: 34px;

    }
    .questionItemRotate180 {

        transform: rotate(180deg);
        content: url(https://cdn.shopify.com/s/files/1/0022/5103/0563/files/doubleDownArrowBlue.png?v=1621284261);

    }
    .questionItemQuestion {

        font-size: 28px;
        padding-left: 40px;

    }
    .questionItemContent {

        padding: 20px 20px 10px 20px;
        margin: 0;
        display: none;
        font-family: 'Open Sans';

    }

</style>


<div id="sectionFAQWrapper">

    <div id="sectionFAQInner">

        <div id="sectionFAQTopBanner">

            <h2>FREQUENTLY ASKED QUESTIONS</h2>

        </div>

        <div class="questionItemWrapper questionItemBoldTopBorderBlue">
            
            <div class="questionItemHeader">
                <div class="questionItemToggle questionItemBoldBlue questionItemRotate180"></div>
                <div class="questionItemQuestion questionItemBoldBlue">Title #1</div>
            </div>

            <div class="questionItemContent" style="display: block;">

                <p><b>Content Paragraph #1</p>

                <p><b>Content Paragraph #2</p>

            </div>

        </div>

        <div class="questionItemWrapper questionItemBoldTopBorderBlue">
            
            <div class="questionItemHeader">
                <div class="questionItemToggle"></div>
                <div class="questionItemQuestion">Title #2</div>
            </div>

            <div class="questionItemContent" style="display: none;">

                <p><b>Content Paragraph #1</p>

                <p><b>Content Paragraph #2</p>

            </div>

        </div>

</div>


<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<script>
    
    // When DOM has loaded
    $(document).ready(function() {

        // FAQ section
        $(".questionItemWrapper").click(function() {

          $(this).find('.questionItemContent').toggle( "slow", function() {});

          $(this).find('.questionItemQuestion').toggleClass("questionItemBoldBlue");
          $(this).find('.questionItemToggle').toggleClass("questionItemBoldBlue");
          $(this).find('.questionItemToggle').toggleClass("questionItemRotate180");
          $(this).toggleClass("questionItemBoldTopBorderBlue");

        });

    // End of document.ready()
    });

</script>

How can I reveal an element behind a flatlist and have it interactable in React Native?

I am trying to render an element that is positioned absolutely behind a flatlist and it will be revealed once the user scrolls to the bottom. The issue I am facing is that the element needs to be interactable, and the flatlist root element takes all pointerevents instead of the background element.

const FlatlistOverElement: FC = () => (
  <View style={{ flex: 1, width: '100%' }}>
    <FlatList
      data={data}
      style={{ flexGrow: 1 }}
      ListFooterComponent={() => (
        <View style={{ height: BACKGROUND_ELEMENT_HEIGHT, opacity: 0 }} />
      )}
      renderItem={RenderItem}
    />
    <AbsolutelyPositionedElementBehindFlatList />
  </View>
)

I have tried to remove pointerevents from the flatlist, then the flatlist is not scrollable.

I have tried to set the height of the flatlist smaller, and let the content overflow. This allows the user to interact with the element, but for that part of the screen, the user can not scroll the flatlist.

What other approach can I utilise in order to solve this issue ?

Prerender.io is not rendering homepage schema scripts but will render them everywhere else

I have an SPA that uses prerender.io to send static pages back to the browser primarily so that my schema scripts will be visible to the bots. If I use the structured data testing tool I can plainly see that everywhere except the homepage will render the schema scripts that exist in the body of the page. The homepage happens to have a website schema script in the head of the document that DOES render and is observed by the structured data testing tool, but the News and Events schemas won’t render. Elsewhere on the News and Events landing pages the schema scripts show up just fine in the structured data testing tool.

I checked the origin-request lamba that vets what URLs get rendered by prerender and the homepage is not included in the regex:

RegExp('/(catalog?|ill/*|wiki/*|docdel/*|ovgtsl2018/*|hackathon/*|rigorandrelevance/*|specialist/*|onesearch/*|instruction/potofgold/*|cds/*|directory/*|documents/*|eresources/*|guide-on-the-side/*|medieval/*|libcat/*|utilities/*|search?)')

Here is the full JS for the origin-request:


// Source: https://bravetheheat.medium.com/prerendering-and-aws-cloudfront-7a6635e9f2dc
module.exports.handler = async (event, context, callback) => {
  const request = event.Records[0].cf.request

  // Here are some paths we never want to hit prerender, even if they have the correct headers.
  const badPaths = new RegExp('/(catalog?|ill/*|wiki/*|docdel/*|ovgtsl2018/*|hackathon/*|rigorandrelevance/*|specialist/*|onesearch/*|instruction/potofgold/*|cds/*|directory/*|documents/*|eresources/*|guide-on-the-side/*|medieval/*|libcat/*|utilities/*|search?)')

  if (request.headers['x-prerender-token'] && request.headers['x-prerender-host'] && !badPaths.test(request.uri)) {
    request.origin = {
      custom: {
        domainName: 'service.prerender.io',
        port: 443,
        protocol: 'https',
        readTimeout: 20,
        keepaliveTimeout: 5,
        customHeaders: {},
        sslProtocols: ['TLSv1', 'TLSv1.1'],
        path: '/https%3A%2F%2F' + request.headers['x-prerender-host'][0].value,
      },
    }
  } else {
    // Not using prerender. Redirect to index.html since this is an SPA
    // ...Unless it's one of these file extensions, in which case the request should continue unaltered
    const validExtensions = [
      '.html',
      '.js',
      '.json',
      '.css',
      '.jpg',
      '.jpeg',
      '.png',
      '.ico',
      '.map',
      '.txt',
      '.kml',
      '.svg',
      '.webmanifest',
      '.webp',
      '.xml',
      '.zip',
      '.woff',
      '.woff2',
      '.ttf',
      '.otf',
    ]
    const parsedPath = path.parse(request.uri)
    if (parsedPath.ext === '' || !validExtensions.includes(parsedPath.ext)) {
      request.uri = '/index.html'
    }
  }
  callback(null, request)
}

Could anything here prevent the homepage from getting sent to prerender? Any suggestions on where to look or what to do to get the index.html file to be sent to prerender and back to the browser as a statically rendered file?

I have a feeling this has something to do with the fact this is an SPA and index.html is the only ACTUAL file in the file system. I know there is some magic that happens when the request for any other file (i.e. https://www.blahblah.com/catalog/shirt), which doesn’t exist, is requested and a 404 will result, which is then routed and handled and sent back as the URL path. Could the fact that index.html does not create this 404 be related to why the it’s not being sent to prerender?

How to sort the date form to latest to the oldest in array of objects react js

im trying to sort the date from this array of objects from the latest to the oldest. Im trying this code, copying the array to a new const then using it with sort, but I have the same result, no sorted date. My code is below:

const array=[...user?.editedBy]
console.log(array,"array")

const sortedDates = array?.sort((dateA, dateB) => dateB.date -dateA.date )
console.log(sortedDates,'sortedArray')

The first pic its the console log from array and the second from sortedDates,
So the same result, can someone please help me figure it out what Im missing???
*Thank you in advance *

enter image description here
enter image description here

How to prevent user from adding duplicate values in a array in Javascript

I have been looking all over for a correct answer on this but can’t seem to get one that works. I am trying to take input for an array that allows a max of 6 entries and does not allow duplicates. My code that I was playing around with only alerts me when I already have duplicates in the array. What would be the correct way to prevent a duplicate value from ever being added then displaying an error stating so?

I need to carry it over to list on the HTML doc but for right now I’m working on not allowing it to add duplicates so I’ve been using the Console tool

Any help would be much appreciated

Javascript:

"use strict"

//DO NOT MODIFY THE CODE BELOW
//wait for everything to load before executing this here code
$(document).ready(()=> {
    // create a new constant to hold a date reference for the current moment
    const dt = new Date();
    //Get the current year from the date reference, and put it
    //in the yield field in the footer.
    $('#year').text(dt.getFullYear());
});
//ADD YOUR CODE BELOW
let franzList = [];

function addTo() {
    franzList.push(document.getElementById("listItemInput").value);
    console.log(franzList);
}

function clearList() {
    franzList.length = 0; 
}


function hasDuplicates(array) {
    let valuesSoFar = Object.create(null);
    for (let i = 0; i < array.length; ++i) {
        let value = array[i];
        if (value in valuesSoFar) {
            return true;
        }
        valuesSoFar[value] = true;
    }
    return false;
}

$(document).ready(()=> {
    $("#addItemToList").click( () => {
        let error = false;
    
        const listItemInput         = $("#listItemInput").val().trim();

        $("#listItemInput").val(listItemInput);

        if(listItemInput == "") {
            console.error("input field blank");
            alert("Error! Franz Liszt's list item cannot be empty. This is unacceptable. 
Franz Lizst demands you correct his list!");
            error = true;
        } else if (franzList.length > 5) {
            console.error("6 items in the list only!");
            alert("Error! Franz Listz's list can only hold 6 items!");
            error = true;
        } else if (hasDuplicates(franzList) === true) {
            alert("Error! No duplicates allowed!")
            error = true;
        }
        $("#listItemInput").val(listItemInput);

        /*
        if(checkDuplicate(franzList) == true) {
            console.log("No Duplicates");
        } else {
            console.log("DUPLICATE NOT ALLOWED!");
            alert("NO DUPLICATES ALLOWED");
            error = true;
        }
        */

        if(!error) {
            addTo();
            $("#listItemInput").val("")
         //if error message is displayed form will not submit    
        } else {
            alert("Nothing added due to error");
        }

    })

    $("#clearList").click( () => {
        clearList();
    })

});

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <title></title>
  <meta charset="utf-8">
  <link rel="stylesheet" type="text/css" href="style.css"/>
  <link rel="preconnect" href="https://fonts.googleapis.com">
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Montserrat&family=Yellowtail&display=swap" rel="stylesheet">
  <script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
  <script src="script.js"></script>
</head>
<body>
  <main>
    <h1>Franz Liszt's List</h1>
    <h2>Listing Things Since 1811!</h2>
    <p>Franz Liszt was more than a Hungarian composer, virtuoso pianist, conductor, music teacher, arranger, and organist of the Romantic era.</p>
    <p>He was more than a writer, philanthropist, and Fraciscan tertiary.</p>
    <p>No, Franz Liszt loved lists. </p>
    <p>Let us pay homage to Franz Lizst's list love by adding some items to our list below.</p>
      <div class="container">
        <div class="left">
        <!-- <label for="listItemInput">Input an item below:</label><br/>-->
          <h3>Input an item below:</h3>
          <input id="listItemInput" type="text" placeholder="Input item here"></input><br/>
          <button id="addItemToList">Add Item to Franz Liszt's List</button> <br/>
          <button id="clearList">Clear Franz Liszt's List</button> 
      <br/>
        </div>
      <div class="right">
        <h3>Franz Liszt's List Items:</h3>
        <ul id="listItemsHolder"></ul>
      </div>
  </div>
  <footer>
    &copy;<span id="year"></span> - Franz Kafka. All rights reserved?
  </footer>
  </main>
</body>
</html>

Automatic scroll bar

Good afternoon,

I’m creating a chat initially in PHP in which in the div called “Message” I load the conversation that was generated.

Through JavaScript/Ajax, I access the PHP file and bring up the conversation that was recorded, putting the data from this file in the Message div. For obvious reasons, after a message number X, a scroll is generated in this div. Using CSS, I set up an “overflor:auto” that generates the vertical scroll.

Initially, I couldn’t get the scroll bar to go down, showing the last message sent. Using the code below, I managed to do this…

$(document).ready(function()
{
    setInterval(function(){
        readMessage();
        var textArea = document.getElementById('Message');
        textArea.scrollTop = textArea.scrollHeight;
    },1000);
});

However, if I want to read a previous message, above and outside the field of view, when manually moving up the scroll (by clicking on the scrollbar and up OR on the mouse, scrolling up), the code above makes the scroll come down, not allowing me to read what I want from the conversation.

How can I solve this problem?

Thank you very much in advance!

How do I animate two letters swapping?

I am trying to make a website where hovering over a misspelling consisting of transposition of two letters corrects it, like so:

var swap = document.querySelector('.swap');

swap.addEventListener('mouseover', swapIn);
swap.addEventListener('mouseout', swapOut);

function swapIn(e) {
  e.target.parentNode.firstChild.classList.toggle('shifted-right');
  e.target.parentNode.lastChild.classList.toggle('shifted-left');
}

function swapOut(e) {
  e.target.parentNode.firstChild.classList.toggle('shifted-right');
  e.target.parentNode.lastChild.classList.toggle('shifted-left');
}
body {
  font-size: 24px;
}

.swap {
  display: inline;
}

span {
    -webkit-transition: all 0.3s linear;
    -moz-transition: all 0.3s linear;
    -o-transition: all 0.3s linear;
    transition: all 0.3s linear;
}

.shifted-right {
  margin-left: 20px;
  color: blue;
}

.shifted-left {
  margin-left: -25px;
  color: red;
}
E<div class="swap" id="swap"><span class="left-swap" id="ls">q</span><span class="right-swap" id="rs">c</span></div>uis me vivit fortunatior?

However, as you can see, the letters don’t swap well, and besides, I don’t want to calculate the precise margins for each different letter width.

What’s a better approach to doing this?

TS7053: Element implicitly has an ‘any’ type

Sry for my stupid question, but i can`t search answer for my promlem.
TS7053: Element implicitly has an ‘any’ type because expression of type ‘string’ can’t be used to index type ‘{ width: number; height: number; title: string; }’

let menu:{width:number; height:number; title:string} = {
width: 200,
height: 300,
title: 'My menu',
 }
function multiplyNumeric(menu:{width:number; height: number; title: string}):void {

for (let k in menu){
    if (typeof menu[k] === "number"){
        menu[k] = Number(menu[k]) * 2;
    }
}
}
multiplyNumeric(menu);

I can’t save the image to the DynamoDB table from the form

I’m having a problem storing the image in the DynamoDB table.

I have a form where there is an id in it. a name and an image; regarding the image, the table shows the name of the image (therefore of type string, example img_mountains_wide.jpg), while in the form there is a field of type file.

So referring to the latter, as I see from my json array, the image is saved with all the full path; only if I go to the dynamo table I don’t see the path. ( EXAMPLE: in the array I get {“id”:”232643″,”name”:”mountains”,”image”:”C:UsersDesktopimg_mountains_wide.jpg”} while in the table I must have only img_mountains_wide.jpg ).

What should I do to fix this?

function myFunction() {
            const data = {
                id: document.getElementById('id').value,
                name: document.getElementById('name').value,
                image: document.getElementById('image').value,
            };
   <div class="container">
        <form method="post" id="save" action="javascript:myFunction()">
            <h1>Inserire articolo</h1>
            <div class="field">
                <label for="id">ID :</label>
                <input type="text" id="id" name="id" />
            </div>
            <div class="field">
                <label for="name">Name:</label>
                <input type="text" id="date" name="name" />
            </div>
            <div class="field">
                <label for="image">Image:</label>
                <input type="file" id="image" name="image" />

            <div class="field">
                <button type="submit" class="full">Save</button>
            </div>
        </form>
    </div>

How to trigger a JavaScript function only when the user scrolls the page

I need to add positon: fixed to .box only if the user scrolls the page.

The important point here is that the element with the class .box get generated only after the user scrolls the page.

This is what I came up with:

window.addEventListener('scroll', () => {
const myDiv = document.querySelector('.box')
if (myDiv) {
    if (myDiv.style.position !== 'fixed') {
        myDiv.style.position = 'fixed'
    }
}
})

The problem with my code is that the scroll event is now going to fire a million events all the time and kill performance.

What would be the right way to achieve the above without firing scroll event again and again.

PDF download not retaining font family

  const url = window.URL.createObjectURL(
    new Blob([pdf], {type: 'application/pdf'}),
  );
  const link = document.createElement('a');
  link.href = url;
  link.setAttribute(
    'download',
    `shipping_labels.pdf`,
  );
  document.body.appendChild(link);
  link.click();
  link.parentNode?.removeChild(link);

I am trying to get a string PDF to download automatically, though in converting it to a blob it loses its existing font families; when testing the endpoint that returns the string PDF via Postman, it downloads correctly. How can I retain the font families?

PHP form submitting when clicking any buttons

currently setting up a form to create a new order within a payment system and when I click any of the buttons within the form the form submits. Anyone know what the issue could be?
This is the code with the issue:

 <form action="scripts/php/addorder.php" method="POST">
  <script src="scripts/javascript/cookies.js"></script>
  <script src="scripts/javascript/addproduct.js"></script>
  <label>Choose Customer: </label>
  <input type="text" value="" name="name" id="name" required readonly>
  <button onclick ="window.open('customertable.php','popup','width=600,height=600');">Choose</button>
  <br/>
  <div id="products">
      <label>Products: </label>
      <br/>
      ID: <input type="text" value=" " name="chosenproduct0" id="chosenproduct0" required readonly>
      Name: <input type="text" value=" " name="chosenproduct0name" id="chosenproduct0name" required readonly>
      Price: <input type="text" value=" " name="chosenproduct0price" id="chosenproduct0price" required readonly>
      Quantity: <input type="number" value="1" name="chosenproduct0quantity" id="chosenproduct0quantity" required>
      <button onclick ="findproduct('chosenproduct0');">Choose Product</button>
  </div>
  <br/>
  <label>Discount: </label>
  <input type="number" placeholder="0" name="discount" id="discount" step=".01" min="0">
  <label>Total: </label>
  <input type="number" value="0" name="total" id="total" readonly>
  <button onclick="addproduct()">Add Product</button>
  <br/>
  <input type="submit" id="submit" value="Create New Order" class="button"/>
  </form>