JavaScript stop to work after refreshing the page

I wrote few Java Scripts, mostly for change of text color, depends of value. It is implements in JSF application. Example below:

$(document).ready(function(){
    
    var allCells = $(".kolorStatus > div");
    
    $.each(allCells, function (index, child) { 
        
        switch(child.textContent){
            
            case "Produkcja": $(child).parent().css("color", "green");
            break;
            
            case "Brak zleceń": $(child).parent().css("color", "black");
            break;
            
            case "Brak zlecen": $(child).parent().css("color", "black");
            break;
            
            case "Tech. red. prędkości": $(child).parent().css("color", "orange");
            break;
            
            default: $(child).parent().css("color", "red");
        }
    }); 
});

Script works correct until I refresh from JSF Bean with ajax:

PrimeFaces instance = PrimeFaces.current();
instance.ajax().update("form:gridPanel");

In result there is lack of any colors.

Geogebra with JavaScript or Python

I want to use GeoGebra programmatically, i.e. define in code what I want to draw. For example, let’s suppose I want to build the following construction purely in code:

  • defining a point p in (0,0)
  • defining an integer slider s in the range(5, 10)
  • creating a Circle c centered in p and radius s
  • finding the positive intersect (p_i0) between c and xAxis
  • compute the list of p_i obtained after rotating p_i1 around p_i0 by a list of given angles (loop)

I have seen that there’s python geogebra that has a python interface and builds the objects exactly the way I want. However, I haven’t been able to find any documentation to the best of my efforts, only resorting to do dir(ggb) as instructed by someone in Reddit (r/pyggb). As suboptimal as this is, this could work if I could find all instructions I can find in the classic view of GeoGebra.

I have also seen that there’s a Javascript API which looks at least documented, but from what I have seen, you have to create the HTML from scratch, which seems to be cumbersome.

My question is: is there any way of programmatically building everything you can build with the Classic View in an interface in which I write code and it builds objects? (similar to the python version linked above)

Deal-breakers:

  • It must be a programmatic interface
  • Code must build objects as run (no building HTML by hand)

Bonus points (no deal breakers, nice to have):

  • I would prefer python over javascript
  • Online version over offline installation

Is my wishlist possible?

Object Inheritance: Property assignment not working

I am learning OOP with JavaScript based on MDN.

I created class Shape and Square.

    class Shape {
      name;
      sides;
      sideLength;

      constructor(name, sides, sideLength) {
        this.name = name;
        this.sides = sides;
        this.sideLength = sideLength;
      }

      calcPerimeter() {
        const result = this.sides * this.sideLength;

        console.log(`Perimeter is ${result}`)
      }
    }

    class Square extends Shape {

      constructor(sideLength) {
        super(sideLength);
        this.name = 'square';
        this.sides = 4;
        // this.sideLength = sideLength;
      }
    }

I expect class Square to inherit from Shape for property sideLength. I try to create new object with new Square(5) and it produces an object Square {name: 'square', sides: 4, sideLength: undefined}. I create the class Square by automatically assign value 4 to sides and square to name.

Appreciate your advice why the value of sideLength is undefined.

Using JavaScript Excel file Header is not highlighted

I have code for two table I export both table in excel file its working fine but i want to show table header highlighted like Yellow or green color but its not working. I do not understand what is the issue.

please see the output image

enter image description here

but I want to this type of output like header highlighted

enter image description here

<!DOCTYPE html>
<html>
<head>
    <title>Export Tables to Excel</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.16.2/xlsx.full.min.js"></script>
