OnClick function using Vite+Blade Laravel

I have a new laravel application, where I am using Vite

I have already included my js files in vite.config and also in the head of my html

@vite(['resources/js/services/live.js'])

however, when I try to use a button with the onclick function, it does not find any of my functions.

For example, let’s say this is my js file “resources/js/services/live.js”

var Print = function () { alert('Test'); };

Now in my html, where I have already included my js using vite, I want to do the following

<input type="button" onclick="Print()"

But when I click the button, js debugger says “Print is undefined”

I have already tried with function Print()…, export function…, but the same result

Is there something that I am missing using vite?

I have tried exporting the function, creating a variable to access, creating a class, but none looks to work

mongoose.connection Cannot read properties of undefined (reading ‘on’)

When trying to establish a connection to the DB in atlas. I get Cannot read properties of undefined (reading 'on')

db.js

import mongoose from "mongoose";
import dotenv from "dotenv";
mongoose.Promise = global.Promise;
mongoose.set("strictQuery", false);

dotenv.config()


let connection_uri = process.env.MONGODB_URI;
let cachedMongoConn = null;

export const connectToDatabase = () => {
  return new Promise((resolve, reject) => {
    //mongoose.Promise = global.Promise;
    mongoose.connection
    console.log(mongoose.connect)
      .on("error", (error) => {
        console.log("Error: connection to DB failed");
        reject(error);
      })
      .on("close", () => {
        console.log("Error: Connection to DB lost");
        process.exit(1);
      })
      // Connected to DB
      .once("open", () => {
        // Display connection information
        const infos = mongoose.connections;

        infos.map((info) =>
          console.log(`Connected to ${info.host}:${info.port}/${info.name}`)
        );
        // Return successful promise
        resolve(cachedMongoConn);
      });
    if (!cachedMongoConn) {
      cachedMongoConn = mongoose.connect(connection_uri, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        connectTimeoutMS: 60000,
        bufferCommands: false, 
      });
    } else {
      console.log("MongoDB: using cached database instance");
      resolve(cachedMongoConn);
    }
  });
};

Commenting out both .on I get the same error on .once

Not sure why I’m having issues with connection with mongoose.connection, maybe its an ES6 issue.

Any help you provide would be greatly appreciated.

Toggle change class for button

I have buttons. Buttons have the function which shows/hide some text. I’d like to set button different color when it’s clicked and when i click again. Color is changed back.

I think i go wrong. In this case i don’t see how i could change it back. Ofc i can use .removeClass(".clicked") but i dont know how to set this function for every even click.

$(".toggle").click(function () {
  $(".toggle").addClass("clicked");
});

Another option is use something like this 'green' ? 'red' : 'green'; but tbh. I’ve started with JS like 2 weeks ago and i no have noidea..

I’m not sure if it’s important information. But the buttons are generated from this code via ForEach loop

function toggle(i) {
const divs = document.querySelectorAll(
#text_${i}, #result_${i}, #image_${i}
);

  for (let div of divs) {
    if (div.style.display !== "none") {
      div.style.display = "none";
    } else {
      div.style.display = "block";
    }
  }
}

const container = document.querySelector("#examples-container");

examples.forEach((ex, i) => {
  // Make the div for the <div class="card">
  const card = document.createElement("div");
  // Add the "card" class to the div
  card.classList.add("card");

  // Create the div for the <div class="example">${ex.question}</div>
  const example = document.createElement("div");
  // Add the "example" class
  example.classList.add("example");
  // Set the HTML inside of it to ex.question
  example.innerHTML = ex.question;
  // Add it to the card element
  card.appendChild(example);

  // Create the button for the <button class="Toggle">Toggle</button>
  const button = document.createElement("button");
  // Add the "toggle" class to the button
  button.classList.add("toggle");
  // Set the text inside of it to say "Toggle"
  button.innerHTML = "výsledek";
  // Add the onclick event listener
  button.addEventListener("click", () => toggle(i));
  // Add the toggle button to the card
  card.appendChild(button);

  //For answer
  // Create the div for the <div id="result_${i}" class="result">${ex.answer}</div>
  const result = document.createElement("div");
  // Add the id for the element
  result.id = "result_" + i;
  // Hide the result element (display: none)
  result.style.display = "none";
  // Add the "result" class
  result.classList.add("result");
  // Set it's HTML to the answer
  result.innerHTML = ex.answer;
  // Add the result element to the card
  card.appendChild(result);

  //For Image
  const image = document.createElement("div");
  image.id = "image_" + i;
  image.style.display = "none";
  image.classList.add("image");
  image.innerHTML = ex.image;
  card.appendChild(image);

  //For Text
  const text = document.createElement("div");
  text.id = "text_" + i;
  text.style.display = "none";
  text.classList.add("text");
  text.innerHTML = ex.text;
  card.appendChild(text);

  // Add the card to the container
  container.appendChild(card);
});

