Optimal Javascript performance

Do you guys know any common misconception ppl might have when it comes to performance in js? I believe for example when looping though big data stack, for loop is more efficient than foreach. Im looking for stuff like that.

I believe for example when looping though big data stack, for loop is more efficient than foreach. Im looking for stuff like that.

Maybe even when jquery is favorable to js

how to position the button within the content while rending the button using javascript loop

`
this is my button but it is inside the loop so assume it will render more than 2 buttons i just wants this button should stick to the end of the parent div even while scrolling it should not move it should show in the same place like position fixed but i couldn’t fix the position properly because of position fixed behaviour it’s overriding button to the same place i tried position relative absolute still can’t get that

by applying postion relative to parent and psotion absolute to button along with it bottom and top

i want css to align in the correct place which is in the out of the rated-content but it should stick to the rated content without fixed the position`

Mask UnMask SSN Field

I want a SSN input field and the requirement is that when field is empty i want to show placeholder “___”. When User starts to enter value in SSN field. Each digit masks after entry or until the next digit is entered. The last 4 digits do not hide by default. Last 4 digits of SSN are shown by default. All others are hidden unless user selects the show/hide icon. It should also have eye icon on click of which user can see ssn in unmasked state.

If user types 1 in input field it should show .--____
If user types 2 in input field it should show ..-
-____
If user types 3 in input field it should show …--____
If user types 4 in input field it should show …-.
_
If user types 5 in input field it should show …-..-____
If user types 6 in input field it should show …-..-6___
If user types 7 in input field it should show …-..-67__
If user types 8 in input field it should show …-..-678_
If user types 9 in input field it should show …-..-6789
When user clicks on eye icon it should show 123-45-6789 when user again clicks on eye icon it should show …-..-6789
You can try using this with or without any npm package for this
I need solution in react and javascript

Based on start and end date using datepicker change the data values of other components of laravel livewire

We have main parent livewire component called AnalyticsNew in this file we are rendering all other multiple child view files. We have input type for start and end date and filter button onclick this button get selected dates and pass to livewire components, but by default when page loads it should be for 1 month data onclik button all child components should get refreshed in the page

Parent component
`<?php

namespace AppHttpLivewireAnalytics;

use LivewireComponent;

class AnalyticsNew extends Component
{
public $startDate;
public $endDate;

public function mount()
{
    // Set default start and end dates for one month
    $this->startDate = now()->subMonth()->toDateString();
    $this->endDate = now()->toDateString();
}

public function applyFilter()
{
    // Emit event with selected start and end dates
    $this->emit('filterApplied', ['startDate' => $this->startDate, 'endDate' => $this-      >endDate]);
}

public function render()
{
    return view('livewire.analytics.analytics-new')->extends('layouts.dashboard');
}

}
View

`

child component
` <?php

     namespace AppHttpLivewireAnalytics;

     use AppModelsNewsletter;
     use IlluminateSupportFacadesAuth;
     use LivewireComponent;
     use IlluminateSupportCarbon;

     class Subscriber extends Component
    {
        public $startDate;
        public $endDate;

        protected $listeners = ['filterApplied'];

        public function filterApplied($data)
        {
           dd($data);
           $this->startDate = $data['startDate'];
           $this->endDate = $data['endDate'];

          // Call the loadData method to refresh the component data
          $this->loadData();
        }

       public function loadData()
      {
          $userId = Auth::user()->id;
          $subscriber_rate = 0;
          $percentage = 0;

         if ($this->startDate && $this->endDate) {
          $subscriber_rate = Newsletter::whereUserId($userId)
            ->whereBetween('created_at', [$this->startDate, $this->endDate])
            ->count();
            // dd($subscriber_rate);
         } else {
        // Load default data if start and end dates are not set
        $lastMonthDate = Carbon::now()->subMonths(1);
        $subscriber_rate = Newsletter::whereUserId($userId)
            ->where('created_at', '>=', $lastMonthDate)
            ->count();
       }


    // Calculate percentage
          $lastMonthData = Newsletter::whereUserId($userId)
           ->whereBetween('created_at', [date('Y-m-01', strtotime('last month')), date('Y-m-t', strtotime('last month'))])
        ->count();

    $.   currentMonthData = Newsletter::whereUserId($userId)
        ->whereBetween('created_at', [date('Y-m-01', strtotime('this month')), date('Y-m-t', strtotime('this month'))])
        ->count();

    if ($lastMonthData != 0) {
        $percentage = ($currentMonthData - $lastMonthData) / ($lastMonthData / 100);
    }

    return [
        'subscriber_rate' => $subscriber_rate,
        'percentage' => $percentage
    ];
}

public function render()
{
    $data = $this->loadData();

    return view('livewire.analytics.subscriber')
        ->with('subscriber_rate', $data['subscriber_rate'])
        ->with('percentage', $data['percentage']);
}

}`

