Hi, how can i upgrade this code for do it esyer and for using it many times?

This animation move blocks into parent blocks with overflow hidden(text is changing with same way). I want to make it with lesser coding and for using it for few same buttons. Actually this code hard to anderstand so i reccomend you to copy it watch what it does and try wright your verssion of it. Thanks for halping me out!

Html

<section class="setting__color color">
            <h3 class="color__title">Color scheme:</h3>
            <div class="color__buttons">
                <button class="color__button" id="white">White
                    <span class="color__span " id="whitespan">
                        <span class="color__text " id="whitetext">White</span>
                    </span>
                </button>
                <button class="color__button" id="black">Black
                    <span class="color__span" id="blackspan">
                        <span class="color__text" id="blacktext">Black</span>
                    </span>
                </button>
            </div>
        </section>

SCSS

.color {

    margin: 50px;

    &__title {
        font-size: 18px;
        color: #cacaca;
        font-weight: normal;
    }

    &__buttons {
        display: flex;
        margin-top: 7px;
        button {
            margin-left: 5px;

            :first-child {
                margin-left: 0;
            }
        }
    }

    &__on {
        width: 100px;
        height: 40px;
        background-color: #6844B5;
        color: #fff;
        font-size: 15px;
        border-radius: 5px;

        outline: 1px solid#6844B5;

        position: relative;
        top: 0;
        left: 0;
    }

    &__button {
        width: 100px;
        height: 40px;
        background-color: #fff;
        color: #cacaca;
        font-size: 15px;
        border-radius: 5px;
        
        outline: 1px solid#cacaca;
            &:hover {
                outline: 1px solid#6844B5;
                transition: all ease-in-out 0.3s;
            }
        position: relative;
        top: 0;
        left: 0;
        transition: all ease-in-out 0.3s;
        overflow: hidden;
    }

    &__span {
        position: absolute;
        top: 0;
        left: 0;
        z-index: 2;
        color: #cacaca;

        width: 100%;
        height: 100%;

        background-color: #6844B5;

        transition: all ease-in 1s;
        outline: 1px solid#6844B5;
        overflow: hidden;
        display: block;
        transform: translate3d(110%, 0px, 0px);
    }

    &__text {
        display: block;
        padding: 11px 0;
        transition: all ease-in 1s;
        transform: translate3d(-110%,0px , 0px);
    }
}

#white{
    background-color: #6844B5;
    color: #fff;
}

#blacktext{
    color: #fff;
}

#whitespan {
    background-color: #fff;
    outline: none;
}

.active-setting {
    transform: translate3d(0px, 0%, 0px);
    transition: all ease-in 1s;
}

JavaScript

const blackScheme = document.getElementById('black')
const blackSpan = document.getElementById('blackspan')
const blackText = document.getElementById('blacktext')

const whiteScheme = document.getElementById('white')
const whiteSpan = document.getElementById('whitespan')
const whiteText = document.getElementById('whitetext')

blackScheme.addEventListener('click', () => {
    blackSpan.classList.add('active-setting')
    blackText.classList.add('active-setting')
    whiteSpan.classList.add('active-setting')
    whiteText.classList.add('active-setting')
})

whiteScheme.addEventListener('click', () => {
    blackSpan.classList.remove('active-setting')
    blackText.classList.remove('active-setting')
    whiteSpan.classList.remove('active-setting')
    whiteText.classList.remove('active-setting')
})

I want to do less code and do it univerasal (to use many times, with same buttons)

Single HTTP request for HTML template file for multiple instances of the same Web Component

Say I have a Web Component defined like this:

// web-component.js
export class WebComponent extends HTMLElement {
  template = '/path/to/template.html';  
  tmpl = {};

  constructor() {
    super();
  }
    
  async connectedCallback() {
    const html = fetch(this.template).then(response => response.text());
    this.doSomething(await html);
  }
  
  doSomething(html) {
    console.log(html);
  }
}

document.addEventListener('DOMContentLoaded', customElements.define('web-component', WebComponent));

A template file like this:

//template.html
<template id="web-component">
    <h1>Text Goes Here</h1>
</template>

And a web page like this:

//index.html
    ....
    <head>
    <script type="module" src="/path/to/web-component.js"></script>
    </head>
    <body>
    <web-component>Foo</web-component>
    <web-component>Bar</web-component>
    <web-component>Baz</web-component>
    </body>
    ....

The web browser is making three http requests to fetch the same template file. I want to store the html from the template file somewhere on the client so I’m only making a single http request.

I tried this:

async connectedCallback() {
  const existing_template = document.body.querySelector('#web-component');
  console.log(existing_template);
  if (existing_template) {
    this.doSomething(existing_template);
  } else {
    const html = fetch(this.template).then(response => response.text());
    this.addTemplateToWebPage(await html);
    this.doSomething(await html);
}

addTemplateToWebPage(html) {
    const tag = document.createElement('body');
    tag.innerHTML = html;
    document.body.appendChild(tag.querySelector('template'));
}

But existing_template is always null, so I’m still making unnecessary http requests. I also tried this, with the same result:

connectedCallback() {
    this.doSomething();
  }

  async doSomething() {
    const existing_template = document.body.querySelector('#web-component');
    console.log(existing_template);
    if (existing_template) {
      this.doSomethingElse(existing_template);
    } else {
      const html = fetch(this.template).then(response => response.text());
      this.addTemplateToWebPage(await html);
      this.doSomethingElse(await html);
    }
  }

  doSomethingElse(html) {
    console.log('doing something else');
  }

How can I do this so I only have a single http request when calling the same template?

MongoDB to chrome extension

I am working on a project where I want to scrape a website that produces content periodically, store the content in a MongoDB cluster, preview the documents in a chrome extensions.

First two step are completed, the website is being scraped through a python script (automated through GitHub actions) and dumped in a MongoDB cluster.

I am having trouble going through the third step, what is an optimal way to fetch the data from MongoDB and preview you them in an extension. Could this be achieved using Python? Could this be done client-side Javascript? or is Node.JS needed here?

Any ideas are welcome, excuse me for a vague question but I have ran out of resources.

Rock. paper scissors stuck on for loops

BUilding a rock paper scissors project from “The Odin Project”. Right now im stuck on how to make my for loop play the game for only 5 rounds and then show the score on the console.

I tried making the for loop up to 5 rounds and console logging each win for computer and player but its not working…

Compare two Date hours

I have a two times:
“02:00” this is hoursValue : minutesValue
“02:00” this is hoursValue : minutesValue

var startTime = new Date().setHours("02:00".split(":")[0]);
console.log(startTime);

var endTime = new Date().setHours("2:00".split(":")[0]);
console.log(endTime);

var compare = startTime === endTime;
console.log(compare)

> 1672965757045
> 1672965757046
> false

I noticed that sometimes it returns the different number of milliseconds.
why this solution is bad and how to compare two hour when first one started from 0 another no.

Confused on how to get all elements of a form inside of an active tab of a modal

Like the title suggests, I have a modal, with nav tabs, and each tab has it’s own form inside of it. When I click submit, I would like to get all the inputs inside of that form to call other functions for validity checking. I have the bootstrap invalid-feedback validity checking but need to do other checking as well. How would I get those elements?

For example:

document.getElementById('modal_form_submit_button').addEventListener('click', (event) => {
    console.log('submitting form');
    event.preventDefault();
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">


<div class="modal" tabindex="-1" id="test_modal">
    <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable">
        <div class="modal-content">

            <!-- MODAL HEADER -->
            <div class="modal-header">
                <h5 class="modal-title">Test Modal</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>

            <!-- MODAL BODY -->
            <div class="modal-body">
                <!-- NAV TABS -->
                <ul class="nav nav-tabs" id="myTab" role="tablist">
                    <li class="nav-item" role="presentation">
                        <button class="nav-link active" id="tab_1" data-bs-toggle="tab" data-bs-target="#tab_1_pane" type="button" role="tab" aria-controls="tab_1_pane" aria-selected="true">
                            tab 1
                        </button>
                    </li>
                    <li class="nav-item" role="presentation">
                        <button class="nav-link" id="tab_2" data-bs-toggle="tab" data-bs-target="#tab_2_pane" type="button" role="tab" aria-controls="tab_2_pane" aria-selected="false">
                            tab 2
                        </button>
                    </li>
                </ul>

                <!-- TAB CONTENT -->
                <div class="tab-content" id="myTabContent">
                    <!-- TAB 1 -->
                    <div class="tab-pane fade show active" id="tab_1_pane" role="tabpanel" aria-labelledby="tab_1" tabindex="0">
                        <form class="needs-validation" novalidate>
                            <br>

                            <!-- 1 -->
                            <div>
                                <div class="input-group has-validation">
                                    <span class="input-group-text" id="basic-addon3">
                                        test
                                    </span>
                                    
                                    <input type="text" class="form-control" id="basic-url" list="datalistOptions" aria-describedby="basic-addon3" placeholder="placeholder" required disabled>
                                    
                                    <datalist id="datalistOptions">
                                        <option value="test2">
                                        <option value="test3">
                                    </datalist>

                                    <div class="invalid-tooltip">
                                        You need to select something.
                                    </div>
                                </div>
                                <div class="form-text">
                                    Enter/select something.
                                </div>
                            </div>

                            <br>

                            <!-- 2 -->
                            <div>
                                <div class="input-group has-validation">
                                    <span class="input-group-text" id="basic-addon3">
                                        https://test.com/test/
                                    </span>
                                    
                                    <input type="text" class="form-control" id="basic-url" aria-describedby="basic-addon3" placeholder="..." required>
                                    
                                    <div class="invalid-tooltip">
                                        You need to enter something.
                                    </div>
                                </div>
                                <div class="form-text">
                                    Enter something.
                                </div>
                            </div>

                            <br>
    
                            <!-- 3 -->
                            <div>
                                <div class="input-group has-validation">
                                    <span class="input-group-text" id="basic-addon3">
                                        Test
                                    </span>

                                    <input type="number" aria-label="Minimum" class="form-control" id="basic-url" aria-describedby="basic-addon3" placeholder="Minimum" min="1" required>
                                    <input type="number" aria-label="Maximum" class="form-control" id="basic-url" aria-describedby="basic-addon3" placeholder="Maximum" min="1">

                                    <div class="invalid-tooltip">
                                        You need to enter something.
                                    </div>
                                </div>
                                <div class="form-text">
                                    Enter the minimum and maximum.
                                </div>
                            </div>

                            <br>

                            <!-- MODAL FOOTER -->
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-primary" id="modal_form_submit_button">Submit</button>
                            </div>
                        </form>
                    </div>

                    <!-- TAB 2 -->
                    <div class="tab-pane fade" id="tab_2_pane" role="tabpanel" aria-labelledby="tab_2" tabindex="0">
                        <form class="needs-validation" novalidate>
                            <br>

                            <!-- 1 -->
                            <div>
                                <div class="input-group has-validation">
                                    <span class="input-group-text" id="basic-addon3">
                                        test
                                    </span>
                                    
                                    <input type="text" class="form-control" id="basic-url" list="datalistOptions" aria-describedby="basic-addon3" placeholder="Mainnet" required disabled>
                                    
                                    <datalist id="datalistOptions">
                                        <option value="test2">
                                        <option value="test3">
                                    </datalist>

                                    <div class="invalid-tooltip">
                                        You need to select something.
                                    </div>
                                </div>
                                <div class="form-text">
                                    Enter/select something.
                                </div>
                            </div>

                            <br>

                            <!-- 2 -->
                            <div>
                                <div class="input-group has-validation">
                                    <span class="input-group-text" id="basic-addon3">
                                        test
                                    </span>
                                    
                                    <input type="text" class="form-control" list="datalist" id="basic-url" placeholder="Type to search..." aria-describedby="basic-addon3" autocomplete="off" required>

                                    <datalist id="datalist">
                                        <!-- adding programmatically -->
                                        <!-- <option value="San Francisco"> -->
                                    </datalist>

                                    <div class="invalid-tooltip">
                                        You need to enter/select something.
                                    </div>
                                </div>
                                <div class="form-text">
                                    Enter/select something.
                                </div>
                            </div>

                            <br>
    
                            <!-- 3 -->
                            <div>
                                <div class="input-group has-validation">
                                    <span class="input-group-text" id="basic-addon3">
                                        test
                                    </span>

                                    <input type="number" aria-label="Minimum" class="form-control" id="basic-url" aria-describedby="basic-addon3" placeholder="Minimum" min="1" required>
                                    <input type="number" aria-label="Maximum" class="form-control" id="basic-url" aria-describedby="basic-addon3" placeholder="Maximum" min="1">

                                    <div class="invalid-tooltip">
                                        You need to enter something.
                                    </div>
                                </div>
                                <div class="form-text">
                                    Enter the minimum and maximum.
                                </div>
                            </div>

                            <br>

                            <!-- MODAL FOOTER -->
                            <div class="modal-footer">
                                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button>
                                <button type="submit" class="btn btn-primary" id="modal_form_submit_button">Submit</button>
                            </div>
                        </form>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<div class="position-absolute top-50 start-50 translate-middle">
    <a href="#" id="test_modal_button" class="btn btn-primary btn-lg" role="button" data-bs-toggle="modal" data-bs-target="#test_modal">
        Test
    </a>
</div>

<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

ideally would like to do this using regular javascript, not jquery/other.
Using the new alpha version of bootstrap 5 – v5.3.0-alpha1

How to smoothly interpolating colors in a Voronoi diagram to remove cell borders? (JavaScript)

I am trying to create a Voronoi diagram where the color of each cell smoothly interpolates between the colors of its nearest control points. Currently, there are visible borders between the cells in the diagram. How can I get rid of these borders and smoothly interpolate the colors of the cells?

enter image description here

here is a working example: https://codepen.io/miguel007/pen/BaPzxxy?editors=0011

this is the drawVoronoiNoise

function drawVoronoiNoise(canvas,cells=50,noiseScale=0.06,distortionStrength=5) {
  // Get the canvas context
  const ctx = canvas.getContext('2d');

  // Generate a random set of control points
  const controlPoints = [];
  for (let i = 0; i < cells; i++) {
    var x = seededRandom(i) * canvas.width
    var y = seededRandom(i+1) * canvas.height
    const j = noise(x/188.05, y/188.05)*255;

    controlPoints.push({
      x:x,
      y:y,
      color: {r:j ,g: j ,b: j }
    });
  }

//`rgb(${Math.random() * 255}, ${Math.random() * 255}, ${Math.random() * 255})`
  const points = [];
  for (let x = 0; x < canvas.width; x++) {
    for (let y = 0; y < canvas.height; y++) {
      points.push({x, y});
    }
  }
  // For each point, find the nearest control point
  for (const point of points) {
    let nearestDistance = Infinity;
    let nearestControlPoint;
    for (const controlPoint of controlPoints) {
      // Distort the distance between the point and the control point using noise
      const noiseX = noise(point.x * noiseScale, point.y * noiseScale) * distortionStrength;
      const noiseY = noise(point.x * noiseScale + 100, point.y * noiseScale + 100) * distortionStrength;
      const distance = Math.hypot(point.x - controlPoint.x + noiseX, point.y - controlPoint.y + noiseY);
      if (distance < nearestDistance) {
        nearestDistance = distance;
        nearestControlPoint = controlPoint;
      }
    }

    // Interpolate the color of the current point based on the distance to the nearest control point
    const color = nearestControlPoint.color;
    const t = 6*nearestDistance / Math.sqrt(canvas.width ** 2 + canvas.height ** 2);
    const r = Math.round(color.r + t * (255 - color.r));
    const g = Math.round(color.g + t * (255 - color.g));
    const b = Math.round(color.b + t * (255 - color.b));
    ctx.fillStyle = `rgb(${r}, ${g}, ${b})`;
    ctx.fillRect(point.x, point.y, 1, 1);
  }
}

Jquery & vanilla javascript mixed, cart not reciving updated data

to start I’m very new to code. Ive been stuck on this one problem for a week now and its killing me so i came here.

I want the h2 innerText of .item with the class of .item-selected to appear in cart once .cartadd is clicked

here’s how I tired to do that:

let itemname = $('.item-selected h1').text();


    $('.cart').show()



      $('.cart').append('<h2>' + itemname + '</h2>');

When I do this I don’t get anything though as if it didn’t exist

when I console.log

let items = $(.item-selected) console.log(items)

I get log = Object { length: 0, prevObject: {…} }

I think the problem has to do with parts of the css being implemented by vanilla javascript and not jquery but not sure if that’s the case or which part excatly.

heres that code


const dropdowns = document.querySelectorAll('.dropdownbox')
const dropdowns2 = document.querySelectorAll('.dropdownbox2')
const itemboxQER = document.querySelectorAll('.item')

const shirtBox = document.querySelector('.shirtbox')
const hoodiebox = document.querySelector('.hoodiebox')
const sockbox = document.querySelector('.sockbox')
const pantbox = document.querySelector('.pantbox')
const underwearbox = document.querySelector('.underwearbox')
const stuffbox = document.querySelector('.stuffbox')
let selected;
//================CSS==========================






dropdowns.forEach(dropdown =>{
  const select = dropdown.querySelector('.select')
  const caret = dropdown.querySelector('.caret')
  const menu = dropdown.querySelector('.menu')
  const options = dropdown.querySelectorAll('.menu li')
  selected = dropdown.querySelector('.selected')

  select.addEventListener('click', () =>{
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    select.classList.toggle('select-clicked')
    caret.classList.toggle('caret-rotate')
    menu.classList.toggle('menu-open')
  }) 
  
  options.forEach(option =>{
    option.addEventListener('click', () =>{
      sel2.pause()
      sel2.currentTime = 0
      sel2.play()
      selected.innerText = option.innerText

      if (selected.innerText === "Shirts") {
        shirtBox.style.display = "block";
      } else { shirtBox.style.display = "none";}

      if(selected.innerText === "Socks")
      {
        sockbox.style.display = "block";
      } else {sockbox.style.display = "none";}

      if(selected.innerText === "Hoodies")
      {
        hoodiebox.style.display = "block";
      } else {hoodiebox.style.display = "none";}

      if(selected.innerText === "Pants")
      {
        pantbox.style.display = "block";
      } else {pantbox.style.display = "none";}

      if(selected.innerText === "Underwear")
      {
        underwearbox.style.display = "block";
      } else {underwearbox.style.display = "none";}

      if(selected.innerText === "Stuff & Things")
      {
        stuffbox.style.display = "block";
      } else {stuffbox.style.display = "none";}

      select.classList.remove('select-clicked')
      caret.classList.remove('caret-rotate')
      menu.classList.remove('menu-open')
      options.forEach(option =>{
        option.classList.add('active')
      }) 
    })
  })
})
//====================================================

dropdowns2.forEach(dropdown =>{
  const select2 = dropdown.querySelector('.select2')
  const caret2 = dropdown.querySelector('.caret2')
  const menu2 = dropdown.querySelector('.menu2')
  const options2 = dropdown.querySelectorAll('.menu2 li')
  const selected2 = dropdown.querySelector('.selected2')

  select2.addEventListener('click', () =>{
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    select2.classList.toggle('select-clicked2')
    caret2.classList.toggle('caret-rotate2')
    menu2.classList.toggle('menu-open2')
  }) 
  
  options2.forEach(option =>{
    option.addEventListener('click', () =>{
      sel2.pause()
      sel2.currentTime = 0
      sel2.play()
      selected2.innerText = option.innerText
      
    
      
      select2.classList.remove('select-clicked2')
      caret2.classList.remove('caret-rotate2')
      menu2.classList.remove('menu-open2')
      options2.forEach(option =>{
        option.classList.add('active2')
      }) 
    })
  })
})
//====================================================
itemboxQER.forEach(item =>{

  item.addEventListener('click', () =>
    {
  
      itemboxQER.forEach(otherItem => {
        if (otherItem !== item) {
          otherItem.classList.remove('item-selected');
        }
      });

    item.classList.toggle('item-selected')
    sel2.pause()
    sel2.currentTime = 0
    sel2.play()
    })


  
  
  })

Any leads would be much appreciated!

I tried changing this

let itemname = $('.item-selected h1').text();


    $('.cart').show()



      $('.cart').append('<h2>' + itemname + '</h2>');

to its vanilla form

i tired changing parts of the css logic to jquery and both led me to the same result

Workbox and service worker, how do I get the errors in the service worker to the client?

I switched to Workbox to avoid trouble with updating the client. I like it very much, but I do not understand how to implement error handling. I know how to do it without Workbox, but I thought that errors automatically would be sent from the service worker to the client when using Workbox.

However it does not.

When I noticed this I tried the usual serviceWorker.onerror but I could not get it to work with Workbox. Could anyone please point me to a piece of code implementing this?

Adding DropDown list in jQuery DataTable

I want to display table’s data with jQuery DataTable and sometimes apply an extra data filtering, using the output of a dropdown select input.

The main code for fetching data (fetch.php) is:

<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
$query .= "SELECT * FROM Part_tb ";
if(isset($_POST["search"]["value"]))
{
    $query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
    $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
    $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
    $sub_array = array();
    $sub_array[] = $row["part_manufacturer"];
    $sub_array[] = $row["part_id"];
    $sub_array[] = $row["part_category"];
    $sub_array[] = $row["part_stock"];
    $data[] = $sub_array;
}
$output = array(
    "draw"              =>  intval($_POST["draw"]),
    "recordsTotal"      =>  $filtered_rows,
    "recordsFiltered"   =>  get_total_all_records(),
    "data"              =>  $data
);
echo json_encode($output);
?>

while the DataTable is defined in index.php as follows:

    var dataTable = $('#user_data').DataTable({
        "processing":true,
        "serverSide":true,
        "order":[],
        "ajax":{
            url:"actions/fetch.php",
            type:"POST"
        },
        "columnDefs":[
            {
                "targets":[0, 1],
                "orderable":false,
            },
        ],

    });

In index.php, i’ve created 3 dependent dropdown lists, which load data from other tables. Now, i want to take the id of 3rd dropdown list and update the data of Part_tb in fetch.php accordingly. Below, you can see that when 3rd dropdown change, i call a function load_parts():

  $(document).on('change', '#sub3_category_item', function(){
    load_parts();
  });

    function load_parts()
    {
    var action = 'fetch_data';
    var car_edition = $('#sub2_category_item').val();
        $.ajax({
            url:"actions/fetch.php",
            method:"post",
            data:{action:action, car_edition:car_edition},
            success:function(data)
            {
                $('#user_data').DataTable().ajax.reload();
            }
        });
    }

The problem is that i can’t filter the data of fetch.php according to the selected id of #sub2_category_item. Could you help me on that?

I’ve modified the fetch.php as follows:

<?php
include('db.php');
include('function.php');
$query = '';
$output = array();
if(isset($_POST["action"]))
{
    $query .= "SELECT * FROM Part_tb WHERE part_id IN (SELECT pcfit_name from Part_car_fit_tb WHERE pcfit_id ='".$_POST["car_edition"]."') ";
}else{
    $query .= "SELECT * FROM Part_tb ";
}
if(isset($_POST["search"]["value"]))
{
    $query .= 'WHERE part_manufacturer LIKE "%'.$_POST["search"]["value"].'%" ';
    $query .= 'OR part_id LIKE "%'.$_POST["search"]["value"].'%" ';
}
if(isset($_POST["order"]))
{
    $query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
}
else
{
    $query .= 'ORDER BY part_id ASC ';
}
if($_POST["length"] != -1)
{
    $query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$statement = $connection->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$data = array();
$filtered_rows = $statement->rowCount();
foreach($result as $row)
{
    $sub_array = array();
    $sub_array[] = $row["part_manufacturer"];
    $sub_array[] = $row["part_id"];
    $sub_array[] = $row["part_category"];
    $sub_array[] = $row["part_stock"];
    $data[] = $sub_array;
}
$output = array(
    "draw"              =>  intval($_POST["draw"]),
    "recordsTotal"      =>  $filtered_rows,
    "recordsFiltered"   =>  get_total_all_records(),
    "data"              =>  $data
);
echo json_encode($output);
?>

but dataTable crashes. Any help would be very useful to me!

My code running wrong and making A instead of not answered

When I pdf is generated instead of not answering it is appearing as a for this code

 function generatePDF() {
  // Create a new PDF document
  var doc = new jsPDF();

    // Define an array of questions
    var questions = [
      "Question 1", "Question 2", "Question 3", "Question 4", "Question 5",
      "Question 6", "Question 7", "Question 8", "Question 9", "Question 10",
      "Question 11", "Question 12", "Question 13", "Question 14", "Question 15",
      "Question 16", "Question 17", "Question 18", "Question 19", "Question 20",
      "Question 21", "Question 22", "Question 23", "Question 24", "Question 25",
      "Question 26", "Question 27", "Question 28", "Question 29", "Question 30",
      "Question 31", "Question 32", "Question 33", "Question 34", "Question 35",
      "Question 36", "Question 37", "Question 38", "Question 39", "Question 40",
      "Question 41", "Question 42", "Question 43", "Question 44", "Question 45",
      "Question 46", "Question 47", "Question 48", "Question 49", "Question 50",
      "Question 51", "Question 52", "Question 53", "Question 54", "Question 55",
      "Question 56", "Question 57", "Question 58", "Question 59", "Question 60",
      "Question 61", "Question 62", "Question 63", "Question 64", "Question 65",
      "Question 66", "Question 67", "Question 68", "Question 69", "Question 70",
      "Question 71", "Question 72", "Question 73", "Question 74", "Question 75",
      "Question 76", "Question 77", "Question 78", "Question 79", "Question 80",
      "Question 81", "Question 82", "Question 83", "Question 84", "Question 85",
      "Question 86", "Question 87", "Question 88", "Question 89", "Question 90"
    ];

  for (var i = 0; i < questions.length; i++) {
    // Check if there is a radio button selected for the current question
    var radioButton = document.querySelector(`input[name="${i + 1}"]:checked`);
    if (radioButton) {
      var answer = radioButton.value;
    } else {
      // Check if there is an input text field for the current question
      var inputField = document.querySelector(`input[name="${i + 1}"]`);
      if (inputField) {
        var answer = inputField.value;
      } else {
        var answer = "Not answered";
      }
    }

    // Wrap the text in cells
    doc.cell(20, 20 + i * 10, 100, 10, questions[i], i);
    doc.cell(50, 20 + i * 10, 100, 10, "Answer: " + answer, i);
  }

  // Save the PDF
  doc.save("Question and answers.pdf");
}

I was expecting it will generate not answered if questions are left blank but it is showing as a (option) for this div

<div id="question75" class="question" style="display:none;">
    <p>Question 75</p>
    <div id="answers" class="answers">
      <label>
        <input type="radio" name="75" value="A">
        a
      </label>
      <label>
        <input type="radio" name="75" value="B">
        b
      </label>
      <label>
        <input type="radio" name="75" value="C">
        c
      </label>
      <label>
        <input type="radio" name="75" value="D">
        d
      </label>
    </div>
</div>

Sidebar stick to bottom (CSS or JS) – reset to top

I’m trying to build a page with a left sidebar that becomes sticky when the viewport reaches the bottom of that sidebar. I have tried using position:sticky but each time the viewport was reaching the bottom of the sidebar, the stickiness worked but the sidebar was set to top:0px.

I have then tried to do the same with javascript, I can trigger the changes when the bottom of the sidebar crosses the viewport but again, the sidebar gets positioned from the top and is not entirely visible. I suspect it has something to do with height settings but I can’t isolate it.

I have created a codepen to show what is happening once content in inserted into the page:

https://codepen.io/LaurentWi/pen/OJwbrRw (it’s too long to be copied here)

The html without the content is the following:

<body>
  <div id="buffer">
  </div>
  <div id="content_left">
    <div class="sub_container">
    </div>
    <div class="sub_container">
    </div>
    <div class="sub_container">
    </div>
 </div>
<div id="content">
</div>

I have used a “buffer” div to keep the rest of the screen in the right position when content_left leaves the flow.

The CSS looks like this:

    body
    {
        margin:0px;
        padding:0px;
  
        width:100%;
        height;100%;
  
        background-color:#777b87;

        min-height: 100%;
        overflow-x:hidden;
        
        display:flex;
        flex-flow:row wrap;
        justify-content:center;
        max-width:1920px;
        margin:0 auto;
    }

    #content_left
            {
                display:flex;
                flex-flow:column nowrap;
                width:300px;
                padding:0px 10px 0px 10px;
      position:sticky;
      height:100%;
      bottom:0px;
            }

#content
    {   
        width:calc(100% - 60px);
        
        padding:20px;
        margin: 0px 10px 0px 10px;
        border-radius: 5px;
        margin-top:10px;
        z-index:100;
        border:1px solid #CCC;

  width: calc(100% - 350px);
  max-width: 850px;
}
#buffer
{
  display:none;
  height:1px;
  width:300px;
  padding:0px 10px 0px 10px;
}

And finally the JS:

const target = document.getElementById('content_left');
const init_rect = target.getBoundingClientRect();
const index_height = init_rect.height;
console.log('initial height '+index_height); 
const viewportHeight = window.innerHeight || document.documentElement.clientHeight;

window.onscroll = function()
{
    const rect = target.getBoundingClientRect();
    const buffer = document.getElementById('buffer');
    
    console.log("viewport :"+viewportHeight);
    console.log("top: "+rect.top);
    console.log("bottom: "+rect.bottom);
    console.log("height: "+rect.height);
    top_diff = viewportHeight-index_height;
    console.log("topdiff: "+top_diff);
    if (rect.bottom < viewportHeight) 
        {
            console.log('passed');
            target.style.position='fixed';
            buffer.style.display='block';
            buffer_position = buffer.getBoundingClientRect();
            target.style.left=buffer_position.left+"px";
            target.style.bottom="0px";
            
        }       
};

I would prefer a solution without JS if you have one but JS is fine as long as it is only vanilla JS.

I suspect that the problem is coming from the height because when the JS display the height of content_left, the value is ok until the element is in position fixed where the height value becomes the viewport height (see console in codepen). I have tried avoiding this by forcing the initial height but it didn’t work either because the initial height (see code in JS) was always smaller than the reality. I’m a bit puzzled.

Any idea?

How to dynamically import a file based on user input

I’m writing an npm module and want to allow users to create a config file to control how the command line calls to this module run. How can I import this config file reliably? Ideally this should work in development using NPM link as well as in production.

Example file structure:

- project folder
  - node_modules
    - my_module
      - cli.mjs (Where the command line processing is running)
  - my.config.mjs

So, ideally, I want to reliably be able to import my.config.mjs if it exists. I’ve tried several ways of using the dynamic import. The most(?) successful has been:

const baseDir = process.cwd();
const configPath = path.resolve(baseDir,'./my.config.mjs');
const configURL = new URL(configPath);
const userOpts = import(configURL.pathname);
console.log('userOpts',userOpts);

This gives me an error though (using npm link):

TypeError [ERR_INVALID_MODULE_SPECIFIER]: Invalid module "GitKurohyou_studiosinittestk.config.mjs" is not a valid package name imported from E:GitKurohyou_studiosk-scaffoldcli.mjs

So, what’s the proper way for me to dynamically import this config file?

How can I make sure that the jquery function works only for the element which is hovered on

I basically want the class to get added on only the elements one hovers on and not all of them. E.g., if someone hovers on the 2nd bullet point, the text gets displayed only for that one and the styles also changes respectively but currently, the text gets displayed for all the parent divs. How can I achieve the same?

Here’s a codepen of what I’m trying to do: https://codepen.io/JK1314/pen/XWBNxma.

<section class="mattress-layers section">
        <div class="container">
    
            <div class="columns is-flex-desktop is-align-items-center is-centered is-desktop">
                <div class="column is-hidden-touch">
                    <div class="list-wrapper">
                        <div class="list-item-wrapper mb-5">
                            <div class="list-item">
                                <div class="list-item-heading">
                                    <div class="list-bullet">1</div>
                                    <div class="list-title"><p>Mattress Knit Cover <br>+ Optional Cool+ Cover Upgrade</p></div>
                                </div>
                                <div class="list-text"><p>A supremely soft cover with a durable knit. Upgrade to the Cool+ cover for even more cooling and comfort.</p></div>
                            </div>
                        </div>
                        <div class="list-item-wrapper mb-5">
                            <div class="list-item">
                                <div class="list-item-heading">
                                    <div class="list-bullet">2</div>
                                    <div class="list-title"><p>2” Full-Body Cooling Gel Foam</p></div>
                                </div>
                                <div class="list-text"><p>A full layer of gel memory foam to help you sleep comfortably, even during summer. The cushioning surface contours to your body and helps prevent pressure points from forming.</p></div>
                            </div>
                        </div>
                        <div class="list-item-wrapper mb-5">
                            <div class="list-item">
                                <div class="list-item-heading">
                                    <div class="list-bullet">3</div>
                                    <div class="list-title"><p>6” Total Support Foam</p></div>
                                </div>
                                <div class="list-text"><p>Enjoy robust support for your hips and back. Juno's bottom layer eliminates motion transfer and helps you feel properly supported when sleeping on your side, back, or stomach.</p></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>    
        </div>
    </section>
        .mattress-layers .subtitle {
            font-family: libre franklin;
            font-size: 19px !important;
        }

        .mattress-layers .list-wrapper {
            position: relative;
        }

        .mattress-layers .list-wrapper .list-item-wrapper {
            margin-top: 10px;
            position: relative;
        }

        .mattress-layers .list-wrapper .list-item-wrapper .list-bullet {
            float: left;
            margin-right: 20px;
            background: #717571;
            height: 30px;
            width: 30px;
            line-height: 30px;
            border-radius: 100px;
            font-weight: 700;
            color: #fff;
            text-align: center;
        }

        .mattress-layers .list-wrapper .list-item-wrapper .list-item-heading {
            vertical-align: middle;
        }
        
        .mattress-layers .list-wrapper .list-item-wrapper .list-item .list-title {
            color: #717571;
            font-weight: 600;
            font-style: normal;
        }

        .mattress-layers .list-wrapper .list-item-wrapper .list-item .list-text {
            font-weight: 400;
            color: #717571;
            display: none;
        }

        .mattress-layers .list-wrapper .list-item-wrapper:last-child .list-item-line {
            background: #fff;
            z-index: 0;
            top: 30px;
            width: 1px;
            height: 100%;
            position: absolute;
            left: 15px;
        }

        .mattress-layers .mobile-layers-carousel .highlight {
            font-size: 1.175rem;
        }

        .mattress-layers .mobile-layers-carousel .swiper {
            margin-left: -15px;
            margin-right: -15px;
            padding-left: 35px;
            padding-right: 35px;
        }

        .mattress-layers .mobile-layers-carousel .slide-title {
            color: #212721;
            font-weight: bold;
        }

        .mattress-layers .mobile-layers-carousel .swiper-pagination {
            position: relative;
        }

        .mattress-layers .mobile-layers-carousel .swiper-pagination.swiper-pagination-bullets {
            bottom: 0;
        }

        .mattress-layers .mobile-layers-carousel .swiper-pagination .swiper-pagination-bullet {
            background: #717571;
            color: #fff;
            height: 1.75em;
            opacity: 1;
            width: 1.75em;
            line-height: 1.7rem;
            font-weight: 600;
        }

        .mattress-layers .mobile-layers-carousel .swiper-pagination .swiper-pagination-bullet.swiper-pagination-bullet-active {
            background: #212721;
            border-color: #212721;
            color: #fff;
        }

        .mattress-layers .mobile-layers-carousel .swiper-button-prev {
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512'%3E%3Cpath fill='%23235b4e' d='M224 480c-8.188 0-16.38-3.125-22.62-9.375l-192-192c-12.5-12.5-12.5-32.75 0-45.25l192-192c12.5-12.5 32.75-12.5 45.25 0s12.5 32.75 0 45.25L77.25 256l169.4 169.4c12.5 12.5 12.5 32.75 0 45.25C240.4 476.9 232.2 480 224 480z'/%3E%3C/svg%3E") no-repeat left center;
            background-size: 15px;
            left: 0;
            top: 35%;
        }

        .mattress-layers .mobile-layers-carousel .swiper-button-prev::after {
            content: none;
        }

        .mattress-layers .mobile-layers-carousel .swiper-button-next {
            background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 320 512'%3E%3Cpath fill='%23235b4e' d='M96 480c-8.188 0-16.38-3.125-22.62-9.375c-12.5-12.5-12.5-32.75 0-45.25L242.8 256L73.38 86.63c-12.5-12.5-12.5-32.75 0-45.25s32.75-12.5 45.25 0l192 192c12.5 12.5 12.5 32.75 0 45.25l-192 192C112.4 476.9 104.2 480 96 480z'/%3E%3C/svg%3E") no-repeat right center;
            background-size: 15px;
            right: 0;
            top: 35%;
        }

        .mattress-layers .mobile-layers-carousel .swiper-button-next::after {
            content: none;
        } 

        /* MATTRESS LAYER HOVER STYLES AND TEXT STYLES */
        /* filter: drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.25)); */
        .list-item-hover .list-bullet {
            background: #212721 !important;
            filter: drop-shadow(0px 4px 4px rgba(0, 0, 0, 0.25));
          transition: background-color 0.5s ease;
        }

        .list-item-hover .list-title {
            color: #212721 !important;
          transition: color 0.5s ease;
        }

        .list-item-hover .list-text {
            display: block !important;
            text-indent: 3em !important;
          transition: display 0.5s ease-in;
        }
$(document).ready(function() {
        $(".list-title").hover(function(){
            $(".list-item").addClass("list-item-hover")            
        });
        
    });