Click button using java script function

Hello All i am trying to click on world press image upload popup using java script function but its not working .

Select Files

hare is button code i have try
document.getElementById(“__wp-uploader-id-1”).click();

document.querySelector(“#__wp-uploader-id-1”).click();
image


Getting back the value of a `cleared` input element with React Select

I have a several ReactSelect components, and one piece of global state which is responsible for holding all my selected values in an array.

Select

      <Select
        styles={inputStyles}
        className="basic-single"
        classNamePrefix="select"
        isClearable={true}
        isSearchable={false}
        placeholder={'Select Your Most Convenient Time Slot'}
        options={newHoursArr}
        isMulti={false}
        onChange={(values) => handleChange(values)}

        defaultValue={clientServiceReferral.selectedTimeSlots.map((referral) => (
          referral.timeSlot === timeWithDate ? (
            { ['label']: referral.value, ['value']: referral.value }
          ) : null
        ))}
      />

handleChange function

  const handleChange = (value) => {

    const found = clientServiceReferral.selectedTimeSlots.find(element => element.timeSlot === timeWithDate);

    if (found) {
      clientServiceReferral.selectedTimeSlots.splice(found, 1)
    }

    const newValue = {
      timeSlot: timeWithDate,
      value: value.value
    }

    setClientServiceReferral({
      ...clientServiceReferral,
      selectedTimeSlots: [...clientServiceReferral.selectedTimeSlots, newValue]
    })
  }

ReactSelect has an isClearable prop. Which allows users to clear the input with a button click. This returns a value of null when values is logged in the onChange function, but is there a way to return the actual value inside the select that is getting cleared when the clear button is clicked?

An error occurred while loading the data of the collection file in MongoDB using the toArray() function

enter image description here

const express = require('express');
const app = express();
app.use(express.urlencoded({
    extended: true
}));
const MongoClient = require('mongodb').MongoClient;
app.set('view engine', 'ejs');

var db;

app.listen(8080, function () {
    console.log('listening on 8080');
});


app.get('/', function (req, response) {
    response.sendFile(__dirname + '/index.html');
});

app.get('/write', function (req, response) {
    response.sendFile(__dirname + '/write.html');
});


app.get('/list', function (req,response) {
    db.collection('post').find().toArray(function(err, results){
        console.log(results);
    });
    response.render('list.ejs');
});

i want to call my data from collection of mongodb database.

but i have a Typeerror “collection” undefined!

please help me!

enter image description here
i tried googling and i want to show my data to browser!

Draggable that changes opacity of 2 different elements

I wanted to implement a draggable element which increases the opacity of 2 different elements when you get close to them but I couldn’t figure out a way on how to detect whether if its left or right. I used GSAP or GreenSock Animation Plugin to make it work.

here’s whats happening

js

Draggable.create("#dragme", {type:"x,y",
    bounds:"container",
    edgeResistance:0.2,
    onDrag:adjustOpacity,
});

function adjustOpacity() {
  var distanceFromMaxX = this.x - this.maxX,
            distanceFromMinX = this.minX - this.x,
            distanceFromMaxY = this.y - this.maxY,
            distanceFromMinY = this.minY - this.y,
            opacityRange = 100,
            furthestDistance = Math.max(distanceFromMaxX, distanceFromMinX, distanceFromMaxY, distanceFromMinY),
            opacity = 0;
        if (furthestDistance > 0) {
            opacity = 0 + (Math.min(furthestDistance, opacityRange) / opacityRange);
        }
        TweenLite.set(left, {opacity:opacity});
}

I tried using the left and right elements as a bound but it doesnt work the way I intended

function adjustOpacity() {
  var ldistanceFromMaxX = this.x - this.maxX,
            ldistanceFromMinX = this.minX - this.x,
            ldistanceFromMaxY = this.y - this.maxY,
            ldistanceFromMinY = this.minY - this.y,

            rdistanceFromMaxX = this.x - this.maxX,
            rdistanceFromMinX = this.minX - this.x,
            rdistanceFromMaxY = this.y - this.maxY,
            rdistanceFromMinY = this.minY - this.y,
            
            opacityRange = 100,
            lfurthestDistance = Math.max(ldistanceFromMaxX, ldistanceFromMinX, ldistanceFromMaxY, ldistanceFromMinY),
            rfurthestDistance = Math.max(rdistanceFromMaxX, rdistanceFromMinX, rdistanceFromMaxY, rdistanceFromMinY),
            lopacity = 0.1,
      ropacity = 0.1;
        if (lfurthestDistance > 0) {
            lopacity = 0.1 + (Math.min(lfurthestDistance, opacityRange) / opacityRange);
        }
  else (rfurthestDistance > 0)
      ropacity = 0.1 + (Math.min(rfurthestDistance, opacityRange) / opacityRange);
      
    Tweenlite.set(leftDiv, {opacity:lopacity});
    Tweenlite.set(rightDiv, {opacity:ropacity});
}

Does Gsap changes fixed position property static on its own?

Am using gsap animation library in my react project, there is particular div which I animate when mouse enter event is fired on its parent element, I have set position of that element to fixed, before I add the gsap animation the div is not moving along with the rest of the Contents but after applying the animation that div is no longer fixed is moving along with rest of the content, please how can I make that element not to move or scroll with rest of the page? I also tried make the position of it to fixed with the gsap but my styles collapse, how can I solve the issue?

How can I destructure react query async return variables so that one of them doesn’t log undefined?

The Axios object doesn’t have a winnersData property, so destructuring it returns undefined in the original block of ocde. I need to destructure data from both Axios requests and what I call them later on needs to be different. I’m just not sure how to implement this and have been struggling for a while. My attempt below fails as well.

How can I implement this?

Original block of code:

async function fetchUploads(){
        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        };

        const {data} = await axios.get('http://localhost/api/get-user-uploads-data', {headers});
        return data;
    }

