How to make a simple text markup in HTML? [closed]

Is there a way I could add my own text markup?

What I mean by this is for e.g. I have an input field, and when I type a word for e.g. “apple” that word will be green, but if I type “orange” it will be the color orange.

Long story short, each word I type in the input field is a different color (which I will pre-set in my code)?

Is it possible to do this?

How to get the position of all the text within a parent element with another element or more in between the text, in pure JavaScript

After searching for a way to get the text Y and X position in an element on-click, I came across this question How to get the position of text within an element?

aaron‘s answer was the closest i got to what i need.
I tried to change the script a bit but with partial success.

Here is my progress, i get this error { "message": "Uncaught IndexSizeError: Failed to execute 'setStart' on 'Range': There is no child at offset 512.", "filename": "https://stacksnippets.net/js", "lineno": 38, "colno": 15 } when pressing on childNodes 3 and 5.

How do i go about getting childNodes 3 and 5 and etc. to give a response similar to “childNode 1” without wrapping the text with a span tag?

function findClickedWord(parentElt, x, y) {
    /*if (parentElt.nodeName !== '#text') {
        console.log('didn't click on text node');
        return null;
    }*/
    var range = document.createRange();
    //var words = parentElt.textContent;//.split(' ');
    var sentences = [];
    console.log('parentElt.childNodes.length ',parentElt.childNodes.length)
    for (var i = 0; i < parentElt.childNodes.length; i++) {
        sentences[i] = parentElt.childNodes[i].textContent
    }
    
    var start = 0;
    var end = 0;
    for (var i = 0; i < sentences.length; i++) { 
        var words = sentences[i];
        end = start+words.length;
        range.setStart(parentElt.childNodes[i], start);
        range.setEnd(parentElt.childNodes[i], end);
        var rects = range.getClientRects();
        var clickedRect = isClickInRects(rects);
        if (clickedRect) {
            return [words, start, clickedRect];
        }
        start = end + 1;
    }
    
    function isClickInRects(rects) {
        for (var i = 0; i < rects.length; ++i) {
            var r = rects[i]
            if (r.left<x && r.right>x && r.top<y && r.bottom>y) {            
                return r;
            }
        }
        return false;
    }
    return null;
}
function onClick(e) {
    var elt = document.getElementById('info');
    var clicked = findClickedWord(e.target, e.clientX, e.clientY);
    /*var clicked = [];
    for (var i = 0; i < e.target.childNodes.length; i++) {
            if(e.target.childNodes[i])
             clicked = findClickedWord(e.target.childNodes[i], e.clientX, e.clientY);
    }*/
    elt.innerHTML = 'Nothing Clicked';
    if (clicked) {
        var myChildNode = clicked[0];
        var start = clicked[1];
        var r = clicked[2];
        elt.innerHTML = 'Clicked: (top:'+r.top+', left:'+r.left+') context of:'+myChildNode+' at offset '+start; 
    }
}

document.addEventListener('click', onClick);
#info {
    position: absolute;
    bottom: 0;
    background-color: cyan;
}
<div class="parent">
    <div class="child"> (childNode 1) Bacon ipsum dolor amet meatball bresaola t-bone tri-tip brisket. Jowl pig picanha cupim landjaeger, frankfurter spare ribs chicken. Porchetta jowl pancetta drumstick shankle cow spare ribs jerky tail kevin biltong capicola brisket venison bresaola. Flank sirloin jowl andouille meatball venison salami ground round rump boudin turkey capicola t-bone. Sirloin filet mignon tenderloin beef, biltong doner bresaola brisket shoulder pork loin shankle turducken shank cow. Bacon ball tip sirloin ham. <div> (childNode 2) "this text is Ok if clicked"</div> (childNode 3) click on this text to see the error <a href='#'> (childNode 4) Link is Ok if clicked</a> (childNode 5) and click here two see anther error.
    </div>
    <div id="info">Click somewhere in the paragraph above</div>
</div>

Environmental variable read issue in Heroku deployed app

I got a React/Node.js app which is deployed to Herouku.

I have an env variable named REACT_APP_BASE_URL which value is http://localhost:4000 locally and the production site’s URL in Heroku’s config vars.

The issue appears when i’m trying to send an SMS with a string containing the URL, like so:

const msg = `Hello! view your profile in ${process.env.REACT_APP_BASE_URL}/user/${id}` 

Locally it works fine and but in production the result is:

Hello! view your profile in /user/${id}

I would guess it can’t read the value from Heroku’s config vars, but this isn’t the case as this base url reference is working fine in other places in the same component (XHR requests where I paste it the same way and are happening just before the problematic call).

Any idea?

Get variable out from function which is calling export.modules node.js

In the file users.js I want to get code out of randomCode() to assign to the result and use it in whole endpoint '/login'.

randomCode.js

const crypto = require('crypto')