How to fully disable click capture on buttons in javascript for HTML buttons

The aim was to make a “run/stop” button completely unresponsive whilst in the “stopping” state (ie waiting for some code to reach a termination point.

Despite disabling click (mouse) handling use both element.disabled = true AND element.removeEventListener , i find that whilst the code is running with the click event supposedly disabled the browser still collects clicks and will fire events after the wait code ends and the even listener is re-enabled.

Example code :

<!doctype html>
    <html>
        <head>
        <script type="text/javascript" src="js.js"></script>
        </head>

        <body onload="init();">
        <button type="button" id="runstatus">Play</button>
    </body>
    </html>
    var runstatus="stopped";//values 'stopped' , 'running', 'stopping'

    function init() {
    UIupdate();
    }

    //toggle button display text
    function UIupdate(){
    var t = document.getElementById("runstatus");

    if ( runstatus == "stopped") {
        t.innerText = "Run";
        t.addEventListener("click",stopstart);
        t.disabled = false;
    } else
    if ( runstatus == "stopping") {
        t.innerText = "stopping..";
//      t.removeEventListener("click",stopstart,);
        t.removeEventListener("click",stopstart,true);
        t.disabled = true;
    } else
    if ( runstatus == "running") {
        t.innerText = "Stop";
    } 
}       

    function stopstart(){
    var f,f2;

    if (runstatus=="stopped"){
        runstatus="running";
        UIupdate();
    } else
    if (runstatus=="running"){
        document.getElementById("runstatus").removeEventListener("click",stopstart);
        
        f = function(){
            runstatus="stopping";
            UIupdate();
            window.requestAnimationFrame(f2);
        }
        
        f2=function(){
            wait();
            runstatus="stopped";
            UIupdate();
        }
    
        window.requestAnimationFrame(f);
    } else
    if (runstatus=="stopping"){
        //nothing to do 
    } 
}

    function wait(){
    var i,j=0;
    for (i=0;i<1e10;i++){
        if (i%1e9 ==0){
            j++;
            console.log("waiting to stop",j,"of 10");
        }
    }
    console.log("finished");
    return;
}

.. whilst the code is in the ‘wait’ function I find that clicking on the button will still stack click responses that are acted on when the wait code terminates. I want these clicks to be completely ignored

Video Source Blob

I want to blob url of another website link.
this code working only to my video file not another website video file.

let mainVideoSources = mainVideo.querySelectorAll("source");
  for (let i = 0; i < mainVideoSources.length; i++) {
    let videoUrl = mainVideoSources[i].src;
    blobUrl(mainVideoSources[i], videoUrl);
  }
  function blobUrl(video, videoUrl) {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", videoUrl);
    xhr.responseType = "arraybuffer";
    xhr.onload = (e) => {
      let blob = new Blob([xhr.response]);
      let url = URL.createObjectURL(blob);
      video.src = url;
    };
    xhr.send();
  }

Is it posible for a React function to keep calling itself until state value changes?

I’m trying to replicate on React a metronome built with Vue. Basically the play function keeps calling itself while playing is true. The problem I have is that the state being async on React won’t update while the function is running. Here is the Vue code:

data() {
    return {
      playing: false,
      audioContext: null,
      audioBuffer: null,
      currentTime: null
    }
},
mounted() {
    this.initContext();
},
methods: {
    toggle()
      if (!this.playing) {
        this.currentTime = this.audioContext.currentTime;
        this.playing = true;
        this.play();
      } else {
        this.playing = false;
      }
    },
    play() {
      this.currentTime += 60 / this.$store.state.tempo;
      const source = this.audioContext.createBufferSource();
      source.buffer = this.audioBuffer;
      source.connect(this.audioContext.destination);
      source.onended = this.playing ? this.play : "";
      source.start(this.currentTime);
    },
    async initContext() {
      this.audioContext = new AudioContext();
      this.audioBuffer = await fetch("click.wav")
        .then(res => res.arrayBuffer())
        .then(arrayBuffer => 
          this.audioContext.decodeAudioData(arrayBuffer)
        )
    }
}

