How to access nested array in JSON array using javascript or jQuery?

I have a nested array which looks like the example code below.

I need to access a nested array within my JSON array.

But the issue is that I always get undefined!

var json = {
    "status": "OK",
    "tickets": {
        "open_tickets": [{
            "id": "2",
            "assets": [{
                "id": 2446,
                "age": 4,
    
            }]
        }, {
            "id": "3",
            "assets": [{
                "id": 244564646,
                "age": 28,
            }]

        }]
    }
};

for(i=0;i<json.tickets.open_tickets.length;i++){

var id = json.tickets.open_tickets[i].id;
var age = json.tickets.open_tickets[i].assets.age;

$('.holder').append('<p>'+id+' '+age+'</p>')
 

}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="holder">



</div>

The age variable is always undefined and I cant figure out why this is happening.

what am I doing wrong?

ReactJs pass props from great children to parent

Greetings to you all.

So I want do a password reset, and this is the flow. When a user clicks on the reset password Modal, a new modal screen is shown, to enter the email, when the user enter the email, a new screen to enter the OTP sent to the email is show, when the user enter the OTP, a new modal to create a new password is shown. Then finally after the chose a new password, he/she will be aksed to login ( a login modal is shown too).

So now is the the issue. The login expects some props.

login: boolean;
  toggleLoginModal: () => void;
  toggleRegisterModal: () => void;

and they are typed

type LoginModalProps = {
  login: boolean;
  toggleLoginModal: () => void;
  toggleRegisterModal: () => void;
};

so how can I pass this data to the NewPassword.tsx file where the user will need to choose a new password, b4 the loginModal is shown?

In the NewPassword.tsx, when the user choose a new Password, I want to render the <LoginModal /> and pass the props to it.

Getting the props to pass down to it is now the issue.

Delete an item/element from localStorage

I want to be able to delete an item/element form localStorage. I can delete it before reloading. The removeButton removes the selected item form LocalStorage when clicked, it works just fine but once the page reloads, the button does not longer respond on the items saved in localStorage. Is there any way to make it work after reloading?

let ids1 = document.getElementById('ids')
let ids2 = document.getElementById('ids2')

let buttonCreateTask = document.getElementsByClassName('create')
let newd = document.getElementsByClassName('newd')

let prevContent = localStorage.getItem('saved');
if (prevContent) { newd[0].innerHTML = prevContent}

function createTask (){ 

let paro = document.createElement('p')
paro.innerText = ids1.value + 'n' + ids2.value

let removeButton = document.createElement('button')
removeButton.innerHTML = 'REMOVE' 

paro.appendChild(removeButton)

removeButton.onclick = function() {
    paro.remove()
    localStorage.setItem('saved',  newd[0].innerHTML)
   
}

if(ids1.value !== ''){ 
    if(ids2.value !== ''){ 
        
        newd[0].appendChild(paro)
ids1.value = ''
ids2.value = ''

localStorage.setItem('saved',  newd[0].innerHTML) 

    }else {
       alert('missing description')
    }
}else {
     alert('missing value')
}

buttonCreateTask[0].addEventListener('click', createTask )

I have tried adding an if statement on removeButton since the items are store in prevContent in order to display if they are not deleted when the page reloads but it does not remove it

remove.onclick = function() {
    if(paro){ 
    paro.remove()
    localStorage.setItem('saved',  newd[0].innerHTML)
    if(prevContent !== ''){
       delete prevContent      
    }
    }
}

Flickering textures after transform (WebGL2)

In WebGL2, I have textures (sprites) that move across the screen. With a standard orthographic projection matrix, there is no flickering. When I add transformation (rotation + scaling) to the matrix, the textures starts to flicker and become more “restless”. Why is this?

The transformation is only used for positioning the sprites. After adding the positioning/translation, I perform the opposite transformation to regain the original sprite shape.

In the snippet below, you can toggle transform on and off by clicking at the screen. When transform is on, the flickering is most visible at the top of the sprite. It’s even more pronounced in my app.

Is the issue due to sub-pixel rounding errors, because the sprite isn’t positioned at a screen pixel position? If so, how can I fix it?

let transform = false;
let scaleX = 1;
let scaleY = 0.7;
let rotation = 30 * Math.PI/180;

// Setup WebGL
const canvas = document.getElementById('canvas');
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;
const gl = document.getElementById('canvas').getContext('webgl2');
gl.clearColor(0, 0, 0, 0.0);
    
const vs =
    `#version 300 es
    precision highp float;

    in vec2 a_position;
    in vec2 a_texcoord;
            
    uniform mat4 u_matrix;
            
    out vec2 v_texcoord;
            
    void main() {
      gl_Position = u_matrix * vec4(a_position, 0.0, 1.0);

      v_texcoord = a_texcoord;
    }`;
    
const fs =
    `#version 300 es
    precision highp float;
            
    in vec2 v_texcoord;
            
    uniform sampler2D u_texture;
 
    out vec4 outColor;
            
    void main() {
        outColor = texture(u_texture, v_texcoord);
    }`;

// Setup program with shaders
const program = gl.createProgram();

const vertexShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertexShader, vs);
gl.compileShader(vertexShader);
gl.attachShader(program, vertexShader);

const fragmentShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragmentShader, fs);
gl.compileShader(fragmentShader);
gl.attachShader(program, fragmentShader);

gl.linkProgram(program);
gl.useProgram(program);

if (!gl.getShaderParameter(vertexShader, gl.COMPILE_STATUS)) {
    console.error('ERROR compiling vertex shader', gl.getShaderInfoLog(vertexShader))
};
if (!gl.getShaderParameter(fragmentShader, gl.COMPILE_STATUS)) {
    console.error('ERROR compiling fragment shader', gl.getShaderInfoLog(fragmentShader))
};

// Setup attributes
const positionLoc = gl.getAttribLocation(program, 'a_position');
const texcoordLoc = gl.getAttribLocation(program, 'a_texcoord');

// Setup uniforms
const matrixLoc = gl.getUniformLocation(program, 'u_matrix');
const textureLoc = gl.getUniformLocation(program, "u_texture");

const vao = gl.createVertexArray();
gl.bindVertexArray(vao);

// Create position buffer
const positionBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
const positionData = new Float32Array([
  0, 0,
  0, 1,
  1, 0,
  1, 0,
  0, 1,
  1, 1
]);

gl.bufferData(gl.ARRAY_BUFFER, positionData, gl.STATIC_DRAW);
gl.enableVertexAttribArray(positionLoc);
gl.vertexAttribPointer(
    positionLoc, // attribute
    2,           // size
    gl.FLOAT,    // type
    false,       // normalize
    0,           // stride
    0);          // offset

// Create texcoord buffer
const texcoordBuffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, texcoordBuffer);
const texcoords = new Float32Array([
    0, 0,
    0, 1,
    1, 0,
    1, 0,
    0, 1,
    1, 1,
]);

gl.bufferData(gl.ARRAY_BUFFER, texcoords, gl.STATIC_DRAW);
gl.enableVertexAttribArray(texcoordLoc);
gl.vertexAttribPointer(
    texcoordLoc,  // attribute
    2,                          // size
    gl.FLOAT,                   // type
    true,                       // normalize
    0,                          // stride
    0);                         // offset

// Setup texture
let tex = gl.createTexture();
gl.bindTexture(gl.TEXTURE_2D, tex);
gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([0, 0, 255, 255]));

gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);

let texWidth;
let texHeight;
let img = new Image();
img.addEventListener('load', function() {
    texWidth = img.width;
    texHeight = img.height;
    gl.bindTexture(gl.TEXTURE_2D, tex);
    gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, img);
    gl.generateMipmap(gl.TEXTURE_2D);
    requestAnimationFrame(render);
});

img.src = 'https://i.imgur.com/3VirGxb.png';
img.crossOrigin = 'anonymous';

const draw = function() {
    gl.viewport(0, 0, gl.canvas.width, gl.canvas.height);
    gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
  
    let matrix = new Float32Array([
        2 / gl.canvas.width, 0, 0, 0,
        0, -2 / gl.canvas.height, 0, 0,
        0, 0, 1, 0,
        -1, 1, 0, 1
    ]);
  
    if (transform === true) {
        matrix = m4.scale(matrix, scaleX, scaleY, 1);
        matrix = m4.zRotate(matrix, rotation)
    };
    
    matrix = m4.translate(matrix,
        dstX,
        dstY,
        0);
  
    if (transform === true) {
        matrix = m4.zRotate(matrix, -rotation)
        matrix = m4.scale(matrix, scaleX, 1/scaleY, 1);
    };
    
    // Scale unit squad from 1x1 to texWidth and texHeight
    matrix = m4.scale(matrix, texWidth, texHeight, 1);
  
    gl.uniformMatrix4fv(matrixLoc, false, matrix);
    
    let texUnit = 0;
    gl.uniform1i(textureLoc, texUnit);
    gl.activeTexture(gl.TEXTURE0 + texUnit);
    gl.bindTexture(gl.TEXTURE_2D, tex);
    
    gl.drawArrays(
      gl.TRIANGLES, // method
      0,            // offset
      6,            // number of vertices per instance
      1             // number of instances
);           
}