const randomCode = (callback) =>{
    crypto.randomInt(100000, 999999, (err, n) => {
        if (err) throw err;
        callback(n);
    });
}
    
module.exports = randomCode

users.js

require('dotenv').config()
const express = require('express')
const router = express.Router()
const randomCode = require('../controllers/randomCode')


router.get('/login', async (req, res, next)=>{
    try{
//-----------------------------------------------------
        randomCode((code) => {
          console.log(code,'code')
        })
//-----------------------------------------------------
        return res.send('ok')
    }
    catch(error){
        res.send(error)
    }
})

module.exports = router;

I tried to use await but whithout results.

router.get('/login', async (req, res, next)=>{
    try{
//------------------------------------------------------
        const result = await randomCode((code) => {
          console.log(code,'code')
        })
        console.log(result)
//------------------------------------------------------
        return res.send('ok')
    }
    catch(error){
        res.send(error)
    }
})

Google Apps Script, print and don’t render my css file?

I’ve un other problem, with my google apps scpript, now html, css, and js files are ok. But when I call a function

function func(){
  var message="";
  try {
   
    );
  }
  catch (error) {
     message="Errors "+ 
      "rnMessage: " + error.message
      + "rnFile: " + error.fileName
      + "rnLine: " + error.lineNumber;
  }
  finally {
    if(message=="") {
      message="Completed Successfully";
    }
    Logger.log(message);
  }
}

with

function onFailure(error){
    console.log("onFailure: " + error);
}

function onSuccess(resp) {
    console.log("onSuccess: "+ resp);
}

google.script.run.withFailureHandler(onFailure).withSuccessHandler(onSuccess).hotelWorkSync();

the console show this logs, and not my

Net state changed from IDLE to BUSY
Net state changed from BUSY to IDLE
null

I just try to follow much video but I can’t see the error.
I don’t understand where I’m wrong, please help me :’(.

JS and Webserver interaction

I want to check with an JS file if a folder with files was created/uploaded in by webserver.
After that I want to search for the .html file in the folder and then set an link to that file in my html file where the JS file is located.
Is this possible with JS, when yes how?

Putting two divs tags next to each other

so I am trying to put these two s of class= “Col” next to each other with the image in the full left side of the screen.
this is the component code:

import batta from '../../Images/batta.png';
import onlineAuction from '../../Images/onlineAuction.png';
import './LandingScreen.css';
import {useState} from 'react';
import {Link} from 'react-router-dom';
import {Container,Row, Col} from 'react-bootstrap';
const LandingScreen = ()=>{

    const [email, setEmail] = useState("");
    const [password, setPassword] = useState("");

  
    return(
       <Container>
           <Row>
               <Col>
                    <img src ={batta}/>
               </Col>
               <Col>
                    <form style={{marginLeft:300}}>
                        <div className="modal-dialog" role="document" style={{"display":"flex"}}>
                            <div className="modal-content">
                                <div className="modal-header">
                                    <h5 className="modal-title">Sign In</h5>
                                </div>
                                <div className="modal-body">
                                    <form>
                                        <fieldset  style={{maxWidth:500 , marginLeft:20}}> 
                                            <div className="form-group" style={{marginTop :25}}>
                                                <label for="exampleInputEmail1" className="form-label">Email address</label>
                                                <input type="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email"
                                                value={email} onChange={(e)=> setEmail(e.target.value)}/>
                                            </div>
                                            <div className="form-group" style={{marginTop :1}}>
                                                <label for="exampleInputPassword1" className="form-label mt-4">Password</label>
                                                <input type="password" className="form-control" id="exampleInputPassword1" placeholder="Password"
                                                value={password} onChange={(e)=> setPassword(e.target.value)}/>
                                            </div>
                                        </fieldset>
                                    </form>
                                </div>
                                <div className="modal-footer">
                                    <Link to ="/register" style={{marginRight:175}}>
                                        Don't have an account
                                    </Link>
                                    <button type="submit" className="btn btn-secondary" data-bs-dismiss="modal" >
                                        Log In
                                    </button>

                                </div>
                            </div>
                        </div>  
                    </form>
                </Col>
            </Row>
        
        </Container>
    );
};


export default LandingScreen;

and this is how it looks on the browser:Component rendered in the browser

i thought of using this css code but it didn’t work.

#leftHalf{
    position: absolute;
    left: 0px;
    height: 100%;
    width: 63%

}

.image-container{
    width: 100px;
    display: flex;
    margin-top: 50px;
}

.rightHalf{
    width: 50%;
    position: absolute;
    right: 0px;
    height: 100%;
    
}

please i would be so grateful if you give me a hand in this problem since i still don’t master css very well.

Creating an Isoceles Triangle in Javascript with Methods and For Loops

