Detect the HD image size from the given src and srcset

This is my generated html code with the thumbnail being image-four-300x151.jpg and HD quality being image-four.jpg

<figure class="wp-block-gallery has-nested-images columns-default is-cropped lightbox wp-block-gallery-1 is-layout-flex">
    <figure class="wp-block-image size-medium"><img decoding="async" loading="lazy" width="300" height="151" data-id="218" src="http://localhost/demo/wp-content/uploads/2023/11/image-four-300x151.jpg" alt="" class="wp-image-218" srcset="http://localhost/demo/wp-content/uploads/2023/11/image-four-300x151.jpg 300w, http://localhost/demo/wp-content/uploads/2023/11/image-four-1024x517.jpg 1024w, http://localhost/demo/wp-content/uploads/2023/11/image-four-768x388.jpg 768w, http://localhost/demo/wp-content/uploads/2023/11/image-four.jpg 1280w" sizes="(max-width: 300px) 100vw, 300px" data-galley="0" style="cursor: zoom-in;"></figure>
</figure>

Here’s the complete JS code below that detects the src and opens the image in a lightbox. However, the ${linkImage} opens image-four-300x151.jpg which is blurry. I want it to open the original HD image which is image-four.jpg.

How do I go about this?

window.addEventListener('load', function () {
const allGallery = [...document.querySelectorAll('.wp-block-gallery')]

let imageGroup = [];
let images = [];
allGallery.forEach((item, index) => {
   let imgs =  item.querySelectorAll('img')
    const imageArray = [];
   imgs.forEach((im) => {
        im.setAttribute('data-galley', index);
        imageArray.push(im);
        images.push(im);
})
imageGroup.push(imageArray);
});
images.forEach(e => e.style.cursor = "zoom-in")
  array = [...images].forEach(item => item.addEventListener('click', handleCreateLightbox))
  function handleCreateLightbox(e) {
    let linkImage = e.target.getAttribute('src')
    let ss = e.target.dataset.galley
    let code = `<div class="cookie_box">
    <div class="cookie_box-content">
      <i class="cookie_box-prev" data-source="${ss}"><svg class="cookie_box-prev" data-source="${ss}" width="22"  viewBox="0 0 66.692 126.253" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><g style="fill:#fff;fill-opacity:1;stroke:none;stroke-opacity:1"><path d="m360.731 229.075-225.1-225.1c-5.3-5.3-13.8-5.3-19.1 0-5.3 5.3-5.3 13.8 0 19.1l215.5 215.5-215.5 215.5c-5.3 5.3-5.3 13.8 0 19.1 2.6 2.6 6.1 4 9.5 4 3.4 0 6.9-1.3 9.5-4l225.1-225.1c5.3-5.2 5.3-13.8.1-19z" style="fill:#fff;fill-opacity:1;stroke:none;stroke-opacity:1" transform="matrix(-.26458 0 0 .26458 96.472 0)"/></g></svg></i>
      <img
        src="${linkImage}"
        alt=""
        class="cookie_box-image"
      />
      <i class="cookie_box-next" data-source="${ss}"><svg data-source="${ss}" class="cookie_box-next" width="22" viewBox="0 0 66.692 126.253" xml:space="preserve" xmlns="http://www.w3.org/2000/svg"><g style="fill:#fff;fill-opacity:1;stroke:none;stroke-opacity:1"><path d="m360.731 229.075-225.1-225.1c-5.3-5.3-13.8-5.3-19.1 0-5.3 5.3-5.3 13.8 0 19.1l215.5 215.5-215.5 215.5c-5.3 5.3-5.3 13.8 0 19.1 2.6 2.6 6.1 4 9.5 4 3.4 0 6.9-1.3 9.5-4l225.1-225.1c5.3-5.2 5.3-13.8.1-19z" style="fill:#fff;fill-opacity:1;stroke:none;stroke-opacity:1" transform="matrix(.26458 0 0 .26458 -29.78 0)"/></g></svg></i>
    </div>
  </div>`
    document.body.insertAdjacentHTML('beforeend', code)
  }
  let index = 0
  document.addEventListener('click', handleOutLightbox)
  function handleOutLightbox(e) {
    const lightImage = document.querySelector('.cookie_box-image')
    let imageSrc = ''
    if (!lightImage) return
    let galley_id = e.target.dataset.source;

    if (e.target.matches('.cookie_box')) {
      const body = e.target.parentNode
      body.removeChild(e.target)

    } else if (e.target.matches('.cookie_box-next')) {
      imageSrc = lightImage.getAttribute('src')

      index = imageGroup[galley_id].findIndex(item => item.getAttribute('src') === imageSrc)
      index = index + 1
      firstImage = 0
      if (index > imageGroup[galley_id].length - 1) {
        index = firstImage
      }
      ChangeLinkImage(galley_id , index, lightImage)

    } else if (e.target.matches('.cookie_box-prev')) {
      imageSrc = lightImage.getAttribute('src')
      index = imageGroup[galley_id].findIndex(item => item.getAttribute('src') === imageSrc)
      index = index - 1
      lastImage =imageGroup[galley_id].length - 1
      if (index < 0) {
        index = lastImage
      }
      ChangeLinkImage( galley_id, index, lightImage)
    }
  }
  function ChangeLinkImage(galley_id, index, lightImage) {
    const newLink = imageGroup[galley_id][index].getAttribute('src')
    lightImage.setAttribute('src', newLink)
  }
})

