renderButton stops working and not showing google sign in button Angular

This was working fine until now.

ERROR in console – indicating the issue with the line with “renderButton”

enter image description here

login.component.ts

ngAfterViewInit() {
        google.accounts.id.initialize({
            client_id: 'XXXXX',
            callback: this.handleCredentialResponse.bind(this),
            auto_select: false,
            cancel_on_tap_outside: true,

        });
        
        google.accounts.id.renderButton(
            document.getElementById('google-button'),
            { theme: 'filled_blue', size: 'large', width: '215' }
        );
 }

login.component.html

<div id="google-button"></div>.

I tried:

  1. Moving the code from ngAfterViewInit to ngOnInit – it was just a try.
  2. Wrapping the code inside ngAfterViewInit to setTimeout(()=> { // here }) doesn’t work.

Dynamic Dropdowns with Database Values in Laravel

I’m currently facing an issue with dynamic dropdowns in my Laravel project. Specifically, I’m working on the user edit form, which requires a dynamic dropdown to be automatically selected based on the data stored in the database.

I want the Sub Department dropdown to be selected according to the sub_department_id in the users table when the edit page is loaded. I have tried various approaches, but none seem to work as expected.

Below is the relevant code for UsersController, Blade template, and the associated JavaScript function:

UsersController

public function edit(User $user)
    {
        $userRole = $user->roles->pluck('name')->toArray();
        $roles = Role::latest()->get();
        $selectedDepartmentId = $user->department_id;
        $selectedSubDepartmentId = $user->sub_department_id;
        $departments = Department::all();
        $subDepartments = SubDepartment::all();
        $joinDate = Carbon::parse($user->join_date)->format('Y-m-d');
        $is_active = $user->userStatus->is_active;

        return view('pages.master.users.edit', compact('user', 'userRole', 'roles', 'selectedDepartmentId', 'selectedSubDepartmentId', 'departments', 'subDepartments', 'joinDate', 'is_active'));
    }

edit.blade.php

<div class="row">
                                        <div class="form-group col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                                            <label for="departmentDropdown">Department</label>
                                            <select class="form-control selectric" name="department_id" id="departmentDropdown" onchange="ChangedeptList()" required>
                                                <option>Choose a Department</option>
                                                @if ($user->department_id == 1)
                                                    @foreach ($departments as $department)
                                                        <option value="{{ $department->id }}" {{ $department->id == $selectedDepartmentId ? 'selected' : '' }}>{{ $department->department_name }}</option>
                                                    @endforeach
                                                @else
                                                    @foreach ($departments->skip(1) as $department)
                                                        <option value="{{ $department->id }}" {{ $department->id == $selectedDepartmentId ? 'selected' : '' }}>{{ $department->department_name }}</option>
                                                    @endforeach
                                                @endif
                                            </select>
                                            @if ($errors->has('department_id'))
                                                <span class="text-danger text-left">{{ $errors->first('department_id') }}</span>
                                            @endif
                                        </div>
                                        <div class="form-group col-xl-6 col-lg-6 col-md-6 col-sm-12 col-12">
                                            <label for="subdeptDropdown">Sub Department</label>
                                            <select class="form-control selectric" name="sub_department_id" id="subdeptDropdown" required>
                                                <option>Choose a Sub Department</option>
                                            </select>
                                            @if ($errors->has('sub_department_id'))
                                                <span class="text-danger text-left">{{ $errors->first('sub_department_id') }}</span>
                                            @endif
                                        </div>
                                    </div>

Javascript

<script>
        var departments = {!! $departments !!};
        var subDepartments = {!! $subDepartments !!};
        var selectedDepartmentId = {!! json_encode($selectedDepartmentId) !!};
        var selectedSubDepartmentId = {!! json_encode($selectedSubDepartmentId) !!};

        function setSelectedOption(selectElement, selectedValue) {
            for (var i = 0; i < selectElement.options.length; i++) {
                if (selectElement.options[i].value === selectedValue) {
                    selectElement.selectedIndex = i;
                    break;
                }
            }
        }

        function ChangedeptList() {
            var deptList = document.getElementById("departmentDropdown");
            var subList = document.getElementById("subdeptDropdown");
            var selDept = deptList.options[deptList.selectedIndex].value;

            while (subList.options.length > 1) {
                subList.remove(1);
            }

            var selectedDepartment = departments.find(function(department) {
                return department.id == selDept;
            });

            if (selectedDepartment && subDepartments.length > 0) {
                var selectedSubDepartments = subDepartments.filter(function(subDepartment) {
                    return subDepartment.department_id == selDept;
                });

                selectedSubDepartments.forEach(function(subDepartment) {
                    var option = new Option(subDepartment.sub_department_name, subDepartment.id);
                    subList.options.add(option);
                });

                $(subList).selectric('refresh');
                
                setSelectedOption(subList, selectedSubDepartmentId); 
            }
        }

        document.addEventListener("DOMContentLoaded", function() {
            ChangedeptList();
        });
    </script>

If anyone has encountered a similar issue or knows how to correctly selected dynamic dropdown based on database values, I would greatly appreciate your insights and suggestions.

Thank you in advance for your time and assistance.

Ajax Not Working – DATA CANT BE IDENTIFIED

student_id having a value of 0001. It shows the error

“Uncaught ReferenceError: studentId is not defined”

$.ajax({
    url: "student_info.php",
    method: "post",
    data: {
      studentId: student_id
    },
    success: function (data, status) {
      console.log(studentId);
    },
  });

console.log should display the value of ‘0001’.

How to pass value to another file?

How to pass value of ‘row‘ to EditRecord (child file)? Once I’m on EditRecord page, the props (record) of the parent’s file’s gone.

Parent File:

const [record, setRecord] = React.useState({});

return ( 
  <TableBody>
          {stableSort(props.data, getComparator(order, orderBy))
            .slice(page * rowsPerPage, page * rowsPerPage + rowsPerPage)
            .map((row, index) => (   
                <TableRow 
                    className={(classes.tableAltenativeColor, classes.tableRow)}
                    key={index}
                >  
                    <TableCell style={{verticalAlign: 'top'}}>                                                                                                                                  
                          <Button                            
                            onClick={() => {setRecord(JSON.stringify(row))}}
                            href={`${config.home}edit`} 
                            >                  
                              <EditNoteOutlined 
                                color={"primary"}                                            
                              />                                                          
                          </Button>  
                       <EditRecord record={record}/>
                    </TableCell>  
             ))}                  
    </TableBody>
 )

sticky of navbar is effecting other divs

I created a navbar and used sticky to fix the navbar at the top of the webpage. The problem is, when sticky is being activated, it is push the image below it a bit. How do I prevent this from happening? I thought the problem was because of differences in how I used position property but I have a similar code that is working with no problems. Also, will help if anyone can share how to make the sticky transition smooth and seamless. I am attaching part of code for the same

window.onscroll = function() {
  myFunction()
};

var navbar = document.getElementById("navbar");
var sticky = navbar.offsetTop;

function myFunction() {
  if (window.pageYOffset >= sticky) {
    navbar.classList.add("sticky")
  } else {
    navbar.classList.remove("sticky");
  }
.main-navbar {
  display: inline-flex;
  width: 100%;
  max-width: 800px;
  position: relative;
  padding-bottom: 17px;
  left: 20%;
  top: 0px;
}


/*Code for Sticky*/

.sticky {
  position: fixed;
  top: 10px;
  background-color: white;
  z-index: 99999999;
  transition: 0.3s top ease-in-out;
  -webkit-transition: 0.3s top ease-in-out;
  -moz-transition: 0.3s top ease-in-out;
  -ms-transition: 0.3s ease-in-out;
  -o-transition: 1s ease-in-out;
  animation: faceInEffect 0.3s;
  -webkit-animation: faceInEffect 0.3s;
  box-shadow: -1px 2px 4px rgb(110, 109, 109);
}

@keyframes faceInEffect {
  from {
    top: 0px;
  }
  to {
    top: 10px;
  }
}

.hero>img {
  position: relative;
  top: 6.7rem;
  left: 4.5rem;
}
<div class="main-navbar" id="navbar">
  <nav>
    <ul class="nav-list">
      <li class="dropdown-item-1">
        <a href="">Men</a>
        <ul class="sub-menu">
          <li><a href="#">shirts</a> </li>
        </ul>
      </li>
    </ul>
  </nav>
</div>



<div class="contentforscroll>

 src=" https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_906,c_limit/83f15213-514a-4963-a765-74c379b89a34/nike-just-do-it.png "
        alt=" " style="width: 1300px; ">
<img  src="https://static.nike.com/a/images/f_auto/dpr_1.0,cs_srgb/w_906,c_limit/83f15213-514a-4963-a765-74c379b89a34/nike-just-do-it.png "
        alt=" " style="width: 1300px; ">></img>
</div>

Scrolling acting weird with javascript on firefox

So here is the code I use to scroll (I hope it’s not too bad, I only have about 4 days of experience working with this)

const ScrollDelay = 130;

var LastScrollTime = Date.now();
var NewScrollTime = Date.now();
var IsScrolling = false;
var CurrentPage;

function GotoPage(PageNumber) {
    PageNumber = Math.min(Math.max(PageNumber, 1), 5);
    
    if (CurrentPage == PageNumber) {
        return false;
    }
    
    document.getElementById("Page"+PageNumber).scrollIntoView({behavior: "smooth", inline: "center"})
}

function ScrollStart(Wheel) {
    NewScrollTime = Date.now();
    
    if (!Wheel) {
        return false;
    }
    
    Wheel.preventDefault(Wheel);
    Wheel.stopPropagation(Wheel);
    
    if ((NewScrollTime - LastScrollTime) < ScrollDelay || IsScrolling == true) {
        return false;
    }
    
    IsScrolling = true;
    
    if (Wheel.deltaY < 0) {
        GotoPage(CurrentPage - 1);
    } else {
        GotoPage(CurrentPage + 1);
    }
    
    LastScrollTime = Date.now();
    return false;
}

function ScrollEnd() {
    CurrentPage = Math.min(Math.max(Math.round(window.scrollY / innerHeight) + 1, 1), 5);
}

window.onload = function() {
    CurrentPage = Math.round(window.scrollY / window.innerHeight) + 1;
}

window.addEventListener("wheel", ScrollStart, {passive: false});

document.onscrollend = (event) => {
    ScrollEnd();
    IsScrolling = false;
};
* {
    font: 16px Verdana, sans-serif;
    padding: 0px;
    margin: 0px;
}



:root::-webkit-scrollbar {
    width: 0;
    height: 0;
}

/* ------------------------------------------------------Pages------------------------------------------------------ */

.PageContainer {
    padding: 0;
    margin: 0;
}

.Page {
    width: 100%;
    height: 100vh;
    padding: 0;
    margin: 0;
}

#Page1 {
    background-color: darkred;
}

#Page2 {
    background-color: green;
}

#Page3 {
    background-color: purple;
}

