JS Scripts malfunctionning in Laravel 9

I am a newbie developer to Laravel and lately, I bought a template for an Admin Panel, it usually functions really well before integrating it into my Back-end system, but the ApexCharts on the dashboard seem to load a chart twice instead of packing only one chart at each div with its specific id, and the data tables plugin as well is loading two paginations for one table instead of only one, I’ve read about Laravel Mix but didn’t know if it could be the way to fix the issue since I have lots of js files inside the public/js folder.

Any help is appreciated, thank you!

about a changeTab function

I’m a French beginner of html code and I have a question. I want to make tabs on my website but the js code + html code don’t work. So can you help me ? I will write the script :

function changeTab(evt, target) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementById("tabcontent");
    for (i = 0; i < tabcontent; i++) {
        tabcontent[i].style.display = "none";
    }
    tablinks = document.getElementById("tablinks");
    for (i = 0; i < tablinks; i++) {
        tablinks[i].className = tablinks[i].replace(" active", "");
    }
    document.getElementById(target).style.display = "block";
    evt.currentTarget.className += " active";
}
<div class="tab">
    <button class="tablinks active" onclick="changeTab(event, 'series')">Séries</button>
    <button class="tablinks" onclick="changeTab(event, 'animes')">Animés</button>
<div style="display: none" class="animes tabcontent">

I don’t write the entire code but if you need more informations, I will post them.
Thanks !

I want to create 3 tabs on my website, but I don’t understand how to do that.

I have some problems with recursion in dom when I try to create a list. Javascript

I am a beginner. In this task you have to create a function (‘createTree’) that will add DOM to the website. It should create nested lists using html tags ‘ul’ and ‘li’.
function createTree(container, data): container – the container in html where we should add these lists, data – the object ‘key – obj’. enter image description here. enter image description here.

If I delete the second ‘if’ section it will work, but also will show “[Object object]” as the first li. Can you help me please?

That is my code
'use strict'


let data = {
  "Рыбы": {
    "форель": {},
    "лосось": {}
  },
  "Деревья": {
    "Огромные": {
      "секвойя": {},
      "дуб": {}
    },
    "Цветковые": {
      "яблоня": {},
      "магнолия": {}
    }
  }
};


let container = document.body.querySelector('ul')
container.newData = data;


function createTree(container, data) {
    let li = document.createElement('li');
    if (!Object.keys(container.newData).length) {
        li.append(document.createTextNode(data));
        container.append(li);
        return
    }

    let ul = document.createElement('ul');
    if (typeof data != 'object') {
        ul.append(document.createTextNode(data));
        li.append(ul);
        container.append(li);
    } 

    for (let i in container.newData) {

        ul.newData = container.newData[i];
        createTree(ul, i);

    }
}


createTree(container, data); // создаёт дерево в контейнере

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="css/style.css">
        <title>Операторы в JavaScript</title>
    </head>
    <body>
<!--        <h1 stand="true">Операторы в <span class="yellow">JavaScript</span>.</h1>
        <a name="list">the list</a>
        <h3>Урок №5</h3>
 -->

        <ul class='container'>
            
        </ul>


        
        <script src="js/script.js"></script>
    </body>
</html>

Start/Stop background scripts chrome extension

    window.open(".....")
    chrome.cookies.getAll({domain: "......"}, function(cookies) {
                for(var i=0; i<cookies.length;i++) {
                    chrome.cookies.remove({url: "......", name: "STX_SESSION"});
                }})

            chrome.tabs.reload()
            window.open(".....")

    const interval = setInterval(function() {
            chrome.cookies.getAll({domain: "....."}, function(cookies) {
                for(var i=0; i<cookies.length;i++) {
                    chrome.cookies.remove({url: ".....", name: "STX_SESSION"});
                }})

            chrome.tabs.reload()
            window.open("......")
    }, 1200000);
})

manifest.json