Read local XLSX file and edit it in React

I am using ExcelJS library in React to read a local XLSX file. My motive is to read the template.xlsx file from local, in the same directory and modify it as needed and download it using saveAs library.

Following is the code that I am following right now:

import ExcelJS from 'exceljs';
import { saveAs } from 'file-saver';

export async function generateExcelReport() {
  try {
    const workbook = new ExcelJS.Workbook();
    await workbook.xlsx.readFile('template.xlsx');
    const worksheet = workbook.getWorksheet('Sheet1');
    const cellC2 = worksheet.getCell('C2');
    cellC2.value = 'New Value';
    const blob = await workbook.xlsx.writeBuffer();
    saveAs(new Blob([blob]), 'modified_template.xlsx');
  } catch (error) {
    console.error('Error generating the report', error);
  }
}

But I am unable to read the file, is it true that we would need a FileReader on the client side to read the files?
What is the best way to do this?

Highcharter Network Graph in R

I need to plot a network graph in my shiny app. I mostly use highcharter package for my visuals.

There are some example networkgraphs in this page:
https://www.highcharts.com/docs/chart-and-series-types/network-graph

I tried to use ChatGPT to convert the JS code to R; however the codes that ChatGPT provided did not give the network graph. In fact the codes was only producing blank charts.

Is it possible to obtain a network graph in R using highcharter package?

Is it possible to enable internal routing for the rendered HTML content instead of refreshing the entire page?

I have an HTML string that originates from the server. Since it’s a legacy system, I’m unable to modify its format. However, I need to display this HTML content in the DOM. To achieve this, I’m utilizing the bypassSecurityTrustHtml function provided by DomSanitizer.

The issue lies within this HTML content, as it contains an anchor (<a>) link that is intended to navigate to another page within the system. Currently, when I click on this link, it refreshes the entire page instead of performing internal routing.

In the provided example, you can see the HTML string that I’m rendering to the DOM. Additionally, there are two links with the routeLink attribute that demonstrate internal routing (without page refresh). When you navigate to the /foo route and click on the rendered link (which should navigate to /bar), the entire page gets refreshed.

Is there a way to configure the rendering of this HTML content to enable internal routing instead of refreshing the entire page?

stackblitz demo

import { Component, inject } from '@angular/core';
import { bootstrapApplication } from '@angular/platform-browser';
import { provideRouter, RouterLink, RouterOutlet } from '@angular/router';
import 'zone.js';
import { DomSanitizer } from '@angular/platform-browser';