I am working on a Javascript question from a book to build an Isoceles Triangle from methods and a for loop. The question requires that you build two methods first and then use those to create the triangle. I have the below, but it seems to be ignoring these lines:

spaces = spaces – 1;
stars = stars + 2;
because when I run it, I only get 5 lines of 3 spaces and then one asterisk.

Any help is appreciated. Thank you.

import java.util.Scanner;
class Main {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int size;
    System.out.print("What size is the triangle? ");
    size = input.nextInt();
    drawIsoTriangle(size);
   }
   public static void displaydrawBar(int length) {
    for (int i = 0; i < length; i++) {
    System.out.print("*");
    }
   }
   public static void displaydrawBar(int length, String mark) {
    for (int i = 0; i < length; i++) {
    System.out.print(mark);
    }
   }
   public static void drawIsoTriangle(int size) {
    for (int i = 0; i < size; i++) {
      int spaces = size - 1;
      int stars = 1;
      displaydrawBar(spaces, " ");
      displaydrawBar(stars);
      System.out.println();
      spaces = spaces - 1;
      stars = stars + 2;
    } 
   } 
}

javascript single-threaded , how asynchronous is implemented

It is acknowledged that JavaScript is single-threaded ,but while i try the code below, when i use setTimeout and Promise, it’s obviously that they runs asynchronously

function testTimer(){
  setTimeout(()=>{console.log(2)},100)
}
function testLoop(){
    for(let i = 0; i < 1e3; i++){}
    console.log(3)
}
function testPromise(){
     return new Promise((resolve)=>{
        for(let i = 0; i < 1e3; i++){}
        resolve();
    })
}
console.log(1)
testTimer();
testLoop();
console.log(4)
testPromise().then(()=>{console.log(5)})
console.log(6)

If javascript is completely single-threaded, the console should print 1, 2, 3, 4, 5, 6 in order. But the single threaded feature can only be seen in testLoop(), we can see that the use of Promise and setTimeout allow the code below run ahead, could someone please tell how’s this achieved?

How reset form values using react bootstrap

My goal after clicking the register button is:

  • Make input fields blank
  • Do not show error tooltips

I’ve already tried using event.target.reset(); however the tooltips are still appearing on the screen.

export default function App() {
  const [showSucessAlert, setshowSucessAlert] = useState(false);
  const [validated, setValidated] = useState(false);
  const [transitionAlert, setTransitionAlert] = useState(false);

  const handleSubmit = (event) => {
    const form = event.currentTarget;
    event.preventDefault();

    if (form.checkValidity() === false) {
      event.stopPropagation();
    } else {
      handleClickTransitionAlert();
      setshowSucessAlert(true);
    }
    setValidated(true);
  };

  const handleClickTransitionAlert = () => {
    setTransitionAlert(true);
    setTimeout(() => {
      setTransitionAlert(false);
    }, 1700);
  };

  return (
    <Form noValidate validated={validated} onSubmit={handleSubmit}>
      <Form.Group className="position-relative" controlId="validationPassword">
        <Form.Label>Password</Form.Label>
        <InputGroup hasValidation id="validationPassword" />
        <Form.Control
          type="password"
          aria-describedby="validationPassword"
          required
        />
        <Form.Control.Feedback tooltip type="invalid">
          Please enter your Password.
        </Form.Control.Feedback>
      </Form.Group>
      <Alert
        className={`mt-1 p-1 position-fixed ${
          transitionAlert ? "alert-shown" : "alert-hidden"
        }`}
        show={showSucessAlert}
        variant="success"
      >
        Registered user!
      </Alert>
      <Button className="mt-5" variant="primary" type="submit">
        Register
      </Button>
    </Form>
  );
}

enter image description here

Here is the link on CodeSandbox

Every help is welcome!

How do I get UI to update in loop using forEach

  Promise.all([
    seperatingDMCM(),
    compileDirectMessage(),
    renderingResult(),
    addResultButtonListener(),
  ]);

I have a progress bar in my UI and I have 4 functions mentioned above each of which returns a Promise. I have a loop inside the first function seperatingDMCM(), that will handle all the my data. I want to increment the progress bar with each increment of the loop. Meaning each loop iteration should be async, so the UI will update and only afterwards the loop will iterate. When the loop has ended I want to return a promise so that the other functions will begin to execute. I am facing an issue that progress bar is not working as it suppose to and is immediately being invoked when seperatingDMCM() returns the promise () and not asynchronously. This progress bar is immediately being updated to 100% on the next page instead of live updates with small increment on the current page.

This is my updateUI function:

function startProgressBar(i, arr) {
  return new Promise((resolve) => {
    setTimeout(() => {
      i = (i * 100) / arr.length;
      console.log(i);
      let elem = document.getElementById("progressBar");
      if (i < 100) {
        elem.innerText = i + "%";
        elem.style.width = i + "%";
        elem.innerHTML = i + "%";
        resolve();
      }
    }, 0);
  });
}