{
  "name" : "....",
  "version" : "1.0",
  "description" : "....",
  "permissions": [ "cookies", "tabs", "<all_urls>" , "http://*/", "https://*/"],
  "icons": { "16": "....", "48": ".....", "128": "...." },
  "browser_action": {
    "default_icon": "....."
  },
  "background": {
    "scripts": ["script.js"]
  },
  "manifest_version": 2
}

This is my code. I would like to reset the interval or in other word stop the background script from running. Is it possible to do this by clicking on the extension icon?

Why am I getting undefined on for loop? [closed]

You get an array of numbers, return the sum of all of the positives ones.

Example [1,-4,7,12] => 1 + 7 + 12 = 20

Note: if there is nothing to sum, the sum is default to 0.

I did this ….

function positiveSum(arr) {
for(let i = 0 ; i <= arr.length - 1 ; i++){
  console.log(arr[i])
}
}
console.log(positiveSum([-1, 2, 3, 4,-5]))

####################—RESULT FROM CONSOLE—- ############################

-1,2,3,4,-5,undefined

Why am I getting undefined ???

####################—RESULT FROM CONSOLE—- ############################

Why is my socket.io not defined? (ready is not working)

I’m currently working on socket.io where I’m trying to build a chatapplication. But it seems that my socket.io is not working or even running. The ready(function () {… is not working. Is there a smart and easy to solve this problem?

I have tried to move a bit around with the parentheses, but without any luck.

$(document).ready(function(){
    var socket = io.connect('http://localhost:3000');
    var username = prompt("What is your name?");
    socket.emit('join', username);

    // Listens for form submission
    $("#chatForm").on('submit', function(e){
      e.preventDefault();
      var message = $("#message").val();
      socket.emit('new_message', message)
      $("#message").val("");
    })
  
    // adds HTML message to chat
    const addMessageToChat = (message) => {
      const messageElement = document.createElement('li');
      // Opgave 2 ...
  
      messageElement.innerText = new Date(message.timestamp).toLocaleTimeString('DK') 
        + ': ' + message.username 
        + ": " + message.message + " - "
  
      $("#messagesContainer").append(messageElement);
    }
  
    // On receiving one message: {username: '...', message: '...'}
    socket.on('new_message', function(message){
      console.log('message: ', message)
      addMessageToChat(message);
    })

  
    // on receiving a list of messages
    socket.on('messages', function(messages) {
      console.log('messages: ', messages)
      messages.forEach(message => {
        addMessageToChat(message);
      })
    })
  
    // On person joined chat
    socket.on('addChatter', function(name){
      var $chatter = $("<li>", {
        text: name,
        attr: {
          'data-name':name
        }
      })
      $("#chatters").append($chatter)
    })
  
    // On person disconnect
    socket.on("removeChatter", function(name){
      $("#chatters li[data-name=" + name +"]").remove()
    })
  })

get whole page css with styles

I want to build something like this but I have problem with building iframes.

when I pass them html via srcdoc= that also needs styling, so I am able to pass my CDN link but that is not good solution, because it fetches that link in every render new iframe.

I wanted to get all CSS classes with all style rules to pass it in <style></style> but it still looks ugly. What do I need?

HTML markup

<div class="relative z-10" aria-labelledby="modal-title" role="dialog" aria-modal="true">
  <div class="fixed inset-0 bg-gray-200 opacity-75"></div>
  <div class="fixed inset-0 z-10 overflow-y-auto">
    <div class="flex items-center justify-center h-full w-full">
      <div class="bg-white p-5 px-10 rounded-[1rem] max-w-xs">
        <div class="text-center">
          <h5 class="font-bold text-xl my-2 text-gray-700">
            Exit
          </h5>
          <p class="text-sm font-normal text-gray-500">
            Click the "confirm" button to close the window without saving
          </p>
        </div>
        <div class="grid grid-cols-2 gap-2 text-center mt-3">
          <div class="col-span-1">
            <button class="w-full p-2 bg-gray-100 font-bold text-sm rounded-md text-gray-400">Cancel</button>
          </div>
          <div class="col-span-1">
            <button class="w-full p-2 bg-blue-600 font-bold text-sm rounded-md text-gray-100">Confirm</button>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>

JS Methods

Get style rules from css class

function getStyle(className) {
    var cssText = "";
    var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
    for (var x = 0; x < classes.length; x++) {        
        if (classes[x].selectorText == className) {
            cssText += classes[x].cssText || classes[x].style.cssText;
        }         
    }
    return cssText;
}

Get All class that is used on page

[].concat(...[...document.querySelectorAll('*')].map(e=>[...e.classList])).filter((d,i,a)=>a.indexOf(d)==i).sort().map(i=> getStyle('.'+i)).join(' ');

Pdfjs cant extract language other than English properly

I’m trying to extract texts and images from some pdf files of bengali language with same structure using pdf.js. But the problem is pdf.js can’t output bengali properly.
Most of the characters are shown as black square with question mark inside.
Also the signs used as vowels in bengali aren’t positioned properly.
For example [মোঃ রাজু মিয়া] outputs as [ �মাঃ রাজু িময়া]. As I’m extracting images and that part is working properly. It would be nice if i can also do the text part in pdf.js with custom font or something.

My sample code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.9.359/pdf.worker.min.js"></script>

 <input type="file" id="file-pdf" accept=".pdf">

<script>

const onLoadFile = async event => {

  try {

    // turn array buffer into typed array

    const typedArray = new Uint8Array(event.target.result);

    const loadingPdfDocument = pdfjsLib.getDocument(typedArray);

    const pdfDocumentInstance = await loadingPdfDocument.promise;

    const totalNumPages = pdfDocumentInstance.numPages;

    

    let pn = 1

    

    

let page = await pdfDocumentInstance.getPage(pn)

let textContent = await page.getTextContent()

                var textItems = textContent.items;

console.log(textItems)

 

  } catch (error) {

    console.log(error);

  }

};

document.getElementById('file-pdf').addEventListener('change', event => {

  const file = event.target.files[0];

  if (file.type !== 'application/pdf') {

    alert(`File ${file.name} is not a PDF file type`);

    return;

  }

  const fileReader = new FileReader();

  fileReader.onload = onLoadFile;

  fileReader.readAsArrayBuffer(file);

});

</script>

How do we get user input in java script console

In Python I used input function to get user input but in javascript I am trying to use prompt()
which I seen in goolgle search but it is not working. I am using visual studio code editor.
the code is something like that,

let name = prompt('what is your name')
console.log(name + 'is your name')

Why doesn’t my state update in a way that seems sense?

I want to add 1 to countMoves any time this setState happens. But why doesn’t this code work?

    const initialState = {
        show: {isShow: false, indexes: [], winnerId: []},
        countMoves: 0,
        stars: [1, 1, 1],
        time: {minute: 0, second: 0}
    }
    const [state, setState] = useState(initialState);
    const handleClick = (index) => {
        if(state.show.indexes.length === 1){
            setState({...state, countMoves: state.countMoves + 1})
        }
.
.
.

However, when I change setState to this:

setState({...state, countMoves: state.countMoves++ })

or

setState({...state, countMoves: state.countMoves += 1 })

This works! I think the first code is correct.

How to send an array as a JSON string in postman body?

I’m trying to send some body data in my api call using postman.
(I’m using the “raw” body option)

My data in the body is like so:

{
 "products" : [{"id": 1, "quantity" : 2, "comments": "none"}]
}

Problem is, when I send the json body data containing an array, i get an error saying

The Products must be a valid JSON string

I have set my headers to content-type: application/json, but nothing is working,
am I missing something?

Trigger event when user highlights text

I’m trying to figure out a problem that I recently saw on an e-shop website.

When a user highlights the name of a product, it pops up a little window asking about customer satisfaction and s on, like this:

enter image description here

Is there a way to use a pseudo class line :active or :focus to enable this?

Or is there perhaps a custom solution using javascript event listener?