I guess the solution should be on useEffect but I could not manage to recreate it. Any suggestion is appreciated!

Is there a way to set new route on NextJS using useRouter

I am building a NextJS app and I trying to set a new route using next/router.
When I am on the route

/auth/complete_profile

I would like to move to the route

/account

I try doing it like so:

      if(userData?.id != undefined){
         router.push('/account')
      }

But this quickly pushes to account route and goes back to the previous route.

please help.

socket io client changes the url

Im trying to connect socket io client to my server using https://cdn.socket.io/4.5.4/socket.io.min.js

My problem is the URL to my server is not correct as it changes the url when connecting to the socket

the url im trying to use http://x.example.com but the actual url is being https://x.example.com/socket.io/?EIO=4&transport=polling&t=OMJ94Ct

how the url got changed from http to https ? and how it appends the rest of the url ?

i followed this guide https://socket.io/get-started/chat

and here is what i did var socket = io.connect("http://x.example.com:9457");

How to get current selection on dropdown (bootstrap 5.3) with vanilla javascript

How can I grab the selected content from each menu ?

I have unordered list with two dropdown menus which I fill them with data from api.

             <ul class="navbar-nav me-auto mb-2 mb-lg-0" >
                <li class="nav-item dropdown" >
                    <a class="nav-link dropdown-toggle" id="clicked"  href="#" role="button" data-bs-toggle="dropdown"
                        aria-expanded="false">
                        Име на станция:
                    </a>
                    <ul class="dropdown-menu" id="clickedNames">
                       
                    </ul>
                </li>

                <li class="nav-item dropdown">
                    <a class="nav-link dropdown-toggle" id="clicked2" href="#" role="button" data-bs-toggle="dropdown"
                        aria-expanded="false">
                        Начална дата:
                    </a>
                    <ul class="dropdown-menu" id="clickedDates">
                       
                    </ul>
                </li>
            </ul>

This is my api.js code with free api end point:

//Create 3 objects for parameters on api query
const dataAPI = {nameStation:'', dataStation:'', dataHours:''}

const url = 'https://raddythebrand.github.io/apex-legends/data.json';

const btn = document.querySelector('#clicked');

btn.addEventListener('click', random);

let ulNames = document.getElementById('clickedNames');
let ulDates = document.getElementById('clickedDates');


function random(e) {
  getData();
}

// Create Asynchronous function to grab the data for filling dropdown
async function getData() {
  try {
    // We are using fetch to get the response
    const response = await fetch(url);
    const data = await response.json();
    
    // Trigger the listData function and pass the result
    listDataNames(data);
    listDataDates(data);
  } catch (error) {
    console.log(error);
  }
}

const list = document.createDocumentFragment();

// Create a function that will insert the data into our legends UL in dropdown
function listDataNames(data) {
  // Loop through each result and append the data.
  data.map(function (clickedNames) {
    const fillNames = `
    <li><a class="dropdown-item" href="#">${clickedNames.name}</a></li>
    `;
    const item = document.createElement('li');
    item.innerHTML = fillNames;
    list.appendChild(item);
  });
  // Finally append all the data to the UL.
  ulNames.appendChild(list);
}

// Create a function that will insert the data into our legends UL in dropdown
function listDataDates(data) {
  // Loop through each result and append the data.
  data.map(function (clickedDates) {
    const fillDates = `
    <li><a class="dropdown-item" href="#">${clickedDates.age}</a></li>
    `;
    const item = document.createElement('li');
    item.innerHTML = fillDates;
    list.appendChild(item);
  });
  // Finally append all the data to the UL.
  ulDates.appendChild(list);
}

I need a function where I will pass these two parameters from the selected content to api ?
Is there a way to do it in a separate function in which I will take the response from another api ?

How can I make the pattern execute one after the other rather than all at once?

I am making a sort of game where you repeat the pattern that’s randomly generated. everything works and I made it show the last button of the pattern to the user but if I want to show the full pattern I cant seem to do it.