@Component({
  selector: 'foo',
  standalone: true,
  imports: [],
  template: `
    in foo!
    <div [innerHtml]="html"></div>
  `,
})
export class FooComponent {
  private sanitizer = inject(DomSanitizer);

  html = '';

  ngOnInit() {
    const htmlFromTheServer = `<h2>foo title</h2><a href="/bar">goto bar!</a>`;

    this.html = this.sanitizer.bypassSecurityTrustHtml(
      htmlFromTheServer
    ) as string;
  }
}

@Component({
  selector: 'bar',
  standalone: true,
  imports: [],
  template: `in bar!`,
})
export class BarComponent {}

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet, RouterLink],
  template: `
    <h1>Hello from {{ name }}!</h1>
    
    <a routerLink="/foo">/foo</a> <br>
    <a routerLink="/bar">/bar</a> <br>
    <hr>
    <router-outlet></router-outlet>
  `,
})
export class App {
  name = 'Angular';
}

bootstrapApplication(App, {
  providers: [
    provideRouter([
      { path: 'foo', component: FooComponent },
      { path: 'bar', component: BarComponent },
    ]),
  ],
});

react-bootstrap modal disappears without setting shoModal to false

I have a login Modal, from react-bootstrap, that when I fill the username and password and click on login, it disappears without waiting to showLoginModal to be set to false. This is the component:

import { Modal } from 'react-bootstrap'
const AccountsMenu: React.FC = () => {
    const dispatch = useDispatch()
    const navigate = useNavigate()
    const accounts = useSelector((state: RootState) => state.accounts)
    const location = useLocation()
    const getCurrentPath = () => location.pathname + encodeURIComponent(location.search)
    useEffect(() => {
        dispatch(getUserInfoAction())
    }, [dispatch])
    
    const registerPage = () => {
        navigate(ROUTES.REGISTER_ROUTE)
    }
    const [showLoginModal, setShowLoginModal] = useState(false)
    const [username, setUsername] = useState<string>('')
    const [password, setPassword] = useState<string>('')
    const [usernameError, setUsernameError] = useState<string>('')
    const [passwordError, setPasswordError] = useState<string>('')
    const login = () => {
        // Check if username and password are not empty
        if (!username.trim()) {
            setUsernameError('Username cannot be empty.')
            return
        } else {
            setUsernameError('')
        }

        if (!password.trim()) {
            setPasswordError('Password cannot be empty.')
            return
        } else {
            setPasswordError('')
        }
        dispatch(actions.loginUser({ username: username, password: password }))
        setUsername('')
        setPassword('')
    }
    useEffect(() => {
        if (accounts.apiSuccess) {
            setShowLoginModal(false)
        }
    }, [accounts.apiSuccess])
    if (accounts.loading) return <li>Loading ...</li>
    return (
        <li className="nav-item dropdown">
            <a className="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                Account
            </a>
            <ul className="dropdown-menu">
                {accounts.userInfo.is_active ? (
                    <li>
                        <a href={'/b/logout?next=' + getCurrentPath()} className="dropdown-item">
                            Logout
                        </a>
                    </li>
                ) : (
                    <>
                        <li>
                            <a href={'/b/login?next=' + getCurrentPath()} className="dropdown-item">
                                Login
                            </a>
                        </li>
                        <li>
                            <button onClick={() => registerPage()} className="dropdown-item">
                                Register
                            </button>
                        </li>
                        <li>
                            <button onClick={() => setShowLoginModal(true)} className="dropdown-item">
                                Login modal
                            </button>
                        </li>
                    </>
                )}
            </ul>
            <Modal show={showLoginModal} onHide={() => setShowLoginModal(false)} centered={true}>
                <div className="d-flex justify-content-center m-3">
                    <ErrorHandling error={accounts.error} loading={accounts.loading} />
                </div>
                <form className="p-4">
                    <div className="form-outline mb-4">
                        <label className="form-label" htmlFor="username">
                            User name:
                        </label>
                        <input
                            type="text"
                            id="username"
                            className={`form-control ${usernameError ? 'is-invalid' : ''}`}
                            value={username}
                            onChange={(e) => {
                                setUsername(e.target.value)
                                setUsernameError('')
                            }}
                        />
                        {usernameError && <div className="invalid-feedback">{usernameError}</div>}
                    </div>
                    <div className="form-outline mb-4">
                        <label className="form-label" htmlFor="password">
                            password:
                        </label>
                        <input
                            type="password"
                            id="password"
                            className={`form-control ${passwordError ? 'is-invalid' : ''}`}
                            value={password}
                            onChange={(e) => {
                                setPassword(e.target.value)
                                setPasswordError('')
                            }}
                        />
                        {passwordError && <div className="invalid-feedback">{passwordError}</div>}
                    </div>
                    <div className="form-outline mt-5 text-center">
                        <button type="button" className="btn btn-primary" onClick={() => login()}>
                            Login
                        </button>
                    </div>
                </form>
            </Modal>
        </li>
    )
}