async function fetchWinners(){
        const headers = {
            "Accept": 'application/json',
            "Authorization": `Bearer ${authToken}`
        };

        const {winnersData} =  axios.get('http://localhost/api/choose-winners', {headers});
        return winnersData
    }

    const { data }        = useQuery('uploads', fetchUploads)
    const { winnersData } = useQuery('winners', fetchWinners)
    console.log(data); // logs data correctly
    console.log(winnersData); // logs undefined

    return(....);

Attempted fix for fetchWinners() I’ve tried but it failed:

async function fetchWinners(){
    const headers = {
        "Accept": 'application/json',
        "Authorization": `Bearer ${authToken}`
    };

    const { winnersData } =  axios.get('http://localhost/api/choose-winners', {headers});
    return { winnersData };
}



const { data }        = useQuery('uploads', fetchUploads)
const { data: { winnersData } } = useQuery('winners', fetchWinners)
console.log(data.winnersData); // still logs undefined

How to make a script when the button text appears, refresh the page

Hello forum users. Help me solve the problem, I need to make a script for Tampermonkey in, when with the text of the button to appear, it just refreshes the page, the button itself is visible in the screenshot, you need to make this button with the text.

The Js Path code of the button itself:

document.querySelector("#hcaptcha[enter image description here][1]-container-1648687012980 > div")

enter image description here

Declaring Javascript Functions in Script Tags

Could someone help me with a javascript question?

I have an HTML page that loads a javascript function through an Ajax call, the function is declared inside a script tag like this:

<script>
    function greet(){
       return 'Hello Word(1)';
    }
</script>

Through the Ajax call I fetch a snippet of HTML code on the server, and this HTML in turn contains this tag with the function in question.
Well, if I make 2 Ajax calls to get the same piece of HTML code on my page, it means that my greet() function will be declared twice, but the last declaration will override the first.

However, there is a detail, at each Ajax call, the function that is declared in the tag inside the HTML snippet, comes with a different return, for example: in the first Ajax call, the return of the greeting() function is declared to be the string ‘Hellow Word (1)’, in the second Ajax call, the same function comes with the return declared as ‘Hellow Word (2)’, in the third ajax call the same function comes with the return ‘Hellow Word ( 3)’, and so on.

The problem happens when I run the function after it is loaded on the page, in the first Ajax, I call the greeting() function and the return is exactly what I expected (‘Hellow Word (1)’), but when calling the function after the second Ajax, the return is still ‘Hellow Word(1)’, that is, it is as if the function has not been updated. And the most bizarre thing is that if I inspect the HTML using Chrome’s DevTools, I can see that the function is declared with the return being ‘Hellow Word (2)’, but when executing it the return comes from the first function . Could someone explain to me why this happens? Am I missing some default behavior of the language?

Raspberry Pi Server php does not work from outside local network

I have been making a small page on my server to display some photo albums. This is on an nginx server on a raspberry pi 4. When I try to access the page from my laptop or phone when they are on wifi, everything loads correctly. However, when I use my phone with LTE, for example, the php requests do not work. I checked with my laptop using my wireless hotspot and I had the same issue. I never get the “200” code that my browser is waiting for. I do not get an error either. It is as though the http request disappears. I have other pages on this same server where the php is working correctly, one of which is almost the exact same as this code. The php I am trying to use is one which returns file and album names as a long string. Expected output would be:

Siblings|Wyoming|Utah|Skiing|

This all works when accessed from my local network. In the past I have used much more elaborate php files to access security camera footage and also send shell scripts to turn a relay on and off. These worked from anywhere in the world, not just my network. I know very little about this stuff, so I’m hoping I am just missing something obvious that an expert can recognize immediately. 🙂 I will include my code below.