#Page4 {
    background-color: darkblue;
}

#Page5 {
    background-color: brown;
}
<!DOCTYPE html>
<html lang="en">
    <head>
        <link rel="stylesheet" href="index.css">
    </head>
    <body>
        <script src="Main.js"></script>
        <div class="PageContainer">
            <div class="Page" id="Page1"></div>
            <div class="Page" id="Page2"></div>
            <div class="Page" id="Page3"></div>
            <div class="Page" id="Page4"></div>
            <div class="Page" id="Page5"></div>
        </div>
    </body>
</html>

It’s supposed to smoothly scroll between the multi-colored pages, however it doesn’t work as intended on firefox.

It works normally if you only move 1 notch on the scroll wheel, however doing more than one causes it to stutter and stop.

This is how it should work (Shown on google chrome)

This is how it works on firefox

Here is the whole site as a zip file. If I’m not allowed to post this or there are better alternatives then let me know and I’ll fix it.

There are no errors and I have no idea how to fix this, I’ve tried looking for problems similar to mine but haven’t been able to find any because I don’t even know what to call it.

Edit: I made a codepen for it

Calling an async function every 5 seconds but it throws this error: ‘Cannot read properties of undefined (reading ‘temp’)’

I’m trying to create a weather app. I wanted to update the weather data every 5 seconds by calling the async function every 5 seconds using setInterval(). However, I get an error 400
enter image description here