I have tried the following so far:

  1. I have changed the login button type to ‘button’ instead of ‘submit’ to prevent the form from refreshing the page.
  2. I tried using div tag instead of form tag, still it behaved the same.
  3. I tried moving the login button outside the form, but still, the same behavior.

I searched for similar questions, but none addressed this issue.

bootstrap 5 carousel play pause button function

Using jQuery, how do create play/pause on same button on clicking in bootstrap 5 carousel

**HTML **

<div id="customSlider" class="carousel slide" data-bs-ride="carousel" data-bs-interval="2500">
    <div class="container ">
        <div class="carousel-indicators customSlider-indi">
            <a data-bs-target="#customSlider" data-bs-slide-to="0" class="active" aria-current="true" aria-label="Lorem 1">
                <span class="banner-label">Lorem 1</span></a>
            <a data-bs-target="#customSlider" data-bs-slide-to="1" aria-label="Lorem 2">
                <span class="banner-label">Lorem 2</span>
            </a>
            <a data-bs-target="#customSlider" data-bs-slide-to="2" aria-label="Lorem 3">
                <span class="banner-label">Lorem 3</span>
            </a>
            <a data-bs-target="#customSlider" data-bs-slide-to="3" aria-label="Lorem 3">
                <span class="banner-label">Lorem 4</span>
            </a>
            <a id="playBtn" data-cplay="true" class="play-btn play">
                <span class="icon-pause">&nbsp;</span>
                <span class="playPauseText">Pause</span>
            </a>
            <!--         <a class="btn  play">Play</a>
          <a class="btn stop">Stop</a> -->
        </div>
    </div>
    <div class="carousel-inner">
        <div class="carousel-item active">
            <img src="http://placehold.it/1440x500/210471?text=image_1" class="d-block w-100" alt="...">
            <div class="container">
                <div class="custom-cap">
                    <h5>Lorem ipsum</h5>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum maxime aut optio? Est eum laudantium qui aliquam tenetur mollitia, officiis enim laboriosam amet sapiente illum autem maxime molestias, sed ullam!</p>
                </div>
            </div>
        </div>
        <div class="carousel-item">
            <img src="http://placehold.it/1440x500/210471?text=image_2" class="d-block w-100" alt="...">
            <div class="container">

                <div class="custom-cap">
                    <h5>Lorem ipsum</h5>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum maxime aut optio? Est eum laudantium qui aliquam tenetur mollitia, officiis enim laboriosam amet sapiente illum autem maxime molestias, sed ullam!</p>
                </div>
            </div>
        </div>
        <div class="carousel-item">
            <img src="http://placehold.it/1440x500/210471?text=image_3" class="d-block w-100" alt="...">
            <div class="container">
                <div class="custom-cap">
                    <h5>Lorem ipsum</h5>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum maxime aut optio? Est eum laudantium qui aliquam tenetur mollitia, officiis enim laboriosam amet sapiente illum autem maxime molestias, sed ullam!</p>
                </div>
            </div>
        </div>
        <div class="carousel-item">
            <img src="http://placehold.it/1440x500/210471?text=image_4" class="d-block w-100" alt="...">
            <div class="container">
                <div class="custom-cap">
                    <h5>Lorem ipsum</h5>
                    <p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum maxime aut optio? Est eum laudantium qui aliquam tenetur mollitia, officiis enim laboriosam amet sapiente illum autem maxime molestias, sed ullam!</p>
                </div>
            </div>
        </div>
    </div>