</head>
<body>
    <div class="first-report">
        <h4>AVP Report</h4>
        <table id="AVPTable">
            <thead id="AVPHeaderName">
                <tr>
                    <th>Header 1</th>
                    <th>Header 2</th>
                </tr>
            </thead>
            <tbody id="masterTableBody">
                <tr>
                    <td>Data 1</td>
                    <td>Data 2</td>
                </tr>
            </tbody>
        </table>
    </div>
    <div class="second-report">
        <h4>DO Red roll-off Graph</h4>
        <table id="DORedTable">
            <thead id="DORedProjectHeader">
                <tr>
                    <th>Header A</th>
                    <th>Header B</th>
                </tr>
            </thead>
            <tbody id="DORedProjectBody">
                <tr>
                    <td>Data A</td>
                    <td>Data B</td>
                </tr>
            </tbody>
        </table>
    </div>

    <button type="submit" id="excelAVPDOBtn" onclick="DownloadRYProjectReport();" class="btn btn-submit btn-clear-get-all">Export to Excel</button>

    <script>
        function DownloadRYProjectReport() {
            var avpTable = document.getElementById('AVPTable');
            var doRedTable = document.getElementById('DORedTable');

            if (!avpTable || !doRedTable) {
                alert('One or both tables are missing!');
                return;
            }

            var wb = XLSX.utils.book_new();

            var ws1 = XLSX.utils.table_to_sheet(avpTable);
            XLSX.utils.book_append_sheet(wb, ws1, "AVP Report");

            XLSX.utils.sheet_add_aoa(ws1, [[''], ['']], {origin: -1});

            var ws2 = XLSX.utils.table_to_sheet(doRedTable);
            XLSX.utils.sheet_add_json(ws1, XLSX.utils.sheet_to_json(ws2, {header: 1}), {skipHeader: true, origin: -1});

            var range1 = XLSX.utils.decode_range(ws1['!ref']);
            for (var C = range1.s.c; C <= range1.e.c; ++C) {
                var cell = ws1[XLSX.utils.encode_cell({r: 0, c: C})];
                if (cell) {
                    if (!cell.s) cell.s = {};
                    cell.s.fill = {fgColor: {rgb: "FFFF00"}};
                }
            }

            var range2 = XLSX.utils.decode_range(ws2['!ref']);
            for (var C = range2.s.c; C <= range2.e.c; ++C) {
                var cell = ws1[XLSX.utils.encode_cell({r: range1.e.r + 3, c: C})]; 
                if (cell) {
                    if (!cell.s) cell.s = {};
                    cell.s.fill = {fgColor: {rgb: "FFFF00"}};
                }
            }

            XLSX.writeFile(wb, 'Report.xlsx');
        }
    </script>
</body>
</html>

Here is my code both table export is working but header highlight is not working.
if anyone know how to fix this give a valuable response.
Thank you in advance.

How to get multiple promises before running a final function or code in Javascript?

I’m new to Javascript promises and I’m trying to hit two API endpoints before running some Javascript. My expectation was that the console output would be:

GET ConfigData Now... 
hello 
GET Resales Now... 
world
Finished here too...
Finished

Instead the Finished console log appears to never reached nor is the "Finished here too..." from the allDone() function.

function getConfigData() {
  console.log('GET ConfigData Now...');
  return new Promise((resolve) => {
    console.log("hello");
  });
}

function getResales() {
  console.log('GET Resales Now...');
  return new Promise((resolve) => {
    console.log("world");
  });
}

function allDone() {
  console.log('allDone Now...');
  return new Promise((resolve) => {
    console.log("Finished");
  });
}

async function getData() {
  await Promise.allSettled([getConfigData(), getResales()]);
  console.log(config);
  console.log(fullResales);
  await Promise.allSettled([allDone()]);
  console.log('Finished here too..');
}

getData()

Alternative to new RegExp in javascript to resolve ReDos

is it possible to write same function without using new RegExp as it is give ReDos vulnerability

function extractNum(dataList) {
    let resp = []
    dataList.forEach((i) => {
        let regex = new RegExp(`ab:${name}:${place}(::(.[0-9]*))?`)
        let dlist = {
            version: i.filter(j => j.match(regex)).map(j => {
                let verNo = j.replace(new RegExp(`ab::${name}:ds:${place}(::)?`), '');
                return { versionNo: verNo }
            })
        }
        if (dlist.version.length) {
            resp.push(dlsit)
        }
    })
    return resp
}

SAPUI5 – Webclient-Deployment of an Extension – sap.insights missing

I am currently working with SAPUI5 and have developed a application, which should be deployed to the SAP Business One WebClient. I tested my application thoroughly during development and it functions as expected.

However, deployment seems to be quite the issue. Firstly, I have used the following command to build my project:
ui5 build --config=ui5.yaml --clean-dest --dest dist

The file “ui5.yaml” contains the following content:

specVersion: "3.1"
metadata:
  name: myApp
