Calculating a text color based off of a background (not just black or white)

I’m currently trying to build a feature in typescript that automatically generates a text color that works on top of a background that follows the AA WCAG 2 or APCA standards. The problem is that I can can find lots of examples that show this by changing the text to either white or black. The issue is that I want to actually still preserve the color in the text. For example on the coolors.co site:

coolors.co palette generator

I’ve tried using HSL and modifying the lightness value, but I still have issue getting it reliably generating good text colors. Any help or leads on this would be much appreciated!

Here’s what I’m trying to use it for:

anime card with auto generated text colors

How to have 2 different ID’s in the same cell on the same row?

I have 2 different data coming in from javascript and I would like to show both data in the same cell on the same row

HTML code:

  <td>
  <div class="rcelldata">
  <div id="r_laps"></div>
  <div id="r_dfs" ></div>
  </td>

Results are:
data for r_laps
data for r_dfs

I want
r_laps r_dfs

Bonus points, how to add parenthesis around the second data
r_laps (r_dfs)

Thanks in advance

tried many forms of

Read Array json file uploaded on runner (Postman)

Currently I’m working with writing test script that can read and compare the values return from api and json file I provided. The problem is that I’m not sure the error is in the script or json file.

error returning : JSONError: Unexpected token u in JSON at position 0

json file name (Book1.json)
[
    {
      "name": "Test Case 1",
      "tests": [
        {
          "testName": "Test 1",
          "location": {
            "row": 5,
            "column": 12
          },
          "expectedResult": "1023.00"
        },
        {
          "testName": "Test 2",
          "location": {
            "row": 7,
            "column": 10
          },
          "expectedResult": "500.50"
        }
      ]
    },
    {
      "name": "Test Case 2",
      "tests": [
        {
          "testName": "Test 3",
          "location": {
            "row": 2,
            "column": 8
          },
          "expectedResult": "750.25"
        }
      ]
    }
  ]

Test script :-

const responseJson = pm.response.json();
var data = JSON.parse(responseBody);
var investmentLink = data.result;

// Write a script that can read the JSON file provided and compare the actual and expected results
const jsonData = JSON.parse(pm.iterationData.get("Book1.json"));

// Write a script that can read the JSON file provided and compare the actual and expected results
function performTests(testCase) {
  const tests = testCase.tests;

  tests.forEach((test) => {
    const testName = test.testName;
    const location = test.location;
    const expectedResult = test.expectedResult;
    const row = location.row;
    const column = location.column;

    const actualData = investmentLink.reportPIIllustrationTable[0].illustration[row - 1][`column${column}`].data;
    pm.test(testName, () => {
      pm.expect(actualData).to.equal(expectedResult);
    });
  });
}

jsonData.forEach((testCase) => {
  const testCaseName = testCase.name;
  pm.test(testCaseName, () => {
    performTests(testCase);
  });
});

json file preview

As I look into the error it shows something might wrong with the json file. Someone may help with this issue

Proper way to use return statement in try, catch block for asynchronous functions

I have the following code below that creates a new MongoDB document using Mongoose which does work.

async function createQuiz(questions, quizDetails) {
  const { quizName, minPoints, maxPoints } = quizDetails;
  try {
    const user = await Quiz.create({
      quizName,
      minPoints,
      maxPoints,
      questions,
    })
    if (user) console.log("success");
  } catch (e) {
    console.log(e.message);
  }
}

createQuiz(questions, quizDetails);

However, if I replace the console.log statements with return statements shown in the code below, it suddenly stops working.

async function createQuiz(questions, quizDetails) {
  const { quizName, minPoints, maxPoints } = quizDetails;
  try {
    const user = await Quiz.create({
      quizName,
      minPoints,
      maxPoints,
      questions,
    })
    if (user) return "success";
  } catch (e) {
    return e.message;
  }
}

console.log(createQuiz(questions, quizDetails));

With the return statements, the console logs “Promise { pending }.” But why doesn’t it log that same statement when the console.log was inside the function?

TypeError: console.log is not a function in Node crud app