</div>

style


.play-btn {
    width: 38px;
    height: 38px;
    border-radius: 5px;
    background: 0 0;
    position: relative;
    -webkit-box-shadow: none;
    box-shadow: none;
    border: 1px solid rgba(255, 255, 255, .3);
    padding: 0;
    -webkit-transition: all .3s ease;
    -o-transition: all .3s ease;
    transition: all .3s ease;
    overflow: hidden;
}

.play-btn .icon-pause {
    width: 8px;
    height: 12px;
    border-left: 2px solid #fff;
    border-right: 2px solid #fff;
    position: absolute;
    left: 14px;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
}


.play-btn .playPauseText {
    left: 30px;
    opacity: 0;
    position: absolute;
    top: 50%;
    -webkit-transform: translateY(-50%);
    -o-transform: translateY(-50%);
    transform: translateY(-50%);
    font-weight: var(--ds-font-500);
    font-size: var(--ds-font-16);
    line-height: 1.4;
    color: #fff;
    -webkit-transition: all .3s ease;
    -o-transition: all .3s ease;
    transition: all .3s ease;
}

.play-btn:is(:hover, :focus) {
    width: 85px;
}

.play-btn:is(:hover, :focus) .playPauseText {
    opacity: 1;
}

.banner-label {
    color: #fff;
    position: relative;
    bottom: -5px;
    padding: 0px 3px;
}

.customSlider-indi {
    background: transparent;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    align-content: center;
    flex-wrap: wrap;
    gap: 10px;
    bottom: 20px;
    padding: 0px 20px;
}

.customSlider-indi [data-bs-target] {
    flex: none;
    font-size: var(--ds-font-16);
    text-indent: 0;
    width: auto;
    background: transparent;
    position: relative;
    color: #fff;
    margin: 0;
    height: 36px;
    display: inline-block;
    border: 0px !important;
    align-items: center;
}

.customSlider-indi [data-bs-target]:is(:hover, :focus) {
    color: #fff;
}

.customSlider-indi [data-bs-target]::after {
    content: "";
    width: 100%;
    height: 3px;
    bottom: 0;
    padding: 0;
    position: absolute;
    display: block;
    cursor: pointer;
    border-radius: 2px;
    background-color: #fff;
    transition: opacity .6s ease
}

.custom-cap {
    position: absolute;
    height: 100%;
    width: 100%;
    top: 0;
    z-index: 1;
    display: flex;
    align-items: flex-start;
    flex-direction: column;
    justify-content: center;
    flex-wrap: wrap;
    color: #fff;
}

.custom-cap h5 {
    font-family: var(--ds-font-300);
    font-size: 56px;
    color: var(--ds-white);
}

.custom-cap p {
    font-size: var(--ds-font-22);
    font-family: var(--ds-font-300);
    color: var(--ds-white);
}

script