type: application
framework:
  name: SAPUI5
  version: 1.123.2
  libraries:
    - name: sap.m
    - name: sap.ui.core
    - name: sap.f
    - name: sap.suite.ui.generic.template
    - name: sap.ui.comp
    - name: sap.ui.generic.app
    - name: sap.ui.table
    - name: sap.ushell
    - name: themelib_sap_horizon
    - name: sap.insights
server:
  customMiddleware:
    - name: fiori-tools-proxy
      afterMiddleware: compression
      configuration:
        ignoreCertError: true
        ui5:
          path:
            - /resources
            - /test-resources
          url: https://ui5.sap.com
        backend:
          - path: /b1s
            url: https://x.x.x.x:x
    - name: fiori-tools-appreload
      afterMiddleware: compression
      configuration:
        port: x
        path: webapp
        delay: 300
    - name: ui5-tooling-transpile-middleware
      afterMiddleware: compression
      configuration:
        debug: true
        excludePatterns:
          - /Component-preload.js
    - name: fiori-tools-preview
      afterMiddleware: fiori-tools-appreload
      configuration:
        component: myApp
        ui5Theme: sap_horizon
builder:
  customTasks:
    - name: ui5-tooling-transpile-task
      afterTask: replaceVersion
      configuration:
        debug: true

I have used the VS Code Plugin outlined in this chapter of the docs to package my application build into an MTAR.

During this entire process, I didn’t encounter a single error. But when I finally import my WebClient-Extension via the ExtensionManager (and assign it to a CompanyDB) and attempt to open it in the WebClient, I get this error:

WebClient Error message

Expected: The WebClient-Extension functions in the WebClient as it did during development.
Actual result: I get an error (in my browser console), which says, that sap.insights cannot be found. The WebClient displays the following error message: Failed to load UI5 component for navigation intent “#webclient-myApp-myApp”.

What I have tried so far:

  • Using a self-contained build.
  • Downgrading the SAPUI5 version to 1.120.4.
  • Manually including the dependency in the UI5 build using –include-dependency sap.insights

I have already checked the modules available on my WebClient and sap.insights isn’t amongst them. How can I add this module to my WebClient and/or fix this error? I am using FP 2405.

Thanks in advance

querySelector dows not work on event.target

I have onClick function but I can not access to its childeren elements from event

<div className="sortingBy" onClick={openSoring}>
<div className="checkBox" ></div>
</div>

my function

const openFilter=(e)=>{
        e.target.querySelector('.checkBox').classList.toggle('active')
    }

these codes are in react .

after using that code it get this error

e.target.querySelector(...) is null

how can I access to children elements from event variable in onClick propertie

ASP.Net Core MVC – Deleting table rows in view is not received properly in POST action method when form submits

I have a table in ASP.Net Core MVC Project. It is bound to a ModelList object MandateCheckDetailsList in my ViewModel. I have a Delete button in each row which is used to delete the particular row. Once the user is satisfied with his added rows, He then submits the form using Next button which calls the POST action method.

The issue is, if there are 5 rows in the table and user deletes the 3rd row, In UI the row is deleted and 4 rows are displayed. But when user submits the form using Next button, the POST action method receives only the 1st and 2nd row details. The 4th and 5th row details are missing. I feel re-indexing of rows is a problem. I am stuck with this issue figuring out and will be grateful for any help.

VIEW CODE:

<div id="mandateCheckDetailsContainer">
<div class="container-fluid">
    <div class="row">
    @{
        int checkNum = 0;
    }
    <div class="table-responsive">
            @{
                var checkCount = 0;
            }
        <table id="checkTable" class="myTable table table-striped table-bordered mainGridTable dataTable no-footer dtr-inline">

            <tr>
                <th>Package</th>
                <th>Country</th>
                <th>Check Name</th>
                <th>Mandate/Non-Mandate</th>
                <th>Country Type</th>
                <th>Action</th>
            </tr>
            
            @for (checkNum = 0; checkNum < Model.MandateCheckDetailsList.Count; checkNum++)
            {
                <tr>
                    @{
                        checkCount = checkNum + 1;
                    }
                    <td>
                        <input type="hidden" asp-for="MandateCheckDetailsList[checkNum].Id" />
                        <input type="hidden" asp-for="MandateCheckDetailsList[checkNum].ClientId" />
                        <select asp-for="MandateCheckDetailsList[checkNum].PackageId" asp-items="@(new SelectList(ViewBag.PackageList, "Value", "Text"))" class="form-control numeric1"><option>Select Package</option></select>
                    </td>
                    <td>
                        <select asp-for="MandateCheckDetailsList[checkNum].CountryId" asp-items="@(new SelectList(Model.CountryList, "Value", "Text"))" class="form-control numeric1 searchableCountry"><option>Select Country</option></select>
                        <span asp-validation-for="MandateCheckDetailsList[checkNum].CountryId" class="text-danger"></span>

                    </td>
                    <td>
                        <select asp-for="MandateCheckDetailsList[checkNum].CheckNameId" asp-items="@(new SelectList(Model.CheckList, "ID", "name"))" class="form-control numeric1"><option>Select Check Name</option></select>
                        <span asp-validation-for="MandateCheckDetailsList[checkNum].CheckNameId" class="text-danger"></span>

                    </td>
                    <td>
                        <select asp-for="MandateCheckDetailsList[checkNum].CheckTypeId" class="numeric1 form-control" asp-items="@(new SelectList(Model.CheckTypelist, "Value", "Text"))"><option>Select Check Type</option></select>
                        <span asp-validation-for="MandateCheckDetailsList[checkNum].CheckTypeId" class="text-danger"></span>

                    </td>
                    <td>
                        <select asp-for="MandateCheckDetailsList[checkNum].CountryTypeId" class="numeric1 form-control" asp-items="@(new SelectList(Model.CountryTypelist, "Value", "Text"))"><option>Select Country Type</option></select>
                        <span asp-validation-for="MandateCheckDetailsList[checkNum].CountryTypeId" class="text-danger"></span>
                        @* <select class="numeric1 form-control">
                            <option>Select Country Type</option>
                            <option value="1">Hiring country</option>
                            <option value="2">Research Jurisdiction</option>
                        </select> *@
                    </td>
                    <td>
                        **<button id="btnDeleteRow" type="button" class="btn btn-danger delete-btn">delete</button>**
                    </td>
                </tr>
            }

        </table>
        <div id="DivNewRow" class="container"></div>
    </div>
    <div class="row mar-top">
        <div class="col-lg-12">
            <input type="button" value="Add" class="btn btn-dark" id="Add" onclick="javascript: addCheck(@checkNum,@checkCount)" />
            <input id="btnLastDeleteRow" type="button" class="btn btn-danger" value="Delete Last Row" />
            <input type="hidden" id="checkCounter" value="@checkNum" />
            <input type="hidden" id="mandateCheckDetailsList_Count" name="mandateCheckDetailsList_Count" value="@Model.MandateCheckDetailsList.Count" />
        </div>
    </div>
</div>
</div>
</div>

JS FILE CODE:

$('#nextBtn').click(function () {    
        $('#clientCheckForm').submit(); 
});


// Handle delete button click
$('#checkTable').on('click', '.delete-btn', function () {
    if (confirm('Are you sure you want to delete ?')) {

        $(this).closest('tr').remove(); // Remove the clicked row

        //// Re-index remaining rows
        //$('#checkTable tr').each(function (index) {
        //    $(this).find('input, select').each(function () {
        //        var name = $(this).attr('name');
        //        var id = $(this).attr('id');

        //        if (name) {
        //            console.log('Original Name:', name);

        //            // Update the name attribute to reflect new index
        //            var newName = name.replace(/[d+]/g, '[' + index + ']');
        //            $(this).attr('name', newName);

        //            console.log('Updated Name:', newName);
        //        }
        //        if (id) {
        //            console.log('Original ID:', id);

        //            // Update the id attribute to reflect new index
        //            var newId = id.replace(/_d+__/, '_' + index + '__');
        //            $(this).attr('id', newId);

        //            console.log('Updated ID:', newId);
        //        }
        //    });
        //});

        $('#mandateCheckDetailsList_Count').val($('#checkTable tr').length);

        var rowCount = $('#checkTable tr').length;

        if (rowCount === 1) { // If there was only one row
            $('#clientCheckForm').submit();
        }

        toastr.success('Deleted successfully.');
    }
});


