How to have multiple events with a single onclick in javascript

I am veryyy new to this and am trying out a small project while I learn html/css/javascript. So, sorry if this is a fairly obvious question/answer.

Basically, I made my (very simple) site have a dark mode using this set up:

CSS

:root{
    --primary-color: #ffffff;
    --secondary-color: #1d1d1d;
}
.dark-theme{
    --primary-color: #212121;
    --secondary-color: #e0e0e0;
}

I then use primary/secondary for all my background/text colors. Then,

SCRIPT

var icon = document.getElementById("icon");

   icon.onclick = function (){
        document.body.classList.toggle("dark-theme");
       if(document.body.classList.contains("dark-theme")){
          icon.src = "/images/sun-2-svgrepo-com.png";
     }else{
        icon.src = "/images/moon-stars-svgrepo-com.png";
   }
}

This is so when someone clicks my moon image tagged “icon” the colors inverse, and “icon” turns into a sun image. This works perfect for my dark mode!

I tried to insert the same process for “icon” underneath to see if it would happen at the onclick also…

var icon = document.getElementById("icon");

    var icon = document.getElementById("icon");

    icon.onclick = function (){
        document.body.classList.toggle("dark-theme");
        if(document.body.classList.contains("dark-theme")){
            icon.src = "/images/sun-2-svgrepo-com.png";
            icon2.src = "/images/lightmode.png";
        }else{
            icon.src = "/images/moon-stars-svgrepo-com.png";
            icon2.src = "/images/darkmode.png";
        }
}

it didn’t work.

My questions is, is there a way to change my other images (png, used as icons) from their light mode image to dark mode image. Basically, when the moon image changes to the sun image by the click, how can I have my other images switch as well?

Thank you!

How do I convert milliseconds into a date object?

I am trying to make a function that is, effectively, the opposite of getTime(); it takes a number of milliseconds as an input and converts the number into years, days, hours, seconds, and milliseconds, and then returns a Date object with those values. The conversion works perfectly, but when I try to create the Date object, things go wrong.

The code for the conversion itself is this:

function milliConvert(milliseconds){
const second = 1000;
    const minute = 1000 * 60;
    const hour = minute * 60;
    const day = hour * 24;
    const year = day * 365;
    let years2 = Math.floor(milliseconds / year);
    let days = Math.floor(milliseconds / day)-(years2*365);
    let hours = Math.floor((milliseconds / hour)-(((years2*365))*24+(days*24)));
    let minutes = Math.floor((milliseconds / minute)-(((years2*365))*24*60+60*(days*24)+((hours)*60)));
    let seconds= Math.floor((milliseconds / second)-((years2*365*24*60*60)+(days*24*60*60)+(hours*60*60)+(minutes*60)));
    let outMilli= Math.floor((milliseconds)-((years2*365*24*60*60)+(days*24*60*60)+(hours*60*60)+(minutes*60)+(seconds*1000)));
    console.log(years2+":"+days+":"+hours+":"+minutes+":"+seconds)
//the rest of this function is in the next code snippet

Like I said earlier, it works as expected. But I had to do a lot of troubleshooting with the code for converting it into a Date object, and it still doesn’t work.
My first iteration would always give me a large negative number, but I realized that that was because the years2 value was below 1970, so I made sure to increment it by 1970. After that, it still didn’t work, because the day and hour values had been, for some unknown reason, increased by 30 and 5 respectively. My current code for creating the date object is this:


return(new Date(years2+1970,1,days-30,hours-5,minutes,seconds,outMilli));
}

It works fine with smaller dates, but if I set milliseconds to Date.now(), the value of the date is “2078-08-14T17:48:43.764Z” (according to the VSCode console, when the command was run the time and date were 2024-04-27 15:29:03). My goal is for milliConvert(x).getTime() to equal X. I am aware that other people have answered similar questions before, but I would still like to know why this specifically doesn’t work, as I think it will help further my understanding of the Date object.
Thanks in advance!

How to deal with denied access in local host?

how to solve this error : Fatal error: Uncaught PDOException: SQLSTATE[HY000] [1045] Access denied for user ‘root’@’localhost’ (using password: NO) in C:xampphtdocsgrocery storeconfig.php:7 Stack trace: #0 C:xampphtdocsgrocery storeconfig.php(7): PDO->__construct(‘mysql:host=loca…’, ‘roottext