var myCarousel = document.querySelector('#customSlider');
    var carousel = new bootstrap.Carousel(myCarousel);

    $('#playBtn').click(function () {
        if ($(this).data('cplay') == "true") {
            $(this).data('cplay', 'false');
            $(this).removeClass("play");
            $(this).addClass("stop");
            $(this).find(".playPauseText").text("Pause");

            document.querySelector('.stop').addEventListener('click', function () {
                e.preventDefault();
                carousel.pause();
            });
        }
        else {
            $(this).addClass("play");
            $(this).data('cplay', 'true');
            $(this).removeClass("stop");
            $(this).find(".playPauseText").text("Play");

            document.querySelector('.play').addEventListener('click', function () {
                e.preventDefault();
                carousel.cycle();
            });
        }
    });

I would like to have the carousel play on load, and have a pause/play button to control it.

I have tried, and for some reason I cannot seem to get the button to pause on “pause” click, and resume play when “play” clicked.

please help me solve using jQuery or JS

React Query error when making axios request

I am having trouble with this error message every time I try to send an axios request to fetch data.
Starting with v5, only the “Object” form is allowed when calling query related functions. Please use the error stack to find the culprit call.

I am still learning react so I’m currently unable to find the culprit through the dev tools.

This is the topmost component where I called the react query provider

App.js

import {QueryClient, QueryClientProvider} from '@tanstack/react-query';

function App() {
const client = new QueryClient();

return(
<div>
<QueryClientProvider client={client}>
    <ReactQuery/>
</QueryClientProvider>
</div>
);
};

This is the component – React Query

import {BrowserRouter as Router, Routes, Route, Link} from 'react-router-dom';
import Navbar4 from './Navbar4';
import ReactHome from './pages/ReactHome';
import ReactProfile from './pages/ReactProfile';
import About from './pages/About';

const ReactQuery = () => {
  return (
    <div>
        <h4>React Query</h4>
        <Router>
        <Navbar4/>
            <Routes>
                <Route path='/' element={<ReactHome/>}/>
                <Route path='/reactProfile' element={<ReactProfile/>}/>
                <Route path='about' element={<About/>}/>
            </Routes>
        </Router>
    </div>
  )
}

export default ReactQuery;

And this is the “ReactHome” component, where I submit the request.

ReactHome.js

import React from 'react';
import {useQuery} from '@tanstack/react-query';
import Axios from 'axios';

const ReactHome = () => {
    const {data} = useQuery(['cat'], () => {
        return Axios.get("https://catfact.ninja/fact").then((res) => res.data);
    });

    return (
        <div>
            <p>React Home - {data.fact}</p>

        </div>
    )
}

export default ReactHome;

I am trying to use react query to make an axios request to an API. I keep getting errors whenever I do so

How to do mathematics when “=” button is pressed?

When creating a calculator generally using a switch statement works for adding,subtracting etc, in this scenario I am not sure where the Switch statement would go or if its needed, so that the calculator can do its mathematics?

const screen = document.getElementById('screen');
const btn = document.querySelectorAll('.btn');
for (const btns of btn) {
  //press button by index
  btns.addEventListener("click", (num) => {
    const numValue = num.target.innerText;
    const textNode = document.createTextNode(numValue);

    if(numValue === "="){
      
    }

    screen.appendChild(textNode)
    
  });
  
}
switch(numValue){
      case "+":
        num + num
        break;
      case "-":
        num - num
        break;
      case "/":
        num / num
        break;
      case "*":
        num * num
        break;
      case "*":
        num - num
        break;
      default:
        console.log("Error")
    }
<div id="screen"></div>
<div>
<button class="btn">+</button>

Javascript within HTML within Javascript within HTML

I want to nest tags within other tags in order to enable or disable a download button for a chat bot. However, nesting tags is not allowed. Is there an alternative way to accomplish this? Below is my full HTML file.

{% extends "layout.html" %}
{% block content %}