function addCheck(checkNum, chkcount) {
        var counter = $("#mandateCheckDetailsList_Count").val();
        chkcount = parseInt(counter) + 1;
        if (counter == 0) {
            checkNum = parseInt(counter) + 1;
            document.getElementById('mandateCheckDetailsList_Count').innerText = parseInt(checkNum) + 1;
        }
        else {
            checkNum = parseInt(counter);
            x = document.getElementById("mandateCheckDetailsList_Count").value = checkNum + 1;
        }
        var pkg = "";
        var country = "";
        var check = "";
        var checkType = "";
        var countryType = "";
        var dltBtn = "";

        var clientHidden = '<input type="hidden" id="MandateCheckDetailsList_' + checkNum + '__ClientId" name="MandateCheckDetailsList[' + checkNum + '].ClientId" value="' + $('#MandateCheckDetailsList_0__ClientId').val() + '"/>';
        pkg = "<select id='MandateCheckDetailsList_" + checkNum + "__PackageId' name='MandateCheckDetailsList[" + checkNum + "].PackageId' class='form-control numeric1'></select>";
        country = "<select id='MandateCheckDetailsList_" + checkNum + "__CountryId' name='MandateCheckDetailsList[" + checkNum + "].CountryId' class='form-control numeric1 searchablecountry'></select>";
        check = "<select id='MandateCheckDetailsList_" + checkNum + "__CheckNameId' name='MandateCheckDetailsList[" + checkNum + "].CheckNameId' class='form-control numeric1'></select>";
        checkType = "<select id='MandateCheckDetailsList_" + checkNum + "__CheckTypeId' name='MandateCheckDetailsList[" + checkNum + "].CheckTypeId' class='form-control numeric1'></select>";
        countryType = "<select id='MandateCheckDetailsList_" + checkNum + "__CountryTypeId' name='MandateCheckDetailsList[" + checkNum + "].CountryTypeId' class='form-control numeric1'></select>";
        dltBtn = "<button type='button' class='btn btn-danger delete-btn'>delete</button>"

        var html = "<tr><td>" + clientHidden + pkg + "</td><td>" + country + "</td><td>" + check + "</td><td>" + checkType + "</td><td>" + countryType + "</td><td>" + dltBtn + "</td></tr>";
        $("#checkTable").append(html);
        cc = checkNum;
        $('#MandateCheckDetailsList_0__PackageId option').each(function () {
            $("#MandateCheckDetailsList_" + checkNum + "__PackageId").append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>')
        });
        $('#MandateCheckDetailsList_0__CountryId option').each(function () {
            $("#MandateCheckDetailsList_" + checkNum + "__CountryId").append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>')
        });
        $('#MandateCheckDetailsList_0__CheckNameId option').each(function () {
            $("#MandateCheckDetailsList_" + checkNum + "__CheckNameId").append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>')
        });
        $('#MandateCheckDetailsList_0__CheckTypeId option').each(function () {
            $("#MandateCheckDetailsList_" + checkNum + "__CheckTypeId").append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>')
        });
        $('#MandateCheckDetailsList_0__CountryTypeId option').each(function () {
            $("#MandateCheckDetailsList_" + checkNum + "__CountryTypeId").append('<option value="' + $(this).val() + '">' + $(this).text() + '</option>')
        });
    }

I tried re-indexing of rows. But it is not working. When i try re-indexing as in above code which is commented, no rows are received in POST action method.

How to reset default socket host URL?

I am using nodejs to build a socket connection.

Code –

const socketIO = require('socket.io');

let io;
const usersInRoom = {}; // Object to keep track of users in rooms

const initializeSocket = (server) => {

    io = socketIO(server, {
        cors: {
            origin: "*",
            methods: ["GET", "POST"],
            credentials: true,
        },
        path: '/new/api/socket.io', // Custom path for WebSocket connections
        transports: ['websocket', 'polling'],
    });



    // io.of('/new/api').on('connection', (socket) => {
        io.on('connection', (socket) => {
            console.log('A user connected:', socket.id);

        socket.on('joinRoom', (data) => {
            let { groupId, userId } = data;

            if (!groupId || !userId) {
                return;
            }

            // Check if the user is already in the room to avoid duplicate join
            if (!socket.rooms.has(groupId)) {
                socket.join(groupId);
                socket.groupId = groupId;
                socket.userId = userId;

                if (!usersInRoom[groupId]) {
                    usersInRoom[groupId] = new Set();
                }
                usersInRoom[groupId].add(userId);

            } else {
                console.log(`User ${userId} is already in room ${groupId}`);
            }
        });

        socket.on('leaveRoom', () => {
            if (usersInRoom[socket.groupId]) {
                usersInRoom[socket.groupId].delete(socket.userId);
                if (usersInRoom[socket.groupId].size === 0) {
                    delete usersInRoom[socket.groupId];
                }
            }
            socket.leave(socket.groupId);
        });

        socket.on('message', (message) => {
            // Emit to all users in the room except the sender
            socket.broadcast.to(socket.groupId).emit('broadcast-message', message);
        });

        socket.on('disconnect', () => {
            if (usersInRoom[socket.groupId]) {
                usersInRoom[socket.groupId].delete(socket.userId);
                if (usersInRoom[socket.groupId].size === 0) {
                    delete usersInRoom[socket.groupId];
                }
            }
        });
    });
};