I am trying to make a crud app but I am getting an error message “TypeError: console.log is not a function” at Query. (C:UsersLuis HernandezDesktopgaming-crudserverapp.js:30:25)

[![enter image description here][1]][1]

This happens every time I click the add button to add a game to the database.

This is the server

//create server
const express = require('express')
const app = express();
const mysql = require('mysql')
const cors = require('cors')

//Make available to make request from the front end to the backend
app.use(cors());
app.use(express.json());

const db = mysql.createConnection({
    user: "root",
    host: "localhost",
    password: "adminsql",
    database: "storagedgames"
})

app.post('/create', (req, res) => {
    const gameName = req.body.gameName
    const genre = req.body.genre
    const year = req.body.year
    const console = req.body.console

    db.query(
        'INSERT INTO games (game_name, genre, year, console) VALUES (?,?,?,?)',
        [gameName, genre, year, console], 
        (err, result) => {
            if(err){
                console.log(err);
            } else {
                res.send('values added')
            }
        });
});


// port to listen
app.listen(3001, () => {
    console.log('listening to port 3001')
})```



This is the Client frontend 


```import { Link } from 'react-router-dom'
import './Create.css'
import { useState } from 'react';
import Axios from 'axios'


const Create = () => {

    const [gameName, setGameName] = useState('');
    const [genre, setGenre] = useState('');
    const [year, setYear] = useState(0);
    const [console, setConsole] = useState('');

    const addGame = () => {
        Axios.post('http://localhost:3001/create',
            {
                gameName: gameName,
                genre: genre,
                year: year,
                console: console
            }).then((result) => {
                console.log('added succesfully')
            }).catch((err) => {
                console.log('error mesagge' + err)
            });
    }



    return (
        <div className="create">
            <Link to={'/'} className='home-button neon-button-form'>Home</Link>
            <div className="create-container ">
                <h2 className="create-title headtext-h2">Add a Game</h2>
                <form className="create-form">
                    <label className='create-label headtext-label'>Game Name</label>
                    <input type="text" className='create-input ' onChange={(e) => {
                        setGameName(e.target.value);
                    }} />
                    <label className='create-label headtext-label'>Genre</label>
                    <input type="text" className='create-input' onChange={(e) => {
                        setGenre(e.target.value);
                    }} />
                    <label className='create-label headtext-label'>Year</label>
                    <input type="number" className='create-input' onChange={(e) => {
                        setYear(e.target.value);
                    }} />
                    <label className='create-label headtext-label'>Console</label>
                    <input type="text" className='create-input' onChange={(e) => {
                        setConsole(e.target.value);
                    }} />
                    <button className='create-button neon-button-form' onClick={()=>{addGame()}}>ADD</button>
                </form>
            </div>
        </div>
    );
}