<!-- Begin page content -->
  <div class="overflow-auto">
    <br>
    <br>

    <div id="list-group" class="list-group w-auto">
      <a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">                                                           
                    <img src="https://digital-practice.ams3.cdn.digitaloceanspaces.com/static%2Fapp%2Fimg%2Fopenai-logo.png" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0"> 
                    <div class="d-flex gap-2 w-100 justify-content-between">
                      <div>
                        <p class="mb-0 opacity-75">How may I help you?</p>
                      </div>
                    </div>
      </a>
    </div>
    <div class="input-group mb-3">
      <textarea id="chat-input" class="form-control custom-control" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>
      <span id="gpt-button" class="input-group-asson btn btn-primary">Ask ChatGPT</span>

    </div>
  </div>
  

  <script src="https://code.jquery.com/jquery-3.6.3.min.js" integrity="sha256-pvPw+upLPUjgMXY0G+8O0xUf+/Im1MZjXxxgOcBQBXU=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-w76AqPfDkMBDXo30jS1Sgez6pr3x5MlQ1ZAGC+nuZB+EYdgRZgiwxhTBTkF7CXvN" crossorigin="anonymous"></script>

  <script>

    $("#gpt-button").click(function(){
    chat();
    });

    $("#chat-input").keypress(function(event){  
    if(event.which==13){
        chat();
    }
    });


    
    function chat(){
    var question = $("#chat-input").val();
    console.log(true);  
    $("#chat-input").val('');

    let html_data = '';
    html_data += `<a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">
        <img src="{{ url_for('static', filename='images/ai4eic-logo.png') }}" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">
        <div class="d-flex gap-2 w-100 justify-content-between">
          <div>
            <p class="mb-0 opacity-75">${question}</p>
          </div>
        </div>
      </a>`;
    $("#chat-input").val('');
    $("#list-group").append(html_data);

    $.ajax({
        type: "POST",
        url: "/chat",
        data: {'prompt': question},
        success: function (data) {

        let gpt_data = '';
        gpt_data += `
               <script>
               let butt=document.getElementById("download-button");         
               if((data.answer).includes("python")){
                   butt.classList.add("fadeIn");
                   butt.disabled = false;
               }
               </script>

               <style> 
                       p{word-break: break-all;
                         white-space:normal;} 

                       #download-button {
                         transition: opacity 1s;
                         opacity: 0;
                        }

                       #download-button.fadeIn {
                         opacity: 1;
                         }
                </style>       


           <a href="#" class="list-group-item list-group-item-action d-flex gap-3 py-3">
                    <img src="https://digital-practice.ams3.cdn.digitaloceanspaces.com/static%2Fapp%2Fimg%2Fopenai-logo.png" alt="twbs" width="32" height="32" class="rounded-circle flex-shrink-0">  
                    <div class="d-flex gap-2 w-100 justify-content-between">
                      <div class="a">                                                           
                        <p class="mb-0 opacity-75">${data.answer}</p>    
                        <button type="button" disabled="true" id="download-button" class="btn btn-primary">Download Code</button>                
                      </div>                                                          
                    </div>                                                            
                  </a>`;
        $("#list-group").append(gpt_data);
        }
    });
    };

    </script>
 

  {% endblock content %}

The problematic code block is the one that includes

<script>
       let butt=document.getElementById("download-button");         
       if((data.answer).includes("python")){
             butt.classList.add("fadeIn");
             butt.disabled = false;
        }
</script>

I tried putting the script into a separate .js file and calling the .js file from the HTML file. However, that does not seem to work, I think because the Javascript code calls private class properties such as #chat-input, etc.

Desired Email authorization in Google OAuth 2

I know how to use Google OAuth 2 in Node.js but I want to enable authorization just for desired email (prompt containing just specific email). I know that I can validate on callback but it would not be effective if end-user is continuously using another email-id so how can I enable it for Gmail API when authorization process starts?

change an image once after a number of minutes

I want to change id=”ads1″ – id=”ads6″ with a different image that I set in java after 1 minute without random. but this code can run only id=”ads1″.