I have tried delays but it makes a delay and plays the button pattern all at once. then I tried to make it an increasing delay but it still waits, and then plays all at once.

I made the delays with setTimeout but not sure how to make the array of pattern play out one after another rather than all at once.

let i=0;
function nextSeq () {rndNum = Math.floor(Math.random()*6);
let chosenButton = buttons[rndNum];
pattern.push(chosenButton); console.log(pattern);

for (i=0; i<pattern.length; i++) {

switch (pattern[i]) {
case "fst": setTimeout(() => {
$("img.bti1").attr("src", "images/i1.png").addClass("smimg"); delay=1200;trigger="img.bti1";reverse(trigger)
d1.play()
}, 500);

break; case "snd": setTimeout(() => {

$("img.bti2").attr("src", "images/i2.png"); $("img.bti2").addClass("smimg"); delay=500;trigger="img.bti2";reverse(trigger)
d2.play()
}, 500);

break; case "trd": setTimeout(() => {

$("img.bti3").attr("src", "images/i3.png").addClass("smimg"); delay=1700;trigger="img.bti3";reverse(trigger)
d3.play()
}, 500);

break; case "fth": setTimeout(() => {

$("img.bti4").attr("src", "images/i4.png").addClass("smimg"); delay=1300;trigger="img.bti4";reverse(trigger)
d4.play()
}, 500);

break; case "pth": setTimeout(() => {
$("img.bti5").attr("src", "images/i5.png").addClass("smimg"); delay=1400;trigger="img.bti5";reverse(trigger)
d5.play()
}, 500);
break; case "sth": setTimeout(() => {

$("img.bti6").attr("src", "images/i6.png").addClass("smimg"); delay=1800;trigger="img.bti6";reverse(trigger)
d6.play()
}, 500);

break;

default:
}

}
}

How to retrieve a value from a variable outside of a condition?

I’m learning JS, but I don’t know if it’s possible to do what I want to achieve.

I have a variable named btcVariationTotal which is in a condition, and I want to retrieve the value of this variable in another variable called tmp, but this variable is not included in the condition.

My problem is that tmp always shows me 0. I don’t understand why? And how can I solve this problem, please?

enter image description here

I really want to retrieve the value outside the condition.

console.clear();

let wsBtc = new WebSocket('wss://stream.binance.com:9443/ws/btcusdt@trade');

let btcStockPriceElement1 = document.getElementById('btcValue1');
let btcStockPriceElement2 = document.getElementById('btcValue2');


let btcLastPrice = null;
let btcStockObject = null;

wsBtc.onmessage = (event) => {
  btcStockObject = JSON.parse(event.data);
};

let btc1 = 0, btc2 = 0;
let btcVariation_1_2 = 0;
let btcVariationTotal = 0; 

let tmp = 0; 



let btcRunTimers = setInterval(() => {
  let minutes = new Date().getMinutes();
 if (minutes === 51) {
    let val1 = parseFloat(btcStockObject.p).toFixed(1);
    let price = parseFloat(btcStockObject.p).toFixed(1);

    btcStockPriceElement1.innerText = price;
    btcStockPriceElement1.style.color =
      !btcLastPrice || btcLastPrice === price
        ? 'black'
        : price > btcLastPrice
        ? '#AAFF00'
        : 'red';

    btcLastPrice = price;
    btcStockObject = null;

    btc1 = val1;

  }

if (minutes === 52) {
    let val2 = parseFloat(btcStockObject.p).toFixed(1);
    let price = parseFloat(btcStockObject.p).toFixed(1);

    btcStockPriceElement2.innerText = price;
    btcStockPriceElement2.style.color =
      !btcLastPrice || btcLastPrice === price
        ? 'black'
        : price > btcLastPrice
        ? '#AAFF00'
        : 'red';

    btcLastPrice = price;
    btcStockObject = null;

    btc2 = val2;

    btcVariation_1_2 = ( (parseFloat(btc2) - parseFloat(btc1)) / btc1 * 100);

    document.getElementById("btcResult1").innerHTML = btcVariation_1_2.toFixed(2);
    
  }

  btcVariationTotal = (parseFloat(btcVariation_1_2));
  console.log("btc variation => " + btcVariationTotal);
  document.getElementById("result").innerHTML = btcVariationTotal.toFixed(2);
  tmp = btcVariationTotal;


}, 60000);


