How to highlight text when entering into input search bar

Search Bar Without Entry
Search Bar With Entry
In the images above, I have a search bar that allows for input, and filters once an input has been given. However, I want to go one step further and add a highlight to the text when an input has been made. In this example, for picture 2, I would want text highlighted for those selected. This is my current code below.

function myFunction() {
// Declare variables
var input, filter, ul, li, a, i, txtValue;
input = document.getElementById('myInput');
filter = input.value.toUpperCase();
ul = document.getElementById("myUL");
li = ul.getElementsByTagName('li');

// Loop through all list items, and hide those who don't match the search query
for (i = 0; i < li.length; i++) {
  a = li[i].getElementsByTagName("a")[0];
  txtValue = a.textContent || a.innerText;
  if (txtValue.toUpperCase().indexOf(filter) > -1) {
    li[i].style.display = "";
    li[i].style.color = 'green';
  } else {
    li[i].style.display = "none";
  }
}

Return result from MongoClient.connect [duplicate]

i hope someone can help a JavaScript-Newbie. I am trying to retrieve data from a MongoDB and return the result in a function.

test() 
{
    var list = [];
    MongoClient.connect(url, (err, client) => {
        if (err) throw err;
        const db = client.db("test");
        db.listCollections().toArray().then((docs) => {
            list = docs;
        }).catch((err) => {
            console.log(err);
        }).finally(() => {
            client.close();
        });
    });
    return list;
}

When i call console.log(test()) the list is always empty. I know, thats because its an asynchronous function. But how can i solve the Problem?

Changing between themes with Javascript

I’m trying to make a dark/light theme toggle on my website. The SVG file switches back and forth on every click, but there’s an issue with the theme not switching every click.

First two clicks – theme changes as expected.

Third and fourth clicks – SVG image still changes each click, but theme doesn’t change

Fifth and sixth clicks onward – theme changes as expected, cycle repeats

HTML:

<div id="themes">
   <img id="current-theme">
</div>

CSS:

body{
  background-color: #ccc;
}

#themes {
  text-align: right;
  margin-right: 10em;
  margin-top: 2em;
  transform: scale(1.5);
  cursor: pointer;
}

.dark-mode {
  background-color: rgb(65, 65, 65);
  transition: background-color 0.5s ease;

  h1 {
    color: white;
  }

  h3 {
    color: white;
  }

  button {
    background-color: white;
    color: black;
  }
}

.light-mode {
  background-color: #ccc;
  transition: background-color 0.5s ease;

  h1 {
    color: var(--primary-color);
  }

  h3 {
    color: black;
  }

  button {
    background-color: black;
    color: white;
  }
}

Javascript:

//default theme is light
document.getElementById("current-theme").src = "images/moon.svg"

var currentTheme = document.getElementById("current-theme");
currentTheme.setAttribute("onClick", "toDarkTheme()");

var theme = document.body;

function toDarkTheme() {

  document.getElementById("current-theme").src = "images/sun.svg";
  theme.classList.toggle("dark-mode");
  //currentTheme.removeAttribute("onClick");
  currentTheme.setAttribute("onClick", "toLightTheme()");
}

function toLightTheme() {

  document.getElementById("current-theme").src = "images/moon.svg";
  theme.classList.toggle("light-mode");
  //currentTheme.removeAttribute("onClick");
  currentTheme.setAttribute("onClick", "toDarkTheme()");
}


I’ve included a link to the code in jsfiddle so you can see exactly what’s happening. Thank you for any help/advice you can give!

https://jsfiddle.net/6op0fx7L/2/#&togetherjs=zTrev7ILNd

Matching the saturation value of a HSL color

I am trying to match only the saturation value of a HSL color, for example given hsl(190, 40%, 50%) as an input, I would like to match the 40/40%. I have trying using lookarounds for this, but everything I tried just didn’t really work.

I have the following regex which matches pretty much any HSL color I would need: /hsla?(s*(-?(d{1,3}|d{1,3}.d+)(deg|%)?)s*(,s*|s+)(-?(d{1,3}|d{1,3}.d+)%?)s*(,s*|s+)((d{1,3}|d{1,3}.d+)%?)s*((,s*|s*/s*)(0|(0?.d+)|1))?s*)/gi. How would I go about only selecting the saturation value?

Storing the contents of an axios response into a variable in typescript [duplicate]

I’m relatively new to javascript and typescript in general and am struggling to understand the concept of async/await and Promises. (My knowledge is more Python based)

I am trying to make sense of why this function won’t work.