getfiles.php

<?php
    function clean_scandir($dir){
        return array_values(array_diff(scandir($dir),array('.','..')));
    }
    
    $directory = $_GET['dir'];
    $files = clean_scandir("/var/www/html/" . $directory);
    foreach($files as $file){
        $fileStr .= $file . "|";
    }
    echo $fileStr;
?>

And the javascript that is trying to use this php:

function getAlbums(){
    var xmlhttp = new XMLHttpRequest();     
    xmlhttp.onreadystatechange = function(){
        if(this.readyState == 4 && this.status == 200){
            console.log("return packet = " + this.response);
            var albumArray = this.response.split("|");
            albumArray.pop(); //remove empty last element
            for (var i = 0; i < albumArray.length; i++){
                console.log("album " + i + " = " + albumArray[i]);
            }
            getThumbnail(albumArray);
            setTimeout(() => { 
                populateAlbums(albumArray); //waits 1 sec for thumbnail requests to finish before loading thumbnails
            }, 1000);
            
        }
    }

    var urlString = "getfiles.php?dir=" + "photos/";
    xmlhttp.open("GET", urlString, true);
    xmlhttp.send();
}

The code never arrives at the console.logs that are within the big ‘if’ statement, I am assuming because the status never reaches 200. I do not get any other number like a 500 code. It just remains blank.

I have tried slowly modifying the php code. If the file is simply:

echo "php successful";

then it works. But for some reason the full code is causing issues. Sometimes the issues do not act the same each time either.

Appending fetched json data to a div

I have tried to create a client side function that sends a fetch request for json data and then appends the response to a div however it doesnt seem to be working.

here is the client side function code