const getIoInstance = () => {
    if (!io) {
        throw new Error('Socket.io is not initialized!');
    }
    return io;
};

const getUsersInRoom = (groupId) => {
    return usersInRoom[groupId] ? Array.from(usersInRoom[groupId]) : [];
};

module.exports = { initializeSocket, getIoInstance, getUsersInRoom };

My server is running on localhost:5000, when I hot socket connect request on localhost:5000 this get connected with socket and functions working properly, but in production my endpoint is https://example.com/new/api and when I try to connect socket at this endpoint this did not get connected. This returns 404 error. Host URL is https://example.com/new/api not https://example.com/ but this is sending request to https://example.com/new/api. How can I fix this endpoint issue.

p5.touchgui buttons not displaying correctly

I’m making a flappy bird game using p5.play and p5.js with the gui using p5.touchgui. All was fine for a while until one day my gui stopped working properly. At first I thought maybe the library was updated and that caused some issue, but this isn’t the case. I have 4 buttons


startButton = createButton("Start", 20, 20, 100, 40);
pauseButton = createButton("Pause", 20, 60, 100, 40);
resetButton = createButton("Reset", 20, 100, 100, 40);
speedUpButton = createToggle("2x Speed", 20, 160, 100, 40);

pauseButton.visible = false;
resetButton.visible = false;
  1. the start button is meant to be visible only at the beginning and disappear after being clicked
  2. the pause button isnt visible to start with – turns visible when the game is being played and will pause the game when pressed. the pause button will then disappear one the player hits a pipe
  3. the reset button is not visible the whole time up until the player hits a pipe at which point will reset the game if pressed
  4. the speed up button is displayed only at the beginning of the game – when toggled to true the game will run at 2x speed essentially and when false the game will run at a ‘normal’ speed. the button isnt visible when the game is being player

like i said one day this was all working fine and the next it just stopped.
enter image description here
currently on the startig menu the issue is that he text on my start button doesnt appear and hovering over over the 2x speed button makes the start button also change color
enter image description here
while playing the outline of the start button and 2x speed button are both visible when they shouldnt be
enter image description here
similar issue once the player has touched the pipe/wall
enter image description here
after going to low and resetting the pause button outline is now visible too

I’ve checked that the i have the latet version of the libraries are being used and that the buttons are being set the invisible when they are meant to not be seen/displayed

Positioning navbars based on scroll position

I have a page with three navbars. During scrolling navbar1 must remain fixed, navbar2 must scroll away, navbar3 must append to navbar1.

Also in main I have a sidebar where I can’t manage the height so it doesn’t come out of its container. The sidebar must remain fixed during scrolling of the page, and move upwards when I start to no longer see its container.

I’m stuck for both problems, does anyone have a solution?

I’m not using all of Bootstrap, only the Grid system and Responsive utilities downloadable from this link: https://getbootstrap.com/docs/3.4/customize/

window.onscroll = function() {
  var sidebar = document.getElementById("sidebar");
  var footer = document.getElementById("footer");
  var sidebarHeight = sidebar.offsetHeight;
  var scrollPosition = window.scrollY + window.innerHeight;
  var footerPosition = footer.offsetTop;

  // if (window.scrollY > 100) {
  //     sidebar.classList.add("active");
  // } else {
  //     sidebar.classList.remove("active");
  // }

  if (scrollPosition > footerPosition) {
    sidebar.style.position = 'absolute';
    sidebar.style.top = (footerPosition - sidebarHeight) + 'px';
    sidebar.style.width = sidebar.offsetWidth + 'px';
  } else {
    sidebar.style.position = 'fixed';
    sidebar.style.top = '0';
    sidebar.style.width = '100%';
  }
};
@import url(/00.Asset/Reset-grid-Mquery/bootstrap/css/bootstrap.css);