const getData = () => {
  var myData: string;

  axios.get(myEndPoint)
  .then((response) => {
    console.log(response.data) // this outputs the correct data
    myData = response.data
    return myData
  })
  .catch((error) => {
    return error
  });

And then outside this function I would like to get the contents of myData like so

const data_contents = getData()

However this would give me a value of undefined

I have tried various methods including changing the function getData() to an async function and declaring await for axios.get() however that would return a Promise {<pending>} instead and not the actual contents of response.data.

If someone could help explain what I’m doing wrong and point me in the right direction it would be really appreciated. Thanks a lot!

axios: how to access response when getting 403 exception?

I have the following scenario:

The backend detects that the token has expired, so it returns 403 with custom “error” response header.

This can be reproduced by firing the following request:

axios.get(MY_URL)
     .then(res => console.log("I am expecting to enter this block, and do something with the response header"))
     .catch(err => console.log("But instead I skip the Then block and go straight here...));

In Chrome’s networking tab, I can indeed see that the header is there in the response:

<Response headers>
content-type: application/json
error: JWT expired at ......... <-- my header

However, it appears that I go straight into the catch block, where I do not have an access to the response and its headers. I was expecting to go into the then block and do some logic, such as:

.then(res => {
  if (res.statusCode === 403 && res.headers['error'] === 'JWT expired at .....') {
    // refresh token...
  }
});

How can I access my response and its headers, when the then block is skipped?

How to get arguments of another function? [duplicate]

I am trying to make a Express.js package that automatically generates routes from a object.

For example, if I were to put this in,

  info: {
    name: "Test",
    version: "V1.0.0",
    config: {
      platform: "express.js"
    }
  },
  users: {
    add: async function(firstName,lastName,email) {
      return email
    }
  }
}

then example.com/info/version would return V1.0.0.

That part I have already created successfully, but now I want to do the same for functions. I figure that I can pull arguments from query strings or bodies of POST requests and match them up with function arguments.

So now I need to find a way to get a function’s arguments, more specifically the argument names.

What I mean is that for the users.add function, I’d ideally like a array of arguments like ['firstName','lastName','email'] to be returned automatically.

Javascript : Parameters in a parent function are undefined in child function

I’ve been searching for hours and still dont understand what’s the problem with my code. I’ve got a main function called “req” and in this function there’s another arrow function called “data”. When I try to access the “author” and “collection” parameters of the main function, I get a Reference Error : the variables are undefined. Thanks for your help !

const puppeteer = require('puppeteer');
const fs = require('fs');

function saveData (jsonData) {
    fs.writeFile("myData.txt", jsonData, function(err) {
        if (err) {
            console.log(err);
        }
    });
}

async function req (author, collection) { // The two parameters are here : author and collection
    const browser = await puppeteer.launch({headless: false});
    const page = await browser.newPage();
    let link = 'www.myexampleurl/'+ author + '/'+ book + '/';
    await page.goto(link);
    const data = await page.evaluate(() => { // Here's the arrow function
        let elements = document.querySelectorAll('span.alldetails');
        let myBooks = [];
        for(element of elements) {
            myBooks.push(
                {   
                    authorName : author, // !!!!! UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: author is not defined
                    collectionName : collection, // !!!!! UnhandledPromiseRejectionWarning: Error: Evaluation failed: ReferenceError: collection is not defined
                    description : element.description
                }
                )
            }
            return myBooks;
        });
        saveData(JSON.stringify(data)); // A simple function that works to save the data in a text file
        browser.close();
            
};

req('john_doe', 'the_best_jd_books');

Function class javascript not finding variable

I have two javascript docs on my project.
js (script.js) #1:

let func = new Function('return thisvar')
console.log(func())

js (script1.js) #2:

let thisvar = 'hello'

I get an error:
ERROR:{@script.js line 4: cannot find variable 'thisvar'}
I have tried using var instead of let or even window.thisvar
What am I doing wrong?

Generate image from node array [duplicate]

I’m trying to generate an image with the given array of ints, where 1 is white and 0 is black.

var intArray = [
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  [1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
  [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
]; 

Here is what I’ve tried:

function saveImage(filename, data){
  var buffer = new Buffer(data.length);
  for (var i = 0; i < data.length; i++) {
    buffer[i] = data[i];
  }

  fs.writeFile(filename, buffer, function(err) {
    if(err) {
      console.log(err);
    } else {
      console.log("saved");
    }
  });
}

saveImage("image.jpg", intArray);

But the image file that is created is not a valid jpeg and I cannot view it, what am I doing wrong?

How to filter out dragged and dropped items properly in React JS?

I am learning React. I am trying to work out a drag and drop functionality from scratch. I am almost done but when I move an item from one div and try to move back to the original div, its throwing an error. If you are suggesting to use react-dnd, I already tried but I am not able to find a simple example, where I can just try the functionality. Here is what I tried.

Link: https://codesandbox.io/embed/fancy-surf-gnjpv?fontsize=14&hidenavigation=1&theme=dark.

Thanks in Advance

Axios.get() request returning undefined

In the below code Iam trying to use axios get request from await axios.get('/products/api')
is only working i can see the data in the console but forawait axios.get('/users/api')Undefined is being returned on the console but when i try get request through Postman i can get the results .Iam stuck here.

”’ const [userdata, setuserdata] = useState([]);
const [products, setproducts] = useState([]);

useEffect(() => {
    const fetchUserData = async () => {
        
        const { users } = await axios.get('/users/api')
        setuserdata(users);

        const { data } = await axios.get('/products/api')
        setproducts(data);
    }
    fetchUserData();



}, []);
console.log(products)
console.log(userdata)

hover style on page load

I’m looking for a simple way to persist a “hover” style on a page refresh if the user did not move his mouse. The issue is that the hover style is only triggered on a mouse enter/mouseover event, so on a page refresh it will not be applied even if the cursor is above the item in question until the user touches the mouse again and moves it slightly. The code below has this issue.

$('div').click(function () {
     window.location.reload();
});
div {
   width: 100px;
   height: 100px;
   background: grey;
}
div:hover {
   background: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div></div>

Immutable date, datetime and timedelta library for react native

Coming from python I am having a very hard time adapting to the way dates and datetimes are handled in javascript/typescript.

I’d rather not use moment.js as it is considered legacy and I’d really like to have immutable objects.

Luxon is not a good choice for me either because it means I have to eject from expo go. I do not have a mac so I have to use my wifes iPhone, which means I am stuck to this app.

date-fn requires me to set the locale manually on every localization request.

In short I would like to have a javascript library that can localize immutable datetime objects out of the box, has support for timedeltas (or intervals, or durations) and if possible has support for non-localized time objects.

I don’t believe this is an uncommon problem and yet those are the only 3 libraries I keep finding.