i changed the port config from 3306 to 3307 and phpMyAdmin works and the site doesn’t appear ( I downloaded a project folder of website code using html,css,js,php,mysql)

React Slick infinite slide transition issue

It seems that having infinite set to true causes a bug to occur in which after reaching the end of the slides it does not smoothly continue over to a clone but rather glitches back to the first element. The cloned elements are visible but it does not flow over to them.

Here is my settings for it:

const newArrivalsSettings = {
    infinite: true,
    slidesToShow: 5,
    slidesToScroll: 1,
    // centerMode:true,
    speed: 500,
    arrows:true,
    dots:true,
    // variableWidth: true,
    initialSlide: 0, // Ensure first slide is initially active
nextArrow: <SampleNextArrow />,
prevArrow: <SamplePrevArrow />,
  customPaging:( i:any) => (
    <div
      style={{
      }}
    >
     
    </div>
  ),
  responsive: [
    {
      breakpoint: 1024,
      settings: {
        slidesToShow: 3,
        slidesToScroll: 1,
        initialSlide: 0,      
          infinite: true,

        dots: true
      }
    },
    {
      breakpoint: 600,
      settings: {
        slidesToShow:1,
        slidesToScroll: 1,
        initialSlide: 1
      }
    },
    {
      breakpoint: 480,
      settings: {
        slidesToShow: 1,
        slidesToScroll: 1
      }
    }
  ]
  };```


I have set infinite:::true , I am expecting it should have a smooth between the last element and first element. **Also I have set the width of Active slide (current slide) more than the rest of the slides.**

File downloaded using ytdl-core is not complete when sent to client

I’m working on a Node.js application that downloads audio files from YouTube using the ytdl-core library and then sends them to clients for download.I’m facing this issue where the downloaded file is incomplete when it is sent to the client.

const audioStream = fs.createWriteStream(outputPath);
audio.pipe(audioStream, { end: false });

audio.on("progress", (_, downloaded, total) => {
  const percent = ((downloaded / total) * 100).toFixed(2);
  console.log(percent);
  io.emit("progress", percent);
});

audio.on("end", () => {
  console.log("Download complete");
  res.send(outputPath);
});

audio.on("error", (err) => {
  console.error("Error downloading audio:", err);
  res.status(500).json({ error: "Error downloading audio" });
});

I have tried reading the stream and piping the response to client, it works but what happens is the download dialog box appears very late and when i click on save the download is already complete. i want the file to start downloading on the clients browser.

How to animate a radar chart

So I am very new to coding, but a friend asked me to help them make a radar chart that showcases their skills. I have found an example online that I have made some changes to to customize it to their needs. The issue I am having is figuring out how to animate it. What I am trying to do is have each of the plot points move out one at a time until the chart is fully expanded. I then am trying to have each of them collapse from their final value (ie. 65) back to 0, and then repeat the process of expanding again. So basically I want them to expand out one at a time and then after they are all expanded to collapse one by one until the are back to zero, then out again and have this continuously repeat (if possible). I am not sure if this is possible or too much. I have looked online for any sort of animation to at least expand one by one, but I can’t find anything. I am including the code I have below:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <title>Radar Chart in JavaScript</title>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-core.min.js"></script>
    <script src="https://cdn.anychart.com/releases/8.11.0/js/anychart-radar.min.js"></script>
    <style type="text/css">
      html, body, #container {
        width: 100%;
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>
  <body>
    <div id="container"></div>
    <script>

      anychart.onDocumentReady(function () {

        // create a data set
        var chartData = {
          rows: [
            ['Advertising', 33],
            ['Branding', 34],
            ['Creative Problem-Solving', 17],
            ['Digital Marketing', 50],
            ['Research', 24],
            ['SEO', 11],
            ['Social Media Marketing', 59],
            ['Strategy', 43],
            ['UI', 22],
            ['UX', 73]
          ]
        };

        // create a radar chart
        var chart = anychart.radar();

        // set the series type
        chart.defaultSeriesType('area');

        // set the chart data
        chart.data(chartData);

        // set the color palette
        chart.palette(['#9BC53DE6']);

        // configure the appearance of the y-axis
        chart.yAxis().stroke('#000000');
        chart.yAxis().ticks().stroke('#000000');

        // configure the stroke of the x-grid
        chart.xGrid().stroke({
          color: "#545f69",
          thickness: 0.5,
          dash: "10 5"
        });

        // configure the appearance of the y-grid
        chart.yGrid().palette(['gray 0.05', 'gray 0.025']);

        // begin the y-scale at 0
        chart.yScale().minimum(0);

        // set the y-scale ticks interval
        chart.yScale().ticks().interval(10);

        // set the hover mode
        chart.interactivity().hoverMode('by-x');

        //  set the marker type
        chart.markerPalette(['star5']);

        // improve the tooltip
        chart.tooltip()
          .displayMode('union')
          .useHtml(true)
          .format(function(e){
            console.log(this);
            return '<span style="color:' + this.series.color() + '">' +
              this.seriesName + ": " + this.value + "</span>"
          });

        // set chart legend settings
        chart.legend()
          .align('center')
          .position('center-bottom')
          .enabled(false);

        // set the chart title
        chart.title("Services");

        // set container id for the chart
        chart.container('container');

        // initiate chart drawing
        chart.draw();
      });

    </script>
  </body>
</html>

If possible could you please provide me with help on how to code something like this. I will need to include it in this code as they need one html file that they can upload to their Wix website.

I am not sure if any of this is possible, but I would really appreciate any sort of help or code that I can use.

Thank you so much for your time and help.

My website has a bar in the right side so all the centered things look off place

Help i keep getting a bar at the side of my webpage and my header is ending after it should at the side anyone knows how to fix this? i tried anything, im using boostrap, i think the header its the problem but i don’t have any width css i think, and the idea is that i keep maintaining the responsive part

HTML
https://codeshare.io/Ljr7mV
CSS
* {
    font-family: 'Lucida Sans', 'Lucida Sans Regular', 'Lucida Grande', 'Lucida Sans Unicode', Geneva, Verdana, sans-serif;
}

body {
    background: #161815;
}

.section-padding {
    padding: 70px 0;
}

.carousel-item {
    height: auto;
    min-height: 300px;
}

.carousel-caption {
    bottom: 200px;
    z-index: 2;
}

.carousel-caption h5 {
    font-size: 45px;
    text-transform: uppercase;
    letter-spacing: 2px;
    margin-top: 25px;
}

.carousel-caption p {
    width: 60%;
    margin: auto;
    font-size: 18px;
    line-height: 1.9;
}

.carousel-inner:before {
    content: "";
    position: absolute;
    width: 100%;
    height: 100%;
    top: 0;
    left: 0;
    background: rgba(0, 30, 82, 0.327);
    z-index: 1;

}
@media (max-width: 767px) {
    #carouselE {
        margin-top: 150px;
    }
}
.carousel-item img {
    max-height: 65%; 
}

.navbar-nav a {
    font-size: 15px;
    text-transform: uppercase;
    font-weight: 500;
}

.navbar-dark .navbar-brand {
    color: blanchedalmond;
    font-size: 25px;
    text-transform: uppercase;
    font-weight: bold;
    letter-spacing: 2px;
}

.navbar-light .navbar-brand:focus,
.navbar-light .navbar-brand:hover {
    color: black;
}

.w-100 {
    height: 100vh;
}

.navbar-toggler {
    padding: 1px 5px;
    font-size: 18px;
    line-height: 0.3;
}

.services .card-body i {
    font-size: 50px;
}

.team .card-body i {
    font-size: 20px;
}

.ocre-text {
    color: #e7b921; 
}

@media(max-width: 767px) {
    .navbar-nav {
        text-align: center;
    }

    .carousel-item {
        height: 70vh;
    }

    .w-100 {
        height: 60vh;
    }

    .carousel-caption {
        bottom: 125px;
    }

    .carousel-caption h5 {
        font-size: 17px;
    }

    .carousel-caption a {
        padding: 10px 15px;
        font-size: 15px;
    }

    .carousel-caption p {
        width: 100%;
        line-height: 1.5;
        font-size: 12px;
    }

    .about-text {
        padding-top: 50px;
    }

    .card {
        margin-bottom: 30px;
    }

    .section-padding {
        padding: 50px 0;
    }
/*ADICION RESPONSIVE*/
    .navbar-toggler {
        padding: 8px 10px;
        font-size: 20px;
    }
    .navbar-nav .nav-item {
        margin-bottom: 10px;
    }

    .services .section-header h2,
    .portfolio .section-header h2 {
        font-size: 25px;
    }

    .services .section-header p,
    .portfolio .section-header p {
        font-size: 14px;
    }

    .about .about-text,
    .services .card-body,
    .team .card-body {
        text-align: center;
    }

    .about .about-img img {
        margin-bottom: 20px;
    }

.ocre-text {
    color: #cc7722;

}

.footer-bg {
    background-color: hsl(53, 74%, 60%);
    padding: 20px 0;
    text-align: center;
}
 

.plan-terapia {
    background-color: #e7b921; }




   
}


.container {
    margin: 1px
}  



/*REGISTRO*/

.mi-clase {
    color: #e7b921; 
    
}
#titulonomayusculas .no-uppercase {
    text-transform: none;
}
footer h5 {
    font-size: 18px;
    color: rgb(231, 200, 3);
    margin-bottom: 10px; 
    letter-spacing: 1px; 
}



I’m encountering an issue in my code, and I’d appreciate some help troubleshooting. Here’s what I’m experiencing:

I’m getting a very strange output from a JavaScript function that’s supposed to calculate a percentage.

I was expecting the function to output 25 when given the input of 5 and 20. Instead, the result is consistently way too high (e.g., 2500 instead of 25). I can’t figure out why the calculation is being scaled like this.

Could there be something I’m missing about how JavaScript handles percentages or arithmetic operations?

how to use result set of db.all in db.run command that is just next to it. Given these both are in db.serialize()

`db.serialize(()=>{

const rightjoinpromise=new Promise((resolve,reject)=>{

            db.all(
              'select temp_data.colour,temp_data.size,temp_data.price,temp_data.quantity,temp_data.barcode,shoe.shoe_id from shoe right join temp_data on shoe.article_name=temp_data.article_name',
              (err, rows) => {
              console.log('in db.all at start')
              
              if (err) {
                dialog.showMessageBox(mainWindow, {
                  message: `or or here Internal Server Error, ${err.message}`,
                  buttons: []
                })
                reject(err)
              } else {
                console.log('in db.all else at start')
                
                if (!rows.length) {
                  console.log('No result got from right join of TEMP_DATA and SHOE tables')
                } else {
                  // new Promise((resolveee, rejecttt) => {
                    // db.serialize(()=>{
                      console.log('in db.all before foreach at start')
                      console.log("rows: ",rows)
                      rightjoinrows=rows
                      console.log('rows array copied into rightjoinrows',rightjoinrows)
                      resolve(rows)
                      
                      //   resolveee()
                      // }).finally(()=>{
                        
                        // })
                      }
                    }
                  }
                )
                
              })

              rightjoinpromise
              .then((rows)=>{

                rows.forEach((row) => {
                  ...........
        })
})`

I’ve tried using promises, callbacks. but nothing is working
The db.close() at end of db.serialize() is getting executed before db.run() and causing error
I want that result set of db.all() be used in db.run()

Grouping functions together in javascript

I’m trying to group functions together in javascript, though I have some difficulty understanding how to keep track of the groups. In the below example, my question is: How does: “some.get(‘anotherContent’)” knows that it’s queried under alias “anotherSomeSome” and not “anotherSome” – What I mean is, how to keep the track of the different aliases in this model? Below is what I have tried, but I find it quiet complex and hard to keep track of the aliases:

class someClass {
    alias(callback) {
        callback();
        return this;
    }

    get(content) {
        return 'some' + content;
    }
}

const some = new someClass();

some.alias('some', () => {
    some.alias('anotherSome', () => {
        some.get('content')
    })
    
    some.get('contents')

    some.alias('anotherSomeSome', () {
        some.get('anotherContent')
    })
})

How to remove few fields in grid using ext.js

Below is my javascript code that I am using to remove few columns in grid

data: function (){
var data = this.base.data.call(this);
data[0].lookup.gridcustomization.gridSequence= data[0].lookup.gridcustomization.gridSequence.filter(
item => item.dataIndex != "st1" && item.dataIndex !==  "ZonalCode"
);
return data;
}

The above code removes the 2 records in gridcustomization but it is still getting binded in frontend. Will the data in formHtml and quicktip makes the data still to be displayed in frontend if yes how can I remove those two from my quicktip and formTitle i finally should not see ST1 and ZonalCode in grid

this is the screenshot how the content was built in data variable

Highlight selected row in DataTable

I have a table that is using the DataTables library that appears in a modal with data. The idea here is that I will click on a row which will load information into a textarea. I have all of that working. What I want to do is have the row that is selected stay highlighted. I have attempted multiple versions of this but I’m still not getting the result that is wanted.

I have a clean fiddle that shows the modal and a stripped down version of the returned table here: https://jsfiddle.net/yogx3ksf/1/ In this fiddle

I have tried to add in the select JS with this fiddle but still not getting this to work

https://jsfiddle.net/dw1jrohx/

var columns = []; // Initialize columns variable globally

$(document).ready(function() {
  var table = $('#customerTable').DataTable({
        select: {
            style: 'single'
        }
    }); // Initialize DataTables with select

  var secondTable = null; // Initialize secondTable variable

  $('#customerTable tbody').on('click', 'tr', function() {
    var userId = $(this).data('userid');

    console.log("Clicked on row with userId:", userId);

React Element with HTML Parameters Not Rendering

On a page, I have a element embedded in HTML:

{dataTable}

Which is initialised as:

  const [dataTable, setDataTable] = useState(<p>Data Table Loading...</p>);

And updated in a useEffect function, where I make a database(supabase PostgreSQL) call, to get data for to-do items.

let dataTable = <DataTable todos={todos} todoLogs={todoLogs} deleteTodo={deleteTodo} toggleTodo={toggleTodo}></DataTable>

setDataTable(dataTable)

But when it’s embedded in the page, nothing shows up and I don’t get any errors.

Other elements with a siple structure like </h1>Hello World</h1> , do show up on the page, and when using useState() etc, just like dataTable

When I console.log() the dataTable element, I get:

Browser Console console.log(dataTable) output

Object
$$typeof
: 
Symbol(react.element)
key
: 
null
props
: 
{todos: null, todoLogs: null, deleteTodo: ƒ, toggleTodo: ƒ}
ref
: 
null
type
: 
class DataTable
_owner
: 
null
_store
: 
{validated: true}
_self
: 
undefined
_source
: 
{fileName: 'C:/Users/tobyh/Desktop/coding-projects/2 }} testin…}/{{REACT}}/table-todo-testing/src/pages/Home.jsx', lineNumber: 132, columnNumber: 21}
[[Prototype]]
: 
Object

If you’re interested, here is what the DataTable component class looks like:

class DataTable extends React.Component {

    constructor(props) {
        super(props);

        this.todos = props.todos
        this.todoLogs = props.todoLogs
        this.deleteTodo = props.deleteTodo

      }


  render() {

    const data = this.todoLogs;
    

    // Map over the data to generate table rows

    try {

      const tableRows = data.map((todoLog) => (


        <tr key={todoLog.id}>
          <td>{this.todos.find(x => x.id === todoLog.id).title}</td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d09_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d08_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d07_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d06_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d05_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d04_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d03_04_24}></input></td>
          <td><input type="checkbox" onChange={() => {this.todos.find(x => x.id === todoLog.id)}} checked={todoLog.d02_04_24}></input></td>
          <td><button><i className="material-icons" onClick={() => {this.deleteTodo(todoLog.id)}}>delete</i></button></td>
        </tr>
      ));

      return (
        <table>
          <thead>
            <tr>
              <th>Title</th>
              <th>09/04</th>
              <th>08/04</th>
              <th>07/04</th>
              <th>06/04</th>
              <th>05/04</th>
              <th>04/04</th>
              <th>03/04</th>
              <th>02/04</th>
            </tr>
          </thead>
          <tbody>
            {tableRows}
          </tbody>
        </table>
      );
     

    } catch (error) {

      console.log("22 could not render table, data not available", error)

    }

    // Render the table with the generated rows
    
  }
}

Thanks

I’ve tried:

  • Researching the problem

  • Experimenting embedding other html elements, and getting the results

  • Ensuring the other parts of the code are error free