console.log("tmp => " +  tmp); 

Convert string to array in javsacript

i have a string containg an array. i can convert it using loop over string with different conditions but that will be slow. so is there any direct way to convert string which has array in it to an actuall array?
my javascript string looks like this

arr_str = '["value1", "value2", "value3"]'

i want to convert it in array something like this

arr = ["value1", "value2", "value3"]

What does this for loop syntax mean?

I recently came to this thread, and had a quick question on the syntax used in the first answer. @ggorlen used this syntax/notation in the for loop that I’ve never seen before and couldn’t find any answers online:

  for (;;) {
    try {
      await page.waitForFunction(
        `${thumbs.length} !==
          document.querySelectorAll("#video-title").length`, 
        {timeout: 10000}
      );
    }
    catch (err) {
      break;
    }

    thumbs = await page.$$eval("#video-title", els => {
      els.at(-1).scrollIntoView();
      return els.map(e => e.getAttribute("title"));
    });
  }

What does the for(;;) {…} do?

Thanks!

I just have a question on the syntax used, and couldn’t find an answer.

SourceBuffer’s appendBuffer() not appending arrayBuffer

Context:

1.) Confirmed that the backend is returning a range of bytes using StreamingResponseBody (I’m using spring boot) via 206 response code

2.) Confirmed that the received data makes sense, I think, by comparing the logs displayed here chrome://media-internals/ with the logs displayed when I play any YouTube video. I attached some pictures to show this.enter image description hereenter image description here

3.) On the frontend, byte stream gets converted into an arrayBuffer via response.arrayBuffer()

4.) Confirmed that the video’s codec profile is video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41" . Used mp4box (https://github.com/gpac/mp4box.js) to get the codec and profile and confirmed that the browser supports this MediaSource.isTypeSupported('video/mp4; codecs="avc1.64002a"; profiles="mp42,mp41"'); I’m using google chrome to test this.

Issue:

1.) It looks like buffered isn’t getting updated, because it’s TimeRange length is not changing and that sourceBuffer.buffered.end(0) and sourceBuffer.buffered.start(0) remains undefined

2.) And because of the previous issue, <video /> doesn’t play.

Using a callback getVideoStreamResourceAPI to receive the arrayBuffer, the following is my code

getVideoStreamResourceAPI(pathVariables, identityPayload, resp => {
                    const mediaSource = new MediaSource();
                    videoRef.current.src = URL.createObjectURL(mediaSource);
                    mediaSource.addEventListener('sourceopen', sourceOpen, {once: true});
    
                    function sourceOpen() {
                        URL.revokeObjectURL(videoRef.current.src);
                        var sourceBuffer = mediaSource.addSourceBuffer('video/mp4; codecs="avc1.64002a,mp4a.40.2"; profiles="mp42,mp41"');

                        sourceBuffer.addEventListener('update', sourceBufferUpdate, { once: true });
                        sourceBuffer.appendBuffer(resp);
                        sourceBuffer.addEventListener('updateend', updateEnd, { once: true });
                    }
    
                    function sourceBufferUpdate(e) {
                        console.log("updated: ", e);
                    }
    
                    function updateEnd(e) {
                        console.log("updatedEnded: ", e);
                        console.log("buffered: ", videoRef.current.buffered);
                        videoRef.current.addEventListener('playing', fetchNextSegment, { once: true });
                    }

                    function fetchNextSegment() {
                        console.log("fetching next segment");
                    }
    
                    setSpinner(null);
                });

NOTE:
resp contains the arrayBuffer and fetchNextSegment() isn’t getting called.

Any suggestions, ideas, and help would be greatly appreciated. Thanks for taking the time to read this.

JavaScript – Can’t assign value to variables from object

Not sure what I’m doing wrong here. I am a beginner.

What I want it to do is to give the result 0.5

If you change var y to equal a number (3.5) it works but I want to grab the number of eggs and just return the decimal.

const chickens = [
  {
    name: "Mac Chicken",
    eggs: 3.5
  }
];

var y = chickens.eggs;
int_part = Math.trunc(y);
remainder = (y - int_part);
partialDec = remainder.toFixed(1);

console.log(partialDec);

Shows up ‘NAN’ instead of a number