const APIkey = 'c571c7fe39b869a406ab7e98d2f009c5';
const apiURL = 'https://api.openweathermap.org/data/2.5/weather?units=metric'


//Default city set to New York
const input = document.querySelector('input');
input.value = 'New York';

checkWeather();
let intervalID = setInterval(checkWeather, 5000)

const button = document.querySelector('button');

button.addEventListener('click', () => {
    checkWeather();
    clearInterval(intervalID);
    intervalID = setInterval(checkWeather, 5000);
});

input.addEventListener('keyup', (event) => {
    if (event.key === 'Enter') {
        checkWeather();
        clearInterval(intervalID);
        intervalID = setInterval(checkWeather, 5000);
    }
});

async function checkWeather(){
    try {
        const response = await fetch(apiURL + `&q=${input.value}&appid=${APIkey}`)
        const data = await response.json();

        const temp = document.querySelector('.temp');
        temp.textContent = `${data.main.temp}°c`

        const city = document.querySelector('.city');
        city.textContent = data.name;

        const windspeed = document.querySelector('.windspeed');
        windspeed.textContent = `${data.wind.speed} km/h`

        const humidity = document.querySelector('.humid');
        humidity.textContent = `${data.main.humidity} %`

        const clouds = document.querySelector('.cloud');
        clouds.setAttribute('src',`images/${data.weather[0].main.toLowerCase()}.png`)

        input.value = '';
        
        console.log(data.main)
    } catch (error) {
        console.log('Error occured:', error.message);
        const errorMsg = document.querySelector('.error-message');
        errorMsg.style.display = 'block'
    }
}