function bobFun(){ 
  
  let response = fetch('http://127.0.0.1:3000/dylan/list', { mode: 'no-cors' })
    .then(console.log("fetch sent"))
    //.then(console.log(response))
    .then(response => {
  return response.text().then(text => {
    document.getElementById("test").append(text)
  });
});

here is the server side json data

let dylan = ['song recommendation 1',
  'song recommendation 2',
  'song recommendation 3',
];

app.get('/dylan/list', function(req, resp){
  resp.send(dylan);

Network request failed in react-native and expo

I have a flask server running on docker container. And it runs on port 5000 in container. I’ve mapped this docker container to my localhost:5000 port. I can display it on my browser so it works.

Now I want to send POST Request to that server endpoint /auth using fetch() in react native.

Here what I’ve tried so far:

 fetch("https://160.75.195.68:5000/auth",
          {
            method: 'POST',
            body: JSON.stringify({
                phone: phone,
                password: password
            }),
            headers: {
              "Content-Type": "application/json"
            }
          }
          ).then((response) => {
            console.log("RETURNED RESPONSE")
            console.log(response.data);
            deviceStorage.saveKey("id_token", response.data.access_token);
            deviceStorage.loadJWT(response.data.jwt);
            // this.props.newJWT(response.data.jwt);
          }).catch((error) => {
            if (error.response) {
              // There is an error response from the server
              // You can anticipate error.response.data here
              console.log("THERE IS AN ERROR RESPONSE FROM THE SERVER")
              const error = err.response.data;
              dispatch(addError(error.message));
            } else if (error.request) {
                // The request was made but no response was received
                // Error details are stored in error.reqeust
                console.log("THE REQUEST WAS MADE BUT NO RESPONSE WAS RECEIVED");
                console.log(error.request);
            } else {
                // Some other errors
                console.log("SOME OTHER ERRORS");
                console.log('Error', error.message);
            }
          })

But I get Network request failed. Please help!!

How to properly print out list of scores in order from highest to lowest in code.org/javascript?

I have function of “endgame” and here’s how the function goes

function endgame()  {
   setScreen("scorescreen");
  ismytimergoing = false;
  appendItem(scorelist, score);
  for (var i = 0; i < scorelist.length; i++) {
    if (scorelist[i] > scorelist[i +1]) {
      highestnumber = scorelist[i];
    } else if ((scorelist[i] == scorelist[i + 1])) {
      highestnumber = scorelist[i];
    } else {
      highestnumber = scorelist[i + 1];
    }
  }
  setText("scoretext", (scorelist + "  ") + namelist);
}

This is a fairly simple click button game and I have a loop which increases the score after each click, different amounts depending on how much the score currently is.

    onEvent("clickbutton", "click", function( ) {
  setProperty("gamescreen", "background-color", rgb(randomNumber(1, 250), randomNumber(1, 250), randomNumber(1, 250), 0.5));
  if (score < 10) {
    level = 1;
    setText("levelbutton", "level " + level );
    score += 1;
    setText("scorecounter", "Score = " + score);
    changebutton("clickbutton");
    changebutton("dontclickbutton");

  }
  else if ((score >= 10)) {
    level = 2;
    setText("levelbutton", "level " + level );
    score += 2;
    setText("scorecounter", "Score = " + score);
    changebutton("clickbutton");
    changebutton("dontclickbutton");
  }
  else if ((score >= 50))  {
    level = 3;
    setText("levelbutton", "level " + level );
    score += 3;
    setText("scorecounter", "Score = " + score);
    changebutton("clickbutton");
    changebutton("dontclickbutton");
  }
});

The changebutton is a function that changes the background color and text color of whatever “button” is through in the parameter, but that’s not the main point here. The function of “Endgame” is what I’m expereincing difficulties with, so here we go. “endgame” is called at least when the wrong button is clicked and when the time runs out, which ever happens during the game. And in my endgame function I have

setText("scoretext", (scorelist + " ") + namelist);

But what is displayed is a whole bunch of numbers, but what I want to be displayed is the list of scores from highest to lowest with the respective names lined up from the namelist. As a side point my start button takes the user input, sets it as a variable called “name” and appends to my namelist. This is an example of the results, I put in meir for name and that displayed ok, but my score was 5 and it showed up as

0,0,0,0,1,2,2,3,3,4,

4,5,5,5 meir

even though the only that should be in my scorelist is 5, so it shouldn’t print out all the other stuff. So if I could get any help on to properly sort the scorelist, and have it only print out the scores, and not whole bunch of numbers that would be great, and prefferably have it print out the names in order with the scores from highest scoring names to lowest scoring names, that would be great. Thanks in advance.

Mocking axios using interceptors (issue)

When running the following test to check if the login endpoint is being called with given arguments…

jest.mock("axios", () => {
  return {
    create: () => {
      return {
        interceptors: {
          request: { eject: jest.fn(), use: jest.fn() },
          response: { eject: jest.fn(), use: jest.fn() },
        },
      };
    },
  };
});

const mockedAxios = axios as jest.Mocked<typeof axios>;

it("should call login endpoint with given arguments", async () => {
  render(<MainContextProvider />);

  const mockedResponse = {
    succeeded: true,
    token: "eyJhbGc",
    firstName: "Test",
    lastName: "Test",
    email: "[email protected]",
    roles: ["Client"],
  };

  const { login } = authApi();

  mockedAxios.post.mockResolvedValue(mockedResponse);
  await login("[email protected]", "1234");
  expect(axios.post).toHaveBeenCalledWith(
    `${process.env.REACT_APP_URL_IDENTITY}/login`
  );
  expect(axios.post).toHaveBeenCalled();
});

I have the following error regarding mockResolvedValue property:

TypeError: Cannot read properties of undefined (reading
‘mockResolvedValue’)

  231 |     const { login } = authApi();
  232 |
> 233 |     mockedAxios.post.mockResolvedValue(mockedResponse);
      |                      ^
  234 |     await login("[email protected]", "1234");

authApi.js

const authApi = function () {
  const context = this;

  const identityService = axios.create({
    baseURL: process.env.REACT_APP_URL_IDENTITY,
  });

  identityService.interceptors.request.use(
    (config) => {
      config.headers.authorization = context.state.securityToken || null;

      return config;
    },
    (error) => Promise.reject(error)
  );

  return {
    login: async (email, pinCode) => {
      const request = { username: email, password: pinCode };

      const { data } = await identityService.post("/login", request);

      return data;
    },
  };
};

export default authApi;

Any ideas on how to fix this issue and make the test pass?

Hide Div on Scroll

I have this Div that shows up on button click and then lies over some other content, where the button to show the content lies too. I want to hide this div again by scrolling. I have some code which works, but only with limitations which makes it unusable.

I tried the following code:

  $(window).scroll(function() {
  if ($(this).scrollTop() > 100) {
    $('.hidden-content').fadeOut();
  }
});

This actually works but here is the problem: The button I use to show the content does not work anymore while hover-animations in this div still works everywhere. So I do not think this is a problem about a hidden div with a high z-Index value what lies above of everything.

I also tried the following code based on some help of the user Ned Hulton for hiding this div on a button click which worked perfectly fine, but I didn’t get the translation for the scroll event right as it seems.

$(window).scroll(function() {
   if ($(this).scrollTop() > 100) {
        $('.hidden-content').animate({"opacity":"0"}, function(){
        $(this).css({"zIndex":"-1"})
});
});

And maybe it will also help if I show you the code to make the div appear by a click on a button:

$('.clickable-content').click(function(e) {
      $('.hidden-content').css({
        "opacity":"1",
        "z-index": "9"
        });
    });

Hope someone can help me out! Thak you for reading!