This is my first function where I want to update the UI per loop iteration

function seperatingDMCM() {
  const contentType = "Content type";

  return new Promise((resolve) => {
    rowObject.forEach(async (row, index) => {
      const creatingInts = () => {
        console.log("CreatedInt at", index);
        row["Date created (UTC)"] = ExcelDateToJSDate(
          row["Date created (UTC)"]
        );
        if (
          row[contentType] !== "DM" &&
          row.hasOwnProperty("Falcon user name")
        ) {
          publicCommentsCount++;
          interaction = { row : row};
          compiledInteractions.push(interaction);
          interaction = {};
        } else {
          dmData.push(row);
        }
      };

      startProgressBar(index, rowObject).then(creatingInts());
    });
    quickSort(dmData, "Falcon URL");
    console.log("SORTED", dmData);

    console.log(workbook);
    console.log("Rows", rowObject);
    resolve();
  });
}

Is there a succinct guide to the history and use of all the JavaScript package types?

I keep getting lost in the woods with all the different package types. e.g. CJS, UMD, AMD, ESM (and more?) and their compatibility matrix with varying runtime environments, when they can be used, why they were developed, etc etc. Like, I know Node.js requires CJS, UMD is used mostly in the browser and is a superset of AMD and RequireJS(?), and ESM is the future. I’m interested in diving into the nuance.

Is there a handy cheat sheet to all of the above?

The real problem which sparked that question is making a JS package which works in Node and the browser. I’m really close, but I wish I had a better understanding.

JSPDF output(‘dataurlnewwindow’) doesn’t work on safari

Greetings I have a project where I generate a DIV to PDF

But it’s not working on iPhone safari browser

the code

let ref_id = $('#print').next().html();
let HTML_Width = $(".report").width();
let HTML_Height = $(".report").height();
let top_left_margin = 1;
let PDF_Width = HTML_Width + (top_left_margin * 2);
let PDF_Height = (PDF_Width * 1.5) + (top_left_margin * 2);
let canvas_image_width = HTML_Width;
let canvas_image_height = HTML_Height;
let totalPDFPages = Math.ceil(HTML_Height / PDF_Height) - 1;
html2canvas($(".report")[0]).then(function (canvas) {
    let imgData = canvas.toDataURL("image/jpeg", 1.0);
    let pdf = new jsPDF('p', 'pt', [PDF_Width, PDF_Height]);
    pdf.addImage(imgData, 'JPG', top_left_margin, top_left_margin, canvas_image_width, canvas_image_height, 'FAST');
    for (let i = 1; i <= totalPDFPages; i++) {
        pdf.addPage(PDF_Width, PDF_Height);
        pdf.addImage(imgData, 'JPG', top_left_margin, -(PDF_Height * i) + (top_left_margin * 4), canvas_image_width, canvas_image_height);
    }
    pdf.output('dataurlnewwindow');
});

Why is my code to hide a parent div not working?

I tried following the information here, editing it to match my needs, but so far it’s not working.
I’m trying to hide a parent div with two child elements. The parent div is part of a list, all with the same classes, and each div has two child elements: an input, and an image. Each input has a unique “data-wapf-label” that I’m trying to select so that I can hide the parent div. The HTML is as follows:

<div class="has-pricing wapf-swatch wapf-swatch--image">
  <input type="radio" id="wapf-field-61b148f2fc8fe_lzhx7" name="wapf[field_61b148f2fc8fe]" class="wapf-input" data-field-id="61b148f2fc8fe" value="lzhx7" data-wapf-label="Peppermint Mocha" data-is-required data-wapf-pricetype-"fx">
  <img src="...">
</div>

There are several pages where this product shows up, and rather than going in and deleting the product field (because I’ll just have to add it again next season), I’m trying to create a piece of code that will hide all the divs for all the products that have the above code (since each has a unique “id”, I’d have to do it several times for each id using “selectElementById”, and I’d like to avoid doing that, obviously).

I installed Code Snippets, but I’m having a bit of trouble with the Javascript. I’ve tried several things, but this is my latest version. It throws a syntax error “unexpected ‘hideFlavors’ (T_STRING), expecting ‘(‘”.
Here’s my php/Javascript code:

<?php
add_action( 'wp_head', function hideFlavors() { ?>
<script>
    if var peppermintMocha = document.querySelectorAll("[data-wapf-label='Peppermint Mocha']") {
    peppermintMocha.parentNode.style.display = "none"; 
    }
</script>
<?php } );

I’ve also tried it with “document.querySelector” (without the “All”), but with the same or similar problem. When I do get the code to actually go through without any errors, it still doesn’t fix the problem.
At this point, I feel a little like the guy looking through the tank’s periscope on “Independence Day”. No matter what I do, “target remains”.