I tried to change the interval to a minute thinking that 5seconds is to quick but it still shows an error.

Why isn’t VS Code setting every line to a max of 80 on save?

I installed the Prettier extension and the max line width is set to 80. I also have it set to format on save. When I save the file I’m working on, I see that the comments are still really long widths. The extension should be shortening these to 80 max width, but it’s not doing it. Is there another setting I need to use? Or maybe there’s a better extension than Prettier? I just want to use whatever formatter that will get rid of the 200+ errors when I try to deploy my typescript cloud functions.

If else statement in JavaScript keeps returning last else statement no matter user input

 var age = prompt('How old are you?');
    if ('age' <= 5){
        alert("You are a baby!");
    }
    else if ('age' >= 5 && 'age' < 18){
        alert("You are a child!");
    }
    else if ('age' >= 18 && 'age' < 70){
        alert("You are an adult!");
    }
    else
        alert("You are a senior!");

So I am trying to make it change depending on user input for age. However, no matter the age I enter “You are a senior!” is the only alert that goes off.

Category menu drop-down area Disappears on scroll (BLOGGER)

I have the following problem on my blogger, while I scroll down the categories menu and its dropdown area disappears very early on scrolling down, I am unable to access the entire dropdown menu. How to keep dropdown menu permanently and not disappear before scrolling from view….

MY BLOGGER

https://bloggerdetestes2023.blogspot.com/

I don’t have much experience with programming, so I haven’t tried to do anything to solve my problem yet! I’ve been looking on google! However, I couldn’t find an answer to solve my problem!

conditional return type not valid with prisma

I have the following conditional type inside my Express app:

type SerializedFunction<Serialized, Unserialized> 
    = <B extends boolean>(serialized: B) 
    => Promise<B extends true 
        ? (Serialized   | null) 
        : (Unserialized | null)
    >;

It is being attached to a function like so:

import type { examples } from "@prisma/client";

interface DataSerialized{
    foo: string;
    bar: number;
}

const data: SerializedFunction<DataSerialized, examples> = async serialized => {
    // Return non-serialized data.
    if(!serialized) return await prisma.examples.findFirst({ 
        // ...
    });

    const example = await prisma.examples.findFirst({
        // ...
        select: {
            foo: true,
            bar: true,
        }
    });

    if(!example) return null;
    return {
        ...example,
        bar: await doSomethingWithBar(bar)
    };
}

The purpose of SerializedFunction is to set the return type of the function to either DataSerialized or examples depending on whether or not the function parameter is set to true (or null if no result is found).

However, when I try to implement this, I receive the following TypeScript error:

Type examples | { 
    // The object specified in the first "findFirst" call...
}
is not assignable to type 'B extends true ? DataSerialized : examples'.

Type 'examples' is not assignable to type 'B extends true ? DataSerialized : examples'

Where am I going wrong?

VIDEOJS – Reproduce differente content using a main player and a pip player from videojs

I am new to react. Basically what I am trying to do is to have a main player and then through a button, enable a pip window to play the minute I set. That is, the same video but it plays at different times at the same time. Or also to be able to reproduce in the pip player other content that does not have to do with the main video.