export default Create;```

[![enter image description here][2]][2]


  [1]: https://i.stack.imgur.com/UHUyP.png
  [2]: https://i.stack.imgur.com/EkngN.png

Tax calculator output diplays result in incorrect tax bracket?

I recently wrote a Python tax calculator for my mother, who is an accountant. It seems to work just fine, but she hates using the terminal, so I decided to re-write it in JavaScript which I am currently learning at university. Here is the Python calculator:

print("Welcome to the tax calculator!")

assessible_income = int(input("Enter your assessible income in AUD: "))
allowable_deductions = int(input("Enter your allowable deductions in AUD: "))

taxable_income = assessible_income - allowable_deductions

tax_bracket_0 = range(0, 18201)
tax_bracket_1 = range(18201, 45001)
tax_bracket_2 = range(45001, 120001)
tax_bracket_3 = range(120001, 180001)
tax_bracket_4 = range(180001, 1000000)

if (taxable_income in tax_bracket_0):
    print("You do not pay any tax.")
elif (taxable_income in tax_bracket_1):
    print("You will pay $0 tax on the first $18200 of your income, and 19 cents for each dollar over $18200.")
    tax = ((taxable_income - 18200)*0.19)
    medicare_levy = taxable_income*0.02
    total_tax = tax + medicare_levy
    print("You will pay", total_tax, "dollars in tax, including Medicare levy.")
    print("Your Medicare levy is, in AUD: ", medicare_levy)
elif (taxable_income in tax_bracket_2):
    print("You will pay $5092 plus $0.325 for each $1 over $45000.")
    tax1 = ((5092) + ((taxable_income - 45000)*0.325))
    medicare_levy1 =  taxable_income*0.02
    total_tax1 = tax1 + medicare_levy1
    print("You will pay", total_tax1, "dollars in tax, including Medicare levy.")
    print("Your Medicare levy is, in AUD: ", medicare_levy1)
elif (taxable_income in tax_bracket_3):
    print("You will pay $29467 plus $0.37 for every dollar over 120000")
    tax2 = ((29467) + ((taxable_income - 120000)*0.37))
    medicare_levy2 = taxable_income*0.02
    total_tax2 = tax2 + medicare_levy2
    print("You will pay", total_tax2, "dollars in tax, including Medicare levy.")
    print("Your Medicare levy is, in AUD: ", medicare_levy2)
elif (taxable_income in tax_bracket_4):
    print("You will pay $51667 plus $0.45 for each dollar over $180000.")
    tax3 = ((51667) + ((taxable_income - 180000)*0.45))
    medicare_levy3 = taxable_income*0.02
    total_tax3 = tax3 + medicare_levy3
    print("You will pay", total_tax3, "dollars in tax, including Medicare levy.")
    print("Your Medicare levy is, in AUD: ", medicare_levy3)
else:
    print("You have too much money for this calculator. Good luck.")

The JavaScript calculator does not function like the Python one does, though. It appears to work for income values of up to 75000 with 0 deductions, but after that, it appears to calculate to the wrong tax bracket. Running the two scripts side-by-side should highlight the difference. Here is the JS:

function range(start, end) {
  const ans = [];
  for (let i = start; i <= end; i++) {
    ans.push(i);
  }
  return ans;
}

const taxBracketZero = range(1, 18201);
const taxBracketOne = range(18201, 45001);
const taxBracketTwo = range(45001, 120001);
const taxBracketThree = range(120001, 180001);
const taxBracketFour = range(180001, 1000000)

function calculateTax() {
  let income = document.getElementById("income").value;
  let deductions = document.getElementById("deductions").value;
  let tax = income - deductions

  if (tax in taxBracketZero) {
    document.getElementById("result").innerHTML = "You do not pay any tax.";
  } else if (tax in taxBracketOne) {
    document.getElementById("result").innerHTML = "You will pay $0 tax on the first $18200 of your income, and 19 cents for each dollar over $18200.";
    let taxable_income = ((tax - 18200) * 0.19);
    let medicare_levy = tax * 0.02;
    let total_tax = taxable_income + medicare_levy;
    document.getElementById("result1").innerHTML = "You will pay " + total_tax + " dollars in tax, including Medicare levy.";
    document.getElementById("result2").innerHTML = "Your Medicare levy is, in AUD: " + medicare_levy;
  } else if (tax in taxBracketTwo) {
    document.getElementById("result").innerHTML = "You will pay $5092 plus $0.325 for each $1 over $45000.";
    let taxable_income = ((5092) + ((tax - 45000) * 0.325));
    let medicare_levy = tax * 0.02;
    let total_tax = taxable_income + medicare_levy;
    document.getElementById("result1").innerHTML = "You will pay " + total_tax + " dollars in tax, including Medicare levy."
    document.getElementById("result2").innerHTML = "Your Medicare levy is, in AUD: " + medicare_levy;
  } else if (tax in taxBracketThree) {
    document.getElementById("result").innerHTML = "You will pay $29467 plus $0.37 for every dollar over 120000";
    let taxable_income = ((29467) + ((tax - 120000) * 0.37));
    let medicare_levy = tax * 0.02;
    let total_tax = taxable_income + medicare_levy;
    document.getElementById("result1").innerHTML = "You will pay ", total_tax, " dollars in tax, including Medicare levy.";
    document.getElementById("result2").innerHTML = "Your Medicare levy is, in AUD: " + medicare_levy;
  } else if (tax in taxBracketFour) {
    document.getElementById("result").innerHTML = "You will pay $51667 plus $0.45 for each dollar over $180000.";
    let taxable_income = (51667) + ((tax - 180000) * 0.45);
    let medicare_levy = tax * 0.02;
    let total_tax = taxable_income + medicare_levy;
    document.getElementById("result1").innerHTML = "You will pay " + total_tax + " dollars in tax, including Medicare levy.";
    document.getElementById("result2").innerHTML = "Your Medicare levy is, in AUD: " + medicare_levy;
  } else {
    document.getElementById("result").innerHTML = "You have too much money for this calculator. Good luck!"
  }

}
<html>

<head>
  <script type="text/javascript" src="script.js"></script>
</head>

<body>

  <h2>Tax Calculator</h2>

  <h3>Enter your assessible income in AUD:</h3>
  <input type="text" id="income" name="income">
  <h3>Enter your allowable deductions in AUD:</h3>
  <input type="text" id="deductions" name="deductions">
  <button type="button" onclick="calculateTax()">Calculate my tax!</button>
  <p id="result"></p>
  <p id="result1"></p>
  <p id="result2"></p>
</body>

</html>

I am very very confused and would really appreciate some help. Thank you!

Regular expressions getting the word after the matched phrase

I want to get the next word after the matched phrase.

e.t. – I want to change my pain threshold

— “change my ***”

let text = "I want to change my pain threshold"
    let firstTriggerregEx = "(?:\b|')(change my)(?:\b|')";
    const found2 = text.match(firstTriggerregEx);
    console.log(found2);

This will return a match, but not the word after

How to authenticate to MS Graph using JavaScript?

I’m trying to develop an automation using Graph API and JavaScript. I have an app registration in Azure Portal with necessary permissions. How can I authenticate in my JavaScript automation using tenant ID, client ID and client secret and call Graph APIs from automation?

How to use a flask variable inside src script tag?

The below hardcoded string will work:

<script src="https://gist.github.com/xxxxxxx.js"></script>

I have the same string in a db and using the below will not work:

    <script src={{ project.link }}></script>

where {{ project.link }} = https://gist.github.com/xxxxxxx.js

tried:

    <script type="text/javascript" id="myScript">
      var link ='{{ project.title }}'
    </script>

with this below:

  <script>
      document.getElementById('myScript').src = link;
  </script>

Does not work too.

Selecting First Hidden Element Jquery not working

So I have this code here that has a certain amount of dropdown lists preloaded and hidden depending what is calling this partial view.

On the add button click I am attempting to select the first element that is hidden and show it.
For some reason it is not working with the :hidden:first tag I am using to attempt to select it.
Here is my code below

@model Client_Portal.Models.ChartYearViewModel
@using MoreLinq;
@{
    /**/
    var divtoupdate = ViewBag.DivName;
    ViewBag.Title = "Home";
}

<div id="updateTableChartYearsModel">
    @*@using (Ajax.BeginForm("StaffCreateSubmit", "Home", new AjaxOptions
         {
             InsertionMode = InsertionMode.Replace,
             UpdateTargetId = "updateTableChartYearsModel"
         }
        , new { id = "updateTableChartYearsForm" }))
         {*@
    <div class="row">
        <div class="col-lg-12 col-md-12 col-sm-12">

            <div class="form-group row year" id="year1">
                @Html.LabelFor(model => model.Year1, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year1, new SelectList(Model.YearList1, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year2">
                @Html.LabelFor(model => model.Year2, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year2, new SelectList(Model.YearList2, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year3">
                @Html.LabelFor(model => model.Year3, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year3, new SelectList(Model.YearList3, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year4" style="display:none">
                @Html.LabelFor(model => model.Year4, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year4, new SelectList(Model.YearList4, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year5" style="display:none">
                @Html.LabelFor(model => model.Year5, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year5, new SelectList(Model.YearList5, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year6" style="display:none">
                @Html.LabelFor(model => model.Year6, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year6, new SelectList(Model.YearList6, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year7" style="display:none">
                @Html.LabelFor(model => model.Year7, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year7, new SelectList(Model.YearList7, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group row year" id="year8" style="display:none">
                @Html.LabelFor(model => model.Year8, htmlAttributes: new { @class = "col-lg-3 col-md-3 col-sm-12 col-xs-12 col-form-label", @id = "" })
                <div class="col-lg-8 col-md-8 col-sm-12 col-xs-12">
                    @Html.DropDownListFor(model => model.Year8, new SelectList(Model.YearList8, "Value", "Text"), new { @class = "form-control" })
                </div>
                <div class="col-lg-1 col-md-1 col-sm-1 col-xs-1"><span class="glyphicon glyphicon-remove removeYear" style="color:red; font-size:18px; top:8px"></span></div>
            </div>
            <div class="form-group m-b-0">
                <button class="btn btn-info btn-success addYear" style="background: #00c292; border: 1px solid #00c292;">Add Option</button>

                <button class="removeYear">Remove Year</button>

                <button class="btn btn-info pull-right submit">Update Options</button>
            </div>

        </div>
    </div>
    @* } *@
</div>

<script>



        if ("@Model.Name" != "GetPortfolioBenchmarksPerformance") {
            $("div#year4").show();
            $("div#year5").show();
    };


    $('button.addYear').on('click', function (e) {
        e.preventDefault();
        var lastVisibleDiv = $(".year:hidden:first");
        var id = lastVisibleDiv.attr("id");
        alert(id);
        lastVisibleDiv.show();
        //                .addClass("show");

    });

    $('span.removeYear').on('click', function (e) {
        e.preventDefault();
        var lastVisibleDiv = $(this).parent().parent();
        // alert(lastVisibleDiv.next(".form-group").attr("id"));
        var id = lastVisibleDiv.attr("id");
        lastVisibleDiv.hide();
        //                .addClass("show");

    });
   
</script>

I have tried a few other selectors and have had no luck getting the correct one. Seems to always pull the id year1 div.
I need this to be able to remove them and when add clicked it readds the first one hidden on the page.
Thanks In advance

Is it possible to use a JavaScript module from “normal” javascript (debugger)?

I’ve tried to read up on JavaScript modules, but I’m still not clear on one thing: assume the following minimal HTML example:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
  <title>Test</title>

  <script type="module">
  export function hello() {
    console.log("hello");
  }
  </script>

</head>
<body>
</body>
</html>

Let’s say I load this in my browser via file:///C:/tmp/test.html – it is the file:// protocol, yes, but there is no .js file being loaded, as the script is embedded, so CORS should not be a problem (and I don’t get a Console JavaScript error either).

So let’s say, I load this page in Firefox 115, and I open the Console/JavaScript Debugger. No “hello” is accessible by default:

>> hello
Uncaught ReferenceError: hello is not defined
    <anonymous> debugger eval code:1

… and I cannot “import” or “require”:

>> import { hello }
Uncaught SyntaxError: import declarations may only appear at top level of a module

>> require("hello")
Uncaught ReferenceError: require is not defined
    <anonymous> debugger eval code:1

(maybe require needs a library, but as you can tell, I’m not really a JavaScript guru)

So – is there anything I can do with my <script type="module"> from “normal” JavaScript (that is, either <script> which is not type="module" – or direct commands in JavaScript Debugger/Console), without explicitly saying window.hello = hello; at the end of the module code?

Creating an array of dates efficiently?

I have an availabilities collection. Inside this collection could be a few entries that are date based for example:

{
  "_id": "64b03ed794d87927a3066e13",
  "startDateTime": "2023-07-07T18:00:00.000Z",
  "endDateTime": "2023-07-12T15:00:00.000Z",
  "availabilityType": "blackout"
}
{
  "_id": "64b03eb094d87927a3066ddb",
  "startDateTime": "2023-07-03T18:00:00.000Z",
  "endDateTime": "2023-07-06T15:00:00.000Z",
  "availabilityType": "blackout"
}

I am trying to figure out the best way to create an array of dates for the month and if there is an “availability” for some of the days, then return that within the date array. I thought about creating an array of days using javascript but then I’d have to iterate for each day to see there are any availabilities on the day; this seems very inefficient.

Ideally what I am looking to build is something similar to the following:

[
  {
    "date": "2023-07-01",
    "availabilityType": "available"
  },
  {
    "date": "2023-07-02",
    "availabilityType": "available"
  },
  {
    "date": "2023-07-03",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  {
    "date": "2023-07-04",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  {
    "date": "2023-07-05",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  {
    "date": "2023-07-06",
    "availabilityType": "booked" // because there was an availability entry in the collection that is marked as booked
  },
  ... etc up to July 31
]

Any suggestions on how this might be done?

Close Search overlay only if inputs have no error

I am trying to develop a full screen search field and would like the orange “search” button to close the overlay only if all inputs are valid.

Each input has a limit of 2 digits, only numbers and between 1 and 20.
Everything works fine except the “search” button closes the overlay when the last input is valid even if the first 2 inputs are left blank (error)….

Is there any conflict or is the script wrong?

$(function() {
  $('a[href="#search"]').on("click", function(event) {
    event.preventDefault();
    $("#search").addClass("open");
    $('#search > form > input[type="search"]').focus();
  });

  $("#search, #search button.close").on("click keyup", function(event) {
    if (
      event.target == this ||
      event.target.className == "close" ||
      event.keyCode == 27
    ) {
      $(this).removeClass("open");
    }
  });

  $(".send_btn").submit(function(event) {
    event.preventDefault();
    return false;
  });
});

// validation input - error if not..
function handleChange(input) {
  if (input.value < 0) input.value = "";
  else if (input.value < 0.9 || input.value > 20 || input.value.length === 1 || input.value.length === 0) {
    input.style.borderColor = 'red';
  } else {
    input.style.borderColor = '';
  }
}


$('input').keypress(function(event) {
  event = event || window.event;
  var charCode = event.which || event.keyCode;
  var charStr = String.fromCharCode(charCode);
  if (event.key !== undefined && event.charCode === 0) {
    return;
  }
  if (!/^([0-9])*$/.test(charStr)) {
    event.preventDefault();
  }
  if (!/^[a-zA-Z0-9]+$/.test(charStr)) {
    event.preventDefault();
  }
});

// If input is empty Send Button Click - error - no action
$('.send_btn').click(function() {
  $("input.each_item").each(function() {
    if (this.value.trim().length === 0 || this.value.trim().length === 1 || this.value > 20)
      $(this).css('border-color', 'red') &&
      $('#search').addClass('open') &&
      $('html').addClass("noScrollSimple");
    else
      $(this).css('border-color', '') &&
      $('#search').removeClass('open') &&
      $('html').removeClass("noScrollSimple");
  });
});
html {
  overflow-y: scroll;
}

body {
  margin: 0px;
  font-weight: 400;
  font-size: 12px;
  -webkit-font-smoothing: antialiased;
  width: 100%;
  min-width: auto;
  background: #ebebeb;
  padding: 50px;
}

.button {
  width: 250px;
  height: 50px;
  color: #ebebeb;
  background-color: cornflowerblue;
  margin: 0 auto;
  text-align: center;
  font-size: 2.3em;
  margin-top: 50px;
  font-size: 2.3em;
  cursor: pointer;
}

.input_cont {
  display: inline-block;
  width: 100%;
  margin: 0px auto;
  text-align: center;
  max-width: 1250px;
}

.items {
  display: flex;
  flex: 1;
  padding: 0px 20px 0px;
}

.each_item {
  width: 100px;
  height: 100px;
  min-width: 100px;
  min-height: 100px;
  line-height: 2.75em;
  margin: 0px auto;
  display: table-cell;
  float: left;
  font-weight: bold;
  color: #ebebeb;
  font-size: 2.3em;
  background: rgba(0, 0, 0, .6);
  text-align: center;
  -webkit-appearance: none;
}

#search {
  position: fixed;
  top: 50%;
  left: 50%;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: column;
  background-color: rgba(50, 50, 50, .9);
  -webkit-transform: translate(-50%, -50%) scale(0, 0);
  -moz-transform: translate(-50%, -50%) scale(0, 0);
  -o-transform: translate(-50%, -50%) scale(0, 0);
  -ms-transform: translate(-50%, -50%) scale(0, 0);
  transform: translate(-50%, -50%) scale(0, 0);
  opacity: 0;
}

#search input[type=search] {
  color: #ebebeb;
  background: rgba(0, 0, 0, 0);
  font-weight: 300;
  text-align: center;
  border: 0px;
  margin: 0px auto;
  margin-top: -51px;
  padding-left: 30px;
  padding-right: 30px;
  outline: none;
}

#search .btn {
  background: chocolate;
  outline: none;
  -webkit-appearance: none;
  -moz-appearance: none;
  -ms-appearance: none;
  -o-appearance: none;
  appearance: none;
  border: 0px solid transparent;
}

#search .close {
  position: fixed;
  top: 15px;
  right: 15px;
  opacity: 1;
  width: 50px;
  height: 50px;
}

#search .close:after {
  content: '';
  height: 45px;
  border-left: 5px solid #ebebeb;
  position: absolute;
  transform: rotate(45deg);
  left: 28px;
}

#search .close:before {
  content: '';
  height: 45px;
  border-left: 5px solid #ebebeb;
  position: absolute;
  transform: rotate(-45deg);
  left: 28px;
}

#search.open {
  -webkit-transform: translate(-50%, -50%) scale(1, 1);
  -moz-transform: translate(-50%, -50%) scale(1, 1);
  -o-transform: translate(-50%, -50%) scale(1, 1);
  -ms-transform: translate(-50%, -50%) scale(1, 1);
  transform: translate(-50%, -50%) scale(1, 1);
  opacity: 1;
}

#search,
#search.open {
  -webkit-transition: all .35s;
  -moz-transition: all .35s;
  -ms-transition: all .35s;
  -o-transition: all .35s;
  transition: all .35s;
  transition-property: initial;
  transition-duration: 0.35s;
  transition-timing-function: initial;
  transition-delay: initial;
}

.search__input {
  width: 100%;
  height: 100%;
  background: transparent;
  outline: none;
  color: #ebebeb;
  transition: opacity 0s;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a href="#search">
  <div class="button">
    Search</div>
</a>


<div id="search">
  <div type="button" class="close"></div>
  <div class="input_cont">
    <div class="items">
      <input name="num" type="text" min="1" max="20" minlength="2" maxlength="2" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}" onchange="handleChange(this);" class="search__input each_item" placeholder="00" />
      <input name="num" type="text" min="1" max="20" minlength="2" maxlength="2" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}" onchange="handleChange(this);" class="search__input each_item" placeholder="00" />
      <input name="num" type="text" min="1" max="20" minlength="2" maxlength="2" oninput="if((this.value.length) > 2) {this.value = this.value.substring(0, 2);}" onchange="handleChange(this);" class="search__input each_item" placeholder="00" />
    </div>
  </div>
  <button type="submit" class="button btn btn-primary send_btn">Search</button>
</div>

How to create a simple website that turns user submitted images into text using Google Vertext AI Vision API

I’m trying build a simple html/css/jquery website that turns user submitted images into text using Google Vertext AI Vision API (or other service).

I’d really appreciate if someone can answer the following.

  1. How difficult is to create this website?
  2. Any examples, tutorials that I can reference?

Thanks.

I tried finding examples and tutorials but couldn’t find any.

Add action to the enter button [closed]

How can I make my enter button to make the same effect as my click in js?
For people that are used to use only keyboard is easier to just press enter than press click on the button on the screen thats why I need to know how can I do that
Thank you!!

BOTON.addEventListener("click",