How to get Arrays from APIs and display them

I was playing with Pokemon’s API and I was able to get the names and sprites of the pokemons but got stuck when trying to fetch the array.

    async function fetchData()
    {
    const pokemonName = document.getElementById("pokemonName").value.toLowerCase();

    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${pokemonName}`);

    const data = await response.json();

    let elementTypes = data.types;
    for(let i = 0; i < elementTypes.length; i++)
        {
            let markup = `<li>${elementTypes[i]}</li>`;

            document.getElementById("pokeTypes").innerHTML = markup;
        }
    }

Pokemon can have multiple types and that’s ‘types’ I want to put it in my DIV, which is ‘pokeTypes’. I can’t seem to throw them into the HTML using a for loop

HTML Drop down section will not shift to href section

Hi I am trying to set a dropdown that can move to sections specified in herf

here is my initial code

    <div class="dropdown">
        <button class="dropdown-btn" aria-haspopup="menu">
            <span>Menu</span>
        </button>
        <ul class="dropdown-content" role="menu">
            <li><a href="#about-me-section">About Me</a></li>
            <li><a href="#projects-section">Projects</a></li>
            <li><a href="href='documents/resume/resume.pdf">Resume</a></li>
        </ul>
    </div>

According to this, about should go to the about section and projects to projects as mentioned in herf tags
but the li a are not getting clicks or cannot process them.

I have tried this js below that I took from another stack post – I did change the herf to data-herf when i was attempting this – Yet I could not resolve this.

$(document).ready(function() {
    $('a[data-href]').click(function(event) {
        event.preventDefault();

        var sectionToNavigate = $(this).attr('data-href');
        if(sectionToNavigate && $(sectionToNavigate).length) {
            $('html, body').animate({
                scrollTop: $(sectionToNavigate).offset().top
            }, 1000);
        }
    });
});

I have read other posts which concludes it as a browser issue. But I have tried edge, chrome and brave none seem to be working.

having trouble altering DOM from function

thanks for clicking.

I am new to JS and just like dinking around for fun but I am having trouble getting this function to work. I have tested it with google chrome alert('incorrect'); and it works but whenever I try running a style display property nothing happens.

any help is much appreciated & thank you in advance!

function validate() {
  let x = document.forms["myForm"]["fname"].value;
  if (x == "14") {
    pwForm.display.style = "none";
  }
}
<form name="myForm" onsubmit="validate()" id="passwordForm">
      <input
        id="passwordPrompt"
        type="text"
        placeholder="how many years?"
        name="fname"
      />
      <input type="submit" value="Submit" />
    </form>

Run “NPM INSTALL” on Visual Studio Code threw error Error: Unsupported platform: Windows_NT x64 using Window 11

I got facing the issue when running npm install, but always throw error: npm ERR! Error: Unsupported platform: Windows_NT x64

I also delete node_module and package-lock of project and run npm install again, still get issue

Also go to the npm-cache and npm of node js, and run npm i and npm install, nothing changes

enter image description here

Please help, I am using visual studio code to run test

Integrating Keycloak in Micro Frontends with Single SPA and Angular

I’m new to micro frontends and I’m currently building an application using Single SPA, where the child applications are written in Angular 16. I’m now at the stage where I need to integrate Keycloak authentication into my micro frontend architecture.

My question is: should I incorporate Keycloak directly into the Single SPA root configuration, or should I create a separate app just to handle Keycloak authentication?

Issue when try to invoke Javascript Library in Blazor that produce visible user interface elements

I am trying to invoke Tyro’s online payment javascript to create the payment form for my project. But it doesn’t work as my expected. (Refer to https://docs.connect.tyro.com/app/apis/pay/accept-an-online-payment/)

HTML:

 <form id="pay-form">
     <div id="tyro-pay-form">
     <!--Tyro.js injects the Pay Input Fields -->
     </div>
     <button id="pay-form-submit" hidde=@tyroPayForm_hide>Pay</button>
 </form>

.razor:

 TyroPayResponse res = JsonConvert.DeserializeObject<TyroPayResponse>(result);
                            string paySecret = res.paySecret;
 IJSObjectReference tyro;

 tyro = await JsRuntime.InvokeAsync<IJSObjectReference>("import","https://pay.connect.tyro.com/v1/tyro.js");                         
 await tyro.InvokeVoidAsync("init", paySecret);

 var payForm = await tyro.InvokeAsync<IJSObjectReference>("createPayForm");
 await payForm.InvokeAsync<IJSObjectReference>("inject", "#tyro-pay-form");                            
                           

When I get the response and use the paySecret to invoke this external javascript, it doesn’t show the payform that should be injected into the html.

I searched Microsoft official document, and I belive it has relevants with this part (https://learn.microsoft.com/en-us/aspnet/core/blazor/javascript-interoperability/call-javascript-from-dotnet?view=aspnetcore-6.0#javascript-libraries-that-render-ui)

So I introduce the ElementReference, while I create a new element in html

<div @ref="tyropayform"></div>

and use it by

private ElementReference tyropayform;

...

var payForm = await tyro.InvokeAsync<IJSObjectReference>("createPayForm");
await payForm.InvokeAsync<IJSObjectReference>("inject", tyropayform);

It doen’t work, but I am not suprised. The javascript funtion payForm.inject(selector) may not support with the element args.

As a learner of Blazor, I am not sure is there something I made a mistake or it is just because the external javascript function is not supported by Blazor when it try to render the UI. Can Someone give me any suggetions?

Java script Pesian DatePicker problem in calculate leap year

Hello everyone I wish you could help me to solve this problem. I have a date picker which I use in my project many times and it was a component. But now in the Persian New Year, we have 1403(Shamsi) but in my date picker it doesn’t show that it is a leap year.
It shows that next year I mean 1404 is a leap year. But the previous leap year that it was 1399 is correct in it.

function leap_persian(year)
{ return ((((((year - ((year > 0) ? 474 : 473)) % 2820) + 474) + 38) * 682) % 2816) <682, }

var PERSIAN_EPOCH = 1948320.5;

function persian_to_jd(year, month, day)
{
var epbase, epyear;

epbase = year - ((year >= 0) ? 474 : 473);

epyear = 474 + mod(epbase, 2820);

return day +
        ((month <= 7) ?
            ((month - 1) * 31) :
            (((month - 1) * 30) + 6)
        ) +
        Math.floor(((epyear * 682) - 110) / 2816) +
        (epyear - 1) * 365 +
        Math.floor(epbase / 2820) * 1029983 +
        (PERSIAN_EPOCH - 1); }


function jd_to_persian(jd)
 {var year, month, day, depoch, cycle, cyear, ycycle,
    aux1, aux2, yday;
  jd = Math.floor(jd) + 0.5;

depoch = jd - persian_to_jd(475, 1, 1);
cycle = Math.floor(depoch / 1029983);
cyear = mod(depoch, 1029983);
if (cyear == 1029982) {
    ycycle = 2820;
} else {
    aux1 = Math.floor(cyear / 366);
    aux2 = mod(cyear, 366);
    ycycle = Math.floor(((2134 * aux1) + (2816 * aux2) + 2815) / 1028522) +
                aux1 + 1;
}
year = ycycle + (2820 * cycle) + 474;
if (year <= 0) {
    year--;
}
yday = (jd - persian_to_jd(year, 1, 1)) + 1;
month = (yday <= 186) ? Math.ceil(yday / 31) : Math.ceil((yday - 6) / 30);
day = (jd - persian_to_jd(year, month, 1)) + 1;
return new Array(year, month, day);}

These are some functions that are used in the main function and the main function is the following part. I don’t which part I need to change to show it correctly in the calendar because I changed some numbers in the Persian function and it is like: year – ((year > 0)? 474: 473 TO => year – 473
and it said that 1403 is a leap and it’s true but it doesn’t show in the calendar correctly.

function JalaliDate(p0, p1, p2) {
var gregorianDate;
var jalaliDate;

if (!isNaN(parseInt(p0)) && !isNaN(parseInt(p1)) && !isNaN(parseInt(p2))) {
    var g = jalali_to_gregorian([parseInt(p0, 10), parseInt(p1, 10), parseInt(p2, 10)]);
    setFullDate(new Date(g[0], g[1], g[2]));
} else {
    setFullDate(p0);
}

function jalali_to_gregorian(d) {
    var adjustDay = 0;
    if(d[1]<0){
        adjustDay = leap_persian(d[0]-1)? 30: 29;
        d[1]++;
    }
    var gregorian = jd_to_gregorian(persian_to_jd(d[0], d[1] + 1, d[2])-adjustDay);
    gregorian[1]--;
    return gregorian;
}

function gregorian_to_jalali(d) {
    var jalali = jd_to_persian(gregorian_to_jd(d[0], d[1] + 1, d[2]));
    jalali[1]--;
    return jalali;
}

function setFullDate(date) {
    if (date && date.getGregorianDate) date = date.getGregorianDate();
    gregorianDate = new Date(date);
    gregorianDate.setHours(gregorianDate.getHours() > 12 ? gregorianDate.getHours() + 2 : 0)
    if (!gregorianDate || gregorianDate == 'Invalid Date' || isNaN(gregorianDate || !gregorianDate.getDate())) {
        gregorianDate = new Date();
    }
    jalaliDate = gregorian_to_jalali([
        gregorianDate.getFullYear(),
        gregorianDate.getMonth(),
        gregorianDate.getDate()]);
    return this;
}

this.getGregorianDate = function() { return gregorianDate; }

this.setFullDate = setFullDate;

this.setMonth = function(e) {
    jalaliDate[1] = e;
    var g = jalali_to_gregorian(jalaliDate);
    gregorianDate = new Date(g[0], g[1], g[2]);
    jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
}

this.setDate = function(e) {
    jalaliDate[2] = e;
    var g = jalali_to_gregorian(jalaliDate);
    gregorianDate = new Date(g[0], g[1], g[2]);
    jalaliDate = gregorian_to_jalali([g[0], g[1], g[2]]);
};

this.getFullYear = function() { return jalaliDate[0]; };
this.getMonth = function() { return jalaliDate[1]; };
this.getDate = function() { return jalaliDate[2]; };
this.toString = function() { return jalaliDate.join(',').toString(); };
this.getDay = function() { return gregorianDate.getDay(); };
this.getHours = function() { return gregorianDate.getHours(); };
this.getMinutes = function() { return gregorianDate.getMinutes(); };
this.getSeconds = function() { return gregorianDate.getSeconds(); };
this.getTime = function() { return gregorianDate.getTime(); };
this.getTimeZoneOffset = function() { return gregorianDate.getTimeZoneOffset(); };
this.getYear = function() { return jalaliDate[0] % 100; };

this.setHours = function(e) { gregorianDate.setHours(e) };
this.setMinutes = function(e) { gregorianDate.setMinutes(e) };
this.setSeconds = function(e) { gregorianDate.setSeconds(e) };
this.setMilliseconds = function(e) { gregorianDate.setMilliseconds(e) };}