This is my current code,this is a component ive created. Is it possible to do what I am trying to do? or do I have to create a new player that simulates a pip?
The error is that I can not simulate the pip as a new player, besides when I want to run the component 2 times it dies, it is as if after the dispose I can not use it anymore.

import React, { useEffect, useRef, useState } from 'react';
import videojs, { type VideoJsPlayer } from 'video.js';
import 'video.js/dist/video-js.css';

export interface PipVideoJSProps {
    videoSrc: string;
    startTime: number;
    pipDuration: number;
    muted?: boolean;
    controls?: boolean;
}

const PipVideoJS: React.FC<PipVideoJSProps> = ({
    videoSrc,
    startTime,
    pipDuration,
    muted = true,
    controls = false
}) => {
    const videoRef = useRef<HTMLVideoElement>(null);
    const [isPIPOn, setIsPIPOn] = useState(false);

    useEffect(() => {
        let player: VideoJsPlayer | null = null;

        // Initialize Video.js player
        if (videoRef.current != null) {
            player = videojs(videoRef.current, {
                autoplay: true,
                controls,
                muted, // Override the "muted" option to ensure it's muted in PIP mode
                sources: [
                    {
                        src: videoSrc,
                        type: 'video/mp4'
                    }
                ]
            });

            // Set the start time of the video
            player.currentTime(startTime * 30);

            // Enter Picture-in-Picture when the player is ready and metadata is loaded
            player.ready(() => {
                if (player != null && document.pictureInPictureEnabled) {
                    // Get the video element from the Video.js player
                    const videoElement = player.tech().el() as HTMLVideoElement;

                    // Add the event listener for loadedmetadata to ensure the metadata is loaded
                    videoElement.addEventListener('loadedmetadata', () => {
                        // Add the event listener for entering Picture-in-Picture
                        videoElement.addEventListener('enterpictureinpicture', () => {
                            setIsPIPOn(true);
                        });
                        // Add the event listener for leaving Picture-in-Picture
                        videoElement.addEventListener('leavepictureinpicture', () => {
                            setIsPIPOn(false);
                        });

                        // Request Picture-in-Picture after metadata is loaded
                        videoElement.requestPictureInPicture();
                    });
                }
            });
        }

        // Dispose the player when the component unmounts
        return () => {
            if (player != null) {
                player.dispose();
            }
        };
    }, [videoSrc, startTime, muted, controls]);

    useEffect(() => {
        // Exit Picture-in-Picture after the specified duration
        
        const closePIPAfterDuration = () => {
            setTimeout(() => {
                if (document.pictureInPictureElement != null) {
                    document.exitPictureInPicture();
                    setIsPIPOn(false);
                }
            }, pipDuration * 1000);
        };

        closePIPAfterDuration();
    }, [pipDuration]);

    return (
        <div className="pip-container">
            <video ref={videoRef} className="video-js" />
            {isPIPOn ? (
                <p>Picture-in-Picture is ON</p>
            ) : (
                <p>Picture-in-Picture is OFF</p>
            )}
        </div>
    );
};

export default PipVideoJS;

Why I get double number of items in my array? [closed]

I’d like to see two items in the result but I’m getting them twice, why?

let arr = [];

for (let i = 0; i < 2; i++) {
  arr.push(i);
}

document.getElementById("demo").innerHTML = arr.fill(
  arr.map((item) => item * 10)
);
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>Static Template</title>
</head>

<body>

  <p id="demo"></p>

</body>

</html>

Why does blur event never fire if Chrome developer tools debugger is triggered?

Consider this input – we blur on pressing enter.

It normally works. But if you open Devtools, so the debugger line works, then !!blur never fires – even though the element loses focus!

Why, what’s going on?

And is there a way to get a reliable blur event?

(It’s not just Devtools/debugger – there seem to be other cases where this can happen, such as if the window is out of focus, but I haven’t dug deep enough yet to have anything concrete to report here.)

document.querySelector('input').addEventListener('blur', () => console.log('!!blur'));

document.querySelector('input').addEventListener('focus', () => console.log('!!focus'));

document.querySelector('input').addEventListener('keypress', (e) => {
  if (e.key === 'Enter') {
    console.log("!!enter");
    debugger;
    e.target.blur();
  }
});
<input>

<p>Try compare opening / closing devtools and pressing enter - !!blur is missing when open!</p>