window.onload = function () {
  setTimeout(function () {
      document.getElementById("ads1").src = "./assets/ads1.jpg";
      document.getElementById("ads2").src = "./assets/ads2.jpg";
      document.getElementById("ads3").src = "./assets/ads3.jpg";
      document.getElementById("ads4").src = "./assets/ads4.jpg";
      document.getElementById("ads5").src = "./assets/ads5.jpg";
      document.getElementById("ads6").src = "./assets/ads6.jpg";
      console.log("The image changed after 1 minute (60000 ms)");
  }, 60000);
}
            <div>
<img id="ads1" src="./assets/image.jpg" alt="">
<img id="ads2" src="./assets/image.jpg" alt="">
<img id="ads3" src="./assets/image.jpg" alt="">
<img id="ads4" src="./assets/image.jpg" alt="">
<img id="ads5" src="./assets/image.jpg" alt="">
<img id="ads6" src="./assets/image.jpg" alt="">
            </div>

How Do I Prevent Children/Sub Divs from Being Cut/Split Using Html2Canvas/PDF?

I’m trying to create a button that when clicked downloads the html website in a PDF form but using HTML2Canvas causes the divs to be split/cut off when going to the next page. Instead of the divs being cut, I’d like for the divs to go to the new page whenever it’s about to be cut.

 const saveAsPDF = () => {
    const cardElement = document.getElementById("container-to-print");

    if (!cardElement) {
        return;
    }

    html2canvas(cardElement).then((canvas) => {
        const imgData = canvas.toDataURL("image/jpeg");

        if (!imgData) {
            return;
        }

        const pdf = new jsPDF();
        const imgWidth = pdf.internal.pageSize.getWidth();
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        const pageHeight = pdf.internal.pageSize.getHeight();

        // Calculate the number of pages needed
        const totalPages = Math.ceil(canvas.height / pageHeight);

        // Add pages with images
        for (let i = 0; i < totalPages; i++) {
            if (i > 0) {
                pdf.addPage();
            }
            const position = i * pageHeight;
            pdf.addImage(imgData, "JPEG", 0, -position, imgWidth, imgHeight);
        }

        pdf.save("download.pdf");
    });
};

I’ve tried using ReactPDF but it seems to be impractical for my React project as it’s many nested divs I have to add the tags (like , etc) too.

The current solution just adds blank pages and causes the children divs to be cut.

Redux initialstate is has values, but it shows null, Why?

I’ve been getting this error where, I have set the initialState of redux with a value, but while debugging it shows it’s value is null. I’m using Redux Dev tools to check the values.
And also while adding data inside the initialState it throws an error Uncaught TypeError: Cannot read properties of null (reading ‘push’)

Here’s my code:
Store.js

import { configureStore } from "@reduxjs/toolkit";
import { persistStore, persistReducer } from "redux-persist";
import storage from "redux-persist/lib/storage";

import authReducer from "../feature/auth/auth.js";

const persistConfig = {
  key: "root",
  storage,
};

const persistedReducer = persistReducer(persistConfig, authReducer);

export const store = configureStore({
  reducer: {
    auth: persistedReducer, // Use the persisted reducer here
  },
});

export const persistor = persistStore(store);

Feature.js

import { createSlice } from "@reduxjs/toolkit";

const initialState = {
    cookies: [{value: 'test'}]
};

const authSlice = createSlice({
    name: "auth",
    initialState,
    reducers: {
        setCookies: (state, action) => {
           const data = {
                value: action.payload.value
           }
           state.cookies.push(data)
        },
        removeCookies: (state) => {
            state.cookies = [];
        }
    },
});

export const { setCookies, removeCookies } = authSlice.actions;
export default authSlice.reducer;

And This is how I’m trying to add cookies

import { useDispatch } from "react-redux";
import { setCookies } from "../feature/auth/auth";


function About(){

    const dispatch = useDispatch()
    const handleCookies = () => {
        dispatch(setCookies({value: 'test'}))
    }
    return(
        <div>
            <h1>About</h1>
            <p>This is the about page</p>
            <button onClick={handleCookies}>Add Cookeis</button>
        </div>
    )
}
export default About;

Redux