let dstX = 100;
let dstY = gl.canvas.height/2;
let incX = 1;
let incY = 1;

const update = function() {
    dstX += incX;
    dstY += incY;
    if (dstX < 0) {
      incX = 1;
    }
    if (dstX >= gl.canvas.width - texWidth) {
      incX = -1;
    }
    if (dstY < 0) {
      incY = 1;
    }
    if (dstY >= gl.canvas.height - texHeight) {
      incY = -1;
    }
}

const render = function() {
    update();
    draw();
    requestAnimationFrame(render);
};

document.addEventListener('click', function(event) {
    if (transform === true) {
        transform = false;
        document.getElementById('header').textContent = 'Transform off (click to change)';
    } else if (transform === false) {
        transform = true;
        document.getElementById('header').textContent = 'Transform on (click to change)';
        }
});
body {
  margin: 0;
}

h1 {
  font-family: arial;
  position: absolute;
  margin: 0;
}
<h1 id="header">Transform off (click to change)</h1>
<canvas id="canvas"></canvas>
<script src='https://webgl2fundamentals.org/webgl/resources/m4.js'></script>

Resetting Chosen JQuery dropdowns

So I have multiple dropdowns which are dependent on each other. When the button is clicked, it will do something if each dropdown has a value to it and it will also clear out the options and regenerate the options for chosen-province. If the user misses a dropdown, it will prompt them the message until all the options are selected. However, after the dropdowns are reset, the dialog box will appear again even if i have selected all the options and if i miss one dropdown, the dialog box will appear multiple times


   $(".chosen-province")
                     .chosen()
                     .change(function () {
                       var provoption = [$("#ProvinceSelect2").val()];
                       var provresult = "'" + provoption.join("','") + "'";
                       // function which creates option for chosen-region using chosen-province
                       $(".chosen-region")
                         .chosen()
                         .change(function () {
                           var cityoption = [$("#RegionSelect").val()];
                           var cityresult = "'" + cityoption.join("','") + "'";
                           //function which creates open for chosen-sitestat using chosen-region val
                         });
   
                       $(".chosen-sitestat")
                         .chosen()
                         .change(function () {
                           var statopt = [$("#SiteStatusSelect").val()];
                           var statresult = "'" + statopt.join("','") + "'";
                           // function which creates options for chosen-siteclass using chosen-sitestat val
                         });
                       var flag = false;
                       document
                         .getElementById("button")
                         .addEventListener("click", () => {
                           var regionlst = [];
                           var Statuslst = [];
                           var provincelst = [];
                           var classlst = [];
                           regionlst.push($(".chosen-region").val());
                           Statuslst.push($(".chosen-sitestat").val());
                           provincelst.push($(".chosen-province").val());
                           classlst.push($(".chosen-siteclass").val());
                           var regionElem = regionlst.pop();
                           var statusElem = Statuslst.pop();
                           var provinceElem = provincelst.pop();
                           var classElem = classlst.pop();
   
                           var regionExp = "'" + regionElem + "'";
                           var statusExp = "'" + statusElem + "'";
                           var provinceExp = "'" + provinceElem + "'";
                           var classExp = "'" + classElem + "'";
                           if (
                             regionElem != "" &&
                             statusElem != "" &&
                             provinceElem != "" &&
                             classElem != ""
                           ) {
                             if (
                               regionElem == "All" &&
                               statusElem == "All" &&
                               classElem == "All"
                             ) {
                               //do something
                             } else if (
                               statusElem == "All" &&
                               classElem == "All" &&
                               regionElem != "All"
                             ) {
                               var url =
                                 // do something 
                             } else if (
                               statusElem != "All" &&
                               classElem == "All"
                             ) {
                               // do something
                             } else if (statusElem != "All" &&
                               classElem != "All" &&
                               regionElem != "All" && provinceElem != 'All'){
                               // do something
                             }
                           }
                           else {
                           if (
                             regionElem == "" ||
                             statusElem == "" ||
                             provinceElem == "" ||
                             classElem == ""
                           ) {
                             $.confirm({
                                 title: `Cannot Download Site Log!`,
                                 content: `No records meets the filtering criteria`,
                                 boxWidth: "25%",
                                 useBootstrap: false,
                                 buttons: {
                                   ok: function () {},
                                 },
                               });
                               return;
                             }
                             
                         }
                         regionlst.length=0; 
                         Statuslst.length=0;
                         provincelst.length=0;
                         classlst.length=0;
                         $('.chosen-region').empty()
                         $('.chosen-region').trigger("chosen:updated");
                         $('.chosen-sitestat').empty()
                         $('.chosen-sitestat').trigger("chosen:updated");
                         $('.chosen-siteclass').empty()
                         $('.chosen-siteclass').trigger("chosen:updated");
                         $('.chosen-province').empty()
                         $('.chosen-province').trigger("chosen:updated");

                         // function creates the options for chosen-province

                         
   
                         });
   
   
                     });