/*===HEADER===*/

.nav1 {
  background-color: aquamarine;
  height: 150px;
  min-height: 150px;
  width: 100%;
  max-width: 100%;
  top: 0px;
  position: fixed;
}

.intro {
  background-color: orange;
  height: 150px;
  min-height: 150px;
  width: 100%;
  top: 150px;
  position: sticky;
}

.nav2 {
  background-color: violet;
  height: 150px;
  min-height: 150px;
  width: 100%;
  position: relative;
}


/*===MAIN===*/

.content {
  padding: 20px;
  height: 100vh;
}

.sidebar {
  position: fixed;
  top: 0;
  right: 0;
  width: 100%;
  max-width: 100px;
  height: 100vh;
  background-color: #f4f4f4;
  padding: 20px;
  box-shadow: -2px 0 5px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  overflow: hidden;
}

.sidebar-content {
  text-align: center;
  max-height: 100%;
  overflow-y: auto;
  padding-right: 20px;
}

.sidebar.active {
  background-color: #ddd;
}

@media (max-width: 992px) {
  .sidebar {
    display: none;
  }
}


/*===FOOTER===*/

footer {
  clear: both;
  padding: 20px;
  text-align: center;
  background-color: #333;
  color: white;
  position: relative;
}

footer {
  height: 150px;
}
<header class="container-fluid">
  <row class="row-no-gutters">
    <nav class="nav1">
      <h1>Nav1</h1>
    </nav>
    <div class="intro">
      <h1>Intro</h1>
    </div>
    <nav class="nav2">
      <h1>Nav2</h1>
    </nav>
  </row>
</header>
<main>
  <div class="container-fluid">
    <div class="row">
      <div class="col-lg-11 col-md-12 content">
        <h1>Contenuto Principale</h1>
        <p>Testo del contenuto principale...</p>
      </div>
      <div class="col-lg-1 col-md-12">
        <div class="sidebar" id="sidebar">
          <h2>Sidebar</h2>
          <p>Questo è il contenuto della sidebar</p>
        </div>
      </div>
    </div>
  </div>
</main>
<footer id="footer" class="text-center">
  <h2>Footer</h2>
  <p>Contenuto del footer...</p>
</footer>

script src MIME type html or javascript? [closed]

How to fix the problem of wrong MIME type, if a javascript page will firstly redirect you to a html login page, before it shows the javascript page after a successful auto login? For example:

mypage.html:

...
<script src="https://www.cba.com/123.js" type="text/javascript"></script>

This code will create a MIME type error, as the login page redirected from the js page is of html type. Is there any better way to include the js page as a script?

how can i convert words(number in words) to number(integer) [duplicate]

This is my current code
it works like

wordsToNum("one five eight twelve four") //outputs 15124

it returns numbers according to the words in string

I want it to work like this:-

wordsToNum("one hundred and twenty one") //outputs 121

with my code I have to write something like:- wordsToNum(“one two one”) which outputs “121”

const wordsTonum = (w) => {
  const numbers = {
    zero: 0,
    one: 1,
    two: 2,
    three: 3,
    four: 4,
    five: 5,
    six: 6,
    seven: 7,
    eight: 8,
    nine: 9,
    ten: 10,
    eleven: 11,
    twelve: 12,
    thirteen: 13,
    fourteen: 14,
    fifteen: 15,
    sixteen: 16,
    seventeen: 17,
    eighteen: 18,
    nineteen: 19,
    twenty: 20,
    thirty: 30,
    forty: 40,
    fifty: 50,
    sixty: 60,
    seventy: 70,
    eighty: 80,
    ninety: 90,
  };
  let a = w.split(" ");

  let numString = "";
  for (let i = 0; i < a.length; i++) {
    // console.log(a[i]);

    for (let k in numbers) {
      
    
      if (a[i] === k) {
        
        numString += numbers[k].toString();
      }
    }
  }
  return Number(numString);
};

console.log(wordsTonum("one five eight twelve four"));

console.log(wordsTonum("one hundred and twenty one"));