How can I access event variable outside of JSX component React.js?

I have a YouTube JSX component in my file.
All my imports are here:

import io from "socket.io-client";
import { useState, useEffect } from "react";
import YouTube, { YouTubeProps } from "react-youtube";
<YouTube
                    videoId={"di0MtYgeJNE"} // defaults -> ''
                    //id={string} // defaults -> ''
                    //className={string} // defaults -> ''
                    //iframeClassName={string} // defaults -> ''
                    //style={object} // defaults -> {}
                    //title={string} // defaults -> ''
                    //loading={string} // defaults -> undefined
                    //opts={obj} // defaults -> {}
                    //onReady={ready} // defaults -> noop
                    onPlay={(event) => {
                        console.log(event);
                        console.log(event.target);
                        console.log("now playing");
                        console.log(YouTube.PlayerState);
                        event.target.playVideo();
                        event.target.pauseVideo();
                        emitEvent(event); //emit play to backend here
                    }} // defaults -> noop
                    onPause={(event) => {
                        console.log("now pausing", event);
                        console.log(YouTube.PlayerState.BUFFERING);
                                                //emit pause to backend here
                    }
                    
                />

I want to be able to access the event related to this JSX component, so that I may call event.target.playVideo();

I’m listening to sockets in my useEffect() function and I want to call event.target.playVideo() in there depending on the socket msg I recieve.

my UseEffect function to listen to socket:(socket.io client)

useEffect(() => {
        socket.on("user-played", (data) => {
            console.log("other user clicked play: ");

            //call event.target.playVideo() here
        });
    }, [socket]);

Ideally the workflow would my client here emits(“play-video”). Then my backend registers that and emits that event back to client side. Then my client side would recieve(“user-played”) event and play the video with the play video function above.

Unfortunately I can’t just call that anywhere since i need access to the relevant event variable from my YouTube component, so I’m not sure the solution.

I’ve heard useRef() might work but I was having some trouble with it..although I might just be using it wrong. Any help is greatly appreciated!

Access Events from Elements created dynamically

I have 1 repository with 2 projects:

  • One in JS/node (we can call ProjectA)
  • One in Vue (we can call ProjectB)

Tree:

  • MainFolder
    • ProjectA
      • Src
        • fileA.js
    • ProjectB
      • src
        • file.vue

I have elements created on my projectA dynamically like:

var a = document.creatElement('i');
a.classList.add('....')
a.addEventListener(...)

Whenever a user CLICK this element, I change a boolean flag.

I also have the layout created in Vue. But I can’t access the flag value OR the element created dynamically (click event).

Is it possible to make these files talk to eachother?
Make a flag visible or capture the click event on my Vue file?

get the document id after creation in react with firebase

I’m creating an object with firebase to display it in the screen, but after the creation I will need its id in another page to show the object with more details (path example: /object/:id), so when I click the object, I need to take its id and send through the link to another page, and once I’m in the page I will query the id on the link to get the object like that:

query(collection(db, "objects"), where("objectId", "==", x))

and this is how im creating the object

<form onSubmit={(e) => {
        e.preventDefault()
        // checks if user is logged in
        onAuthStateChanged(auth, (user) => {
            if(user) {
                addDoc(collection(db, "objects"), {
                name: "my object",
                description: "a nice object",
                owner: user.uid,
                // objectId: x
            }).then((docRef) => {
                docRef.id // I need this to be in the objectId property
            })
        }})
    }}>

I would like to know if this is a good approach to this problem, since I will need this id later on the project I thought this was the best way to do it

Using chrome.webrequest api to authenticate that users are logged into my website in order to use my chrome extension

I have created a chrome extension and I am needing to authenticate that a user has logged into my website with their credentials in order to use my chrome extension. I am wanting to use a API call to my URL. This is the code I am trying to use. I am trying to figure out what else I would need to authenticate users logging in. Any suggestions?

const target = "https://exampleurl";

function observe(requestDetails) {
  console.log(`observing: ${requestDetails.requestId}`);
}

browser.webRequest.onAuthRequired.addListener(
  observe, {
    urls: [target]
  }
);

Subscribe Map and Observable

I am lost with this problem, not finding solution reading the doc or with some AI help.

I don’t know how to solve the error Angular is giving me.

I would like to be able to use data$?: Observable<Sessions>;

Currently, data$?: any; works but I want to link it to my model.

Here is my code:

export class Sessions {
        ID!: number;
        title!: string;
        device!: Device;
        browser!: string;
        color!: string;
        smartphone!: boolean;
    }
    export class Device{
        appversion! : string;
        deviceid! : number;
        deviceversion! : number;
        environment! : string;
        os! : string;
    }

import { Component, Input } from '@angular/core';
import { NavigationService } from '../../services/navigation.service';
import { SessionsService } from 'src/app/services/sessions.service';
import { map, Observable } from 'rxjs';
import { SessionsVM } from 'src/app/model/sessions-vm';
import { Sessions} from 'src/app/model/sessions';
import { fadeIn } from '../../helpers/animations'
import { DatabaseService } from 'src/app/services/database.service';
import { observableToBeFn } from 'rxjs/internal/testing/TestScheduler';

@Component({
  selector: 'app-creation-page',
  templateUrl: './creation-page.component.html',
  styleUrls: ['./creation-page.component.scss'],
  animations: [fadeIn]
})
export class CreationPageComponent {

  // isConnected: boolean = false;
  isSessionTitle: boolean = false;
  isQRCode: boolean = false;
  creationStarted: boolean = false;
  isNotCreatingNewSession = false;

  sessions$!: Observable<SessionsVM[]>;
  data$?: Observable<Sessions>;

  constructor (private navigationService: NavigationService, private sessionsService: SessionsService, private dataBase : DatabaseService) {
  }

  ngOnInit(): void {
    // this.navigationService.connectionStatusChanged.subscribe(() => {this.isConnected = this.navigationService.isConnected});
    this.navigationService.isQRCodeStatusChanged.subscribe(() => {this.isQRCode = this.navigationService.isQRCode});
    this.navigationService.isSessionTitleStatusChanged.subscribe(() => {this.isSessionTitle = this.navigationService.isSessionTitle});
    this.navigationService.creationStartedStatusChanged.subscribe(() => {this.creationStarted = this.navigationService.creationStarted});
    this.navigationService.isNotCreatingNewSessionStatusChanged.subscribe(() => {this.isNotCreatingNewSession = this.navigationService.isNotCreatingNewSession});
    this.sessions$ = this.sessionsService.getSession();

    this.dataBase.getSessions().snapshotChanges().pipe(
      map(changes =>
        changes.map(c =>
          ({ key: c.payload.key, ...c.payload.val() })
        )
      )
    ).subscribe(data => {
      this.data$ = data;
      console.log(this.data$);
    });
    
  }

  toRecordingPage() {
    this.navigationService.goToRecordingPage();
  }

  toCreatingNewSession() {
    this.navigationService.startCreatingNewSession();
    this.navigationService.startSessionCreation();
    this.navigationService.writeSessionTitle();
  }
}

And the error Angular 13 gives me:

Error: src/app/pages/creation-page/creation-page.component.ts:46:7 - error TS2740: Type '{ ID?: number | undefined; title?: string | undefined; device?: Device | undefined; browser?: string | undefined; color?: string | undefined; smartphone?: boolean | undefined; key: string | null; }[]' is missing the following properties from type 'Observable<Sessions>': source, operator, lift, subscribe, and 2 more.

46       this.data$ = data;

Thank you

Vite-plugin-pwa include assets

I have the following setup (I use vite-plugin-pwa with Laravel:

//vite.config.js
VitePWA({
    injectRegister: null,
    registerType: 'autoUpdate',
    strategies: 'injectManifest',
    srcDir: 'src',
    filename: 'sw.js',
    workbox: {
        globPatterns: ["**/*.{js,css,ico,png,svg,jpg}"],
        navigateFallback: '/'
    },
    manifest: false
})
// src/sw.js
import { clientsClaim } from 'workbox-core'
import { cleanupOutdatedCaches, precacheAndRoute } from 'workbox-precaching'

// self.__WB_MANIFEST is default injection point
precacheAndRoute(self.__WB_MANIFEST)

// clean old assets
cleanupOutdatedCaches()

self.skipWaiting()
clientsClaim()
//app.blade.php
<script>
    if('serviceWorker' in navigator) {
        window.addEventListener('load', () => {
            navigator.serviceWorker.register('/build/sw.js', {
                scope: '/'
            })
        })
    }
</script>
//nginx (Allow SW from non-root)
location ~ sw.js$ {
   add_header 'Service-Worker-Allowed' '/';
}
// Home.vue
<template>
    <section class="main relative p-52 bg-fixed bg-cover bg-no-repeat" :style="style">
        
    </section>
</template>
<script setup>
    import logo from '@assets/home/section_1.jpg'
    const style = `background-image: url(${logo})`
</script>

After running npm run build I can see in public/build/sw.js precache are created:

ce([{
    "revision": null,
    "url": "assets/Home-3e4d7957.js"
}, {
    "revision": null,
    "url": "assets/main-62bd5e77.js"
}, {
    "revision": null,
    "url": "assets/main-f3b0fe11.css"
}]);
ne();
self.skipWaiting();
A();

But the assets/home/section_1.jpg is missing from cache, how can I added assets files from src/assets to be included in sw.js cache?

How to crop an image with open sea dragon?

I have an image of maps and I want to be able to display each map based on a year inputted into a form. I figured out how to set a default zoom, but it doesn’t line up properly without cropping out parts of the image.

https://openseadragon.github.io/examples/ui-tiledimage-polygon-cropping/
I found this and tried it with predefined coords… but it doesn’t seem to work.. and I noticed from looking around that other people have had a similar problem.

I also saw that setClip() is an option that could work but couldn’t get it to work either. Any ideas of how to do this without cropping tons of items in a photo editor?

https://codepen.io/admaloch/pen/ZEMmGqO?editors=1011

const viewer = OpenSeadragon({
id: "openseadragon1",
showNavigator: true,
 prefixUrl: "/openseadragon/images/",
 tileSources: [
{
  type: "legacy-image-pyramid",
  levels: [
    {
      url: "https://www.floridamemory.com/FMP/maps/small/fmc0001.jpg",
      width: 1000,
      height: 733
    },
    {
      url: "https://www.floridamemory.com/FMP/maps/medium/fmc0001.jpg",
      width: 2500,
      height: 1832
    },
    {
      url: "https://www.floridamemory.com/FMP/maps/large/fmc0001.jpg",
      width: 4962,
      height: 3636
    }
  ]
}
]
});

viewer.addHandler("open", function () {
 const tiledImage = viewer.world.getItemAt(0);
 const imageRect = new OpenSeadragon.Rect(200, 80, 866, 826);
 const viewportRect = tiledImage.imageToViewportRectangle(imageRect);
 viewer.viewport.fitBounds(viewportRect, true);
});

Reset autopopulating dependent dropdowns using Chosen JQuery

I have three dropdowns which are dependent on the value selected from previous dropdown. I’m trying to reset them after clicking on the button but when I do, the values go away but i can still see the dropdown options. Is there a way to also clear the dropdown options except for the first dropdown?

I tried doing

$(‘chosen-select).val(”).trigger(“chosen:updated”)
$(‘chosen-select).empty()

How to select specific paragraph number using JQuery?

I want to select the second paragraph, and can I do that using JQuery but without using an id for the paragraph? Something like accessing a specific node.
I tried using $(“#p[1]”) or $(“#p”)[1] but it is not correct.
I based this logic on the var.childNodes[1]

<div id="info">
    <section>
        <div style="text-align: center">My Biography</div>
        <p>
            My name is JJ.
        </p>
        <p id="one">
            I moved to USA when I was 6 years old.
        </p>
        <button id="show">Show</button>
        <button id="hide">Hide</button>
    </section>
</div>
<script>
 $(document).ready(function () {
        $("#info").ready(change1())
        $("#show").click(function () {
            $("#one").css("visibility", "visible")
        })
        $("#hide").click(function () {
            $("#one").css("visibility", "hidden")
        })
    })

</script>