Custom caret position misaligned on web page

I found this cool demo website that emulated a terminal. So, naturally I copy-pasted it into my editor to toy around with it. I understand the code and how it works well enough. However, I discovered a small but annoying visual error. The longer the line your typing on gets the more misaligned the caret will be when trying to reposition to the left with the left arrow key. Example below.

misaligned caret

This is where the caret should be.

enter image description here

I have tried multiple different font-sizes and monospaced fonts to no avail. The differing font-sizes simply made the alignment worse. I even tried measure the character widths with no success. The individual characters would all be the same size but multiple characters together would somehow be smaller than predicted. I have also tried messing with the offset in caret.js, nothing seems to work. So, I am thinking this is probably a styling issue?

The reason I say this is because you are typing into a textarea, but it is position off screen and each character is copied into a span element with each keystroke. So, any suggestions, solutions, or even alternatives would be much appreciated. I have provided the relevant files below. Command.js is just a file with a bunch of strings and Main.js shouldn’t be necessary here. If anyone feels otherwise let me and I will provide it as well.

Index.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1" />
        <title>Terminal</title>
        <link rel="stylesheet" type="text/css" media="screen" href="css/style.css" />
    </head>
    <body>
        <div id="terminal">
            <a id="before"></a>
        </div>
        <div id="command" onclick="$('texter').focus();">
            <textarea
                type="text"
                id="texter"
                onkeyup="typeIt(this, event)"
                onkeydown="typeIt(this, event); 
                        moveIt(this.value.length, event)"
                onkeypress="typeIt(this, event);"
                autofocus
            ></textarea>
            <div id="liner">
                <span id="typer"></span><b class="cursor" id="cursor">L</b>
            </div>
        </div>
        <script src="js/command.js"></script>
        <script src="js/caret.js"></script>
        <script src="js/main.js"></script>
    </body>
</html>

Style.css

body {
    margin: 0;
    padding: 15px 20px 15px 20px;
    min-height: 99%;
    width: 99%;
    min-width: 550px;
    color: #519975;
    background: #211D1B;
    font-family: cursor, monospace, monospace !important;
    font-size: 16px !important;
    overflow-x: hidden;
}
::selection {
    color: #211830;
    background-color: #519975;
}
::-moz-selection {
    color: #211830;
    background-color: #519975;
}
textarea {
    left: -1000px;
    position: absolute;
}
b {
    font-weight: bold;
    text-decoration: underline;
}

/* Cursor Start */
.cursor {
    /* font-size: 13px; */
    color: #4fa5a8;
    background-color: #4fa5a8;
    position: relative;
    opacity: 1;
    height: 1.5em;
    width: 10px;
    max-width: 10px;
    transform: translateY(5px);
    overflow: hidden;
    text-indent: -5px;
    display: inline-block;
    text-decoration: blink;
    animation: blinker 1.3s linear infinite;
    /*border: #4c01c4;
    border-radius: 5px;
    border-style: dotted;*/
}
@keyframes blinker {
    50% {
      opacity: 0;
    }
}
#command {
    cursor: text;
    height: 50px;
    color: #73ABAD;
    /*border: #4c01c4;
    border-radius: 5px;
    border-style: dotted;*/
}
#liner {
    line-height: 1.4em;
    animation: show 0.5s ease forwards;
    animation-delay: 0.5s;
    opacity: 0;
    /*letter-spacing: 0.05em;*/
    /*border: #01bec4;
    border-radius: 5px;
    border-style: dotted;*/
}
#liner::before {
    color: #519975;
    content: "visitor:~$";
}
#liner.password::before {
    content: "Password:";
}
@keyframes show {
    from {
      opacity: 0;
    }
    to {
      opacity: 1;
    }
}
/* Cursor End */
  
p {
    display: block;
    line-height: 1.3em;
    margin: 0;
    overflow: hidden;
    white-space: nowrap;
    /*letter-spacing: 0.05em;*/
    animation: typing 0.5s steps(30, end);
}
.no-animation {
    animation: typing 0 steps(30, end);
}
.margin {
    margin-left: 20px;
}
@keyframes typing {
    from {
      width: 0;
    }
    to {
      width: 100%;
    }
}
.index {
    color: #DCDCCC;
}
.color2 {
    color: #B89076;
}
.command {
    color: #73ABAD;
    text-shadow: 0 0 5px #73ABAD; 
}
.neon {
    color: #b29b6e;
    text-shadow: 0 0 7.5px #b29b6e; 
}
.error {
    color: #B89076;
}
.white {
    color: #fff;
}
.inherit, a {
    color: #9C8394;
}
a {
    text-decoration: inherit;
}
a:hover {
    background: #73ABAD;
    color: #211830;
}
a:focus {
    outline: 0;
}

Caret.js

function $(elid) {
    return document.getElementById(elid);
  }
  
var cursor;
window.onload = init;

function init() {
  cursor = $("cursor");
  cursor.style.left = "0px";
}

function nl2br(txt) {
  return txt.replace(/n/g, '');
}

var audio2 = new Audio("audio/chat_type1.wav")
audio2.volume = 0.75;

function typeIt(from, e) {
  e = e || window.event;
  var w = $("typer");
  var tw = from.value;
  if (!pw){
    audio2.play();
    w.innerHTML = nl2br(tw);
  }
}

function moveIt(count, e) {
  console.log(count);
  e = e || window.event;
  var keycode = e.keyCode || e.which;
  if (keycode == 37 && parseInt(cursor.style.left) >= (0 - ((count - 1) * 10))) {
    console.log(parseInt(cursor.style.left));
    cursor.style.left = parseInt(cursor.style.left) - 10 + "px";
  } else if (keycode == 39 && (parseInt(cursor.style.left) + 10) <= 0) {
    cursor.style.left = parseInt(cursor.style.left) + 10 + "px";
  }
}

function alert(txt) {
  console.log(txt);
}

Run function within custom hook when a function passed from parameters is called

is there any way to accomplish the following without using a “hacky” solution?

It has to be done this way due to how I plan on using the stepper.

export interface StepperProps {
  steps: StepData[];
  nextStep: () => void;
  prevStep: () => void;
}

export const Stepper = ({ steps, nextStep, prevStep }: StepperProps) => {
  const [currentStep, setCurrentStep] = useState(1);

  // when nextStep is called, pasoActual++
  // when prevStep is called, pasoActual--

  return "Not important right now";
};

I was able to do this by returning a different value with nextStep and prevStep every time they were called, however, there might be a better way to achieve this.

Firebase .length broken on infinate scroll

my NextJs site keeps throwing error due to firebase infinate scroll. .length being undefinded for some unknown reaseon. please help debug the code if possible. Its been a mess trying to get this dmn stuff to work in nextjs.

useEffect(() => {
    
    // This useEffect is used to get the todos for the user
    try {
      if (!firestore) return;
      // Only execute the query if we have an user
      const querySubmissions = query(
            collection(firestore, "roadmap"),
            where("csite", "==", router.query.csite),
            where("uid", "==", router.query.uid),
            orderBy("createdAt", "desc"),
            limit(10)
          );
      if (!querySubmissions) return;
      const unsubscribe = onSnapshot(querySubmissions, (querySnapshot) => {
        setSubmissions(querySnapshot.docs);
      });
      return () => unsubscribe();
    } catch (error) {
      console.log(error);
    }
  }, [router]);


// -------------------- unessesary code removed between -------------------------------------


  useEffect(() => {

  window.onscroll = () => {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
  console.log('bottom');
    setIsLoadingData(true);
    const lastDocument = submissions.data().length - 1;
    const documents = query(
      collection(firestore, "roadmap"),
      where("csite", "==", router.query.csite),
      where("uid", "==", router.query.uid),
      orderBy("createdAt", "desc"),
      limit(10),
      startAfter(lastDocument)
    );
    const unsubscribe = onSnapshot(documents, (querySnapshot) => {
      setSubmissions(submissions => submissions.concat(querySnapshot.docs));
      setIsLoadingData(false);
    });
    return () => unsubscribe();
  }
  };
  }, [router]);

Please help.

I was expecting infinate scroll when creating this code in VSCode.

Hover on Elements with JavaScript

Hello. I want to scale the penguin on :hover like this:

#penguin {
  width: 100px;
}
#penguin:hover {
  transform: scale(1.04);
}
<img id="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">

But my problem is that I want to include the scale in JavaScript and not in CSS. I tried it with style.transform = 'scale(1.04)'; but it’s not working.

document.getElementById('penguin').style.transform = 'scale(1.04)';
#penguin {
  width: 100px;
}
<img id="penguin" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b0/NewTux.svg/1707px-NewTux.svg.png">

The reason I want to put it in JavaScript is because I have an image that acts as a button. The opacity is 10%. When an event occurs it becomes 100% and should then achieve the :hover effect.

How to change background color of React Awesome Slider Component

How do I change the background color of the React Awesome Slider component I tried overwritng the css I tried using !important tag here am I missing something like I cannot find out what property it is to overwrite the background color style. Does anyone know how to do this?

here is my component using the Awesome Slider component:

import styles from "../style";
import AwesomeSlider from "react-awesome-slider";
import 'react-awesome-slider/dist/styles.css';
import React, { useRef, useState } from 'react';
import '../index.css'
import 'react-awesome-slider/dist/custom-animations/cube-animation.css';

const Component = () => {

  const sliderStyle = {
    backgroundColor: 'red !important',   
  };
 
  return (
  <section id="top-level" ref={sectionRef} className={`${styles.paddingY} ${styles.flexCenter} flex

    <div className="flex flex-wrap sm:justify-start justify-center w-full feedback-container relative z-[1] ">
      <AwesomeSlider className="slider" style={sliderStyle} bullets={false} mobileTouch={true} animation="cubeAnimation" >
        {array.map((card) => (
          <div key={card.id}>
            <AnotherComponent {...card} />
          </div>
        ))}
      </AwesomeSlider>
    </div>
  </section>
);}

export default Component;

How i can solve this error in HTML, google signin new library. Problem with signout button

I have this HTML and JS code:

<script src="https://accounts.google.com/gsi/client" async defer></script>
                            <div class="loginButton" id="loginButton">
                                <div id="g_id_onload"
                                     data-client_id="314858521059-0ss42dso5d8hn5992mjf5qkcnnhge1vq.apps.googleusercontent.com"
                                     data-callback="handleCredentialResponse" data-auto_prompt="false"></div>
                                <div class="g_id_signin" data-locale="en" data-type="standard" data-size="large"
                                     data-theme="filled_black" data-text="sign_in_with" data-shape="circle"
                                     data-onsuccess="handleCredentialResponse"></div>
                            </div>

And JS code:

function signOut() {
                var auth2 = gapi.auth2.getAuthInstabce();
                auth2.signOut().then(function(){
                    alert("Test sign out");
                    $(".g-signin2").css("display", "block");
                    $(".data").css("display", "none");
                });
            }

And in conclusion i have this problem in my console, when i want to press log out button:
Uncaught ReferenceError: gapi is not defined at signOut (about.html:225:29) at HTMLButtonElement.onclick (about.html:189:75)

Thank you in advance!

I was trying to find some resourses to solve this problem, but every time i had the same result as you can see.

Error Message Not Sending to FrontEnd From NodeJS Server

I have a nodejs server with a controller and a service. I am trying to propogate the error received from the server file and pass it to the frontend for to display. The issue is, I am unable to receive the error in the frontend and get an internal server error instead. I have tried various methods to correct this but it didnt work. Can someone explain what i am doing wrong?

my controller is:

function moveTable(req, res, next) {
  const payload = jwtDecode(req.headers.authorization.split(' ')[1]);
  authService.getAuthToken(payload.sub)
      .then(token => cloverOrderService.moveTable(req.body, token.merchantId,token.cloverToken))
      .then(data => res.send(data))
      .catch(err => next(err));
}

my service code is:

    async function moveTable(data, merchantId, cloverToken) {

    let newMain = await retryOrderWithDifferentName(data.updatedTableName, merchantId, cloverToken, images, true);

    if(!newMain.order) {
        return {
            updatedMain: main.order ? await updateOrder(main, merchantId, cloverToken) : '';
        }
    } else {
        throw new Error('Order Already Exists For Table ' + data.updatedTableName);
    }
}

in the .catch in the controller to send a custom error code and response as below but the response code sends but I don’t receive the custom message:

  .catch(err => res.status(404).json({error :'No such user exists' +err}));

Appointment availability considering multiple chairs/rooms and a provider who is only required for a portion of the time

I need help thinking through the logic and how optimize scheduling which allowing 1 provider to see customers in 2 different chairs with overlapping start/end times. The challenge is that a provider may only be required for a portion of a given appointment.

Resources: 2 Chairs, 1 Provider
In the example below, we have 4 appointments. The Customer (CUST #) will occupy the chair for the duration of the appointment; however, provider is only occupied for for a portion of the time. The (X) denotes the 15 minute increments the provider is needed and otherwise unavailable and the (/) denotes 15 minute increments the provider is not needed and is available to see other customers.

Now, let’s say I’m a user looking to book a 60 minute appointment in which we only need the provider for the third 15 minute increment (pattern of (/)(/)(X)(/)). We know we need a chair that’s available for 60 minutes. However, the challenge I’m finding is ensuring the provider is available during that 15 minute increment in which they are needed. See below for a visual break down. I can’t seem to wrap my mind around the logic required.

APPOINTMENT TO BOOK: 60 Minutes where the provider is needed for a 15 minute portion as denoted by the (X) in the following pattern: (/)(/)(X)(/)

Expected availability based on current schedule:

  • 10:30AM-11:30AM
  • 11:15AM-12:15PM
  • 11:30AM-12:30PM

CURRENT SCHEDULE:

Chair 1 Chair 2
CUST 1 (/) CUST 2 (X)
CUST 1 (/) CUST 2 (X)
CUST 1 (X) CUST 2 (/)
CUST 1 (/) OPEN
CUST 1 (/) OPEN
CUST 1 (/) OPEN
OPEN CUST 3 (/)
OPEN CUST 3 (X)
OPEN CUST 3 (/)
OPEN OPEN
CUST 4 (/) OPEN
CUST 4 (/) OPEN
CUST 4 (/) OPEN
CUST 4 (/) OPEN
CUST 4 (X) OPEN
CUST 4 (/) LUNCH BLOCK
OPEN LUNCH BLOCK
OPEN OPEN

INPUTS:

  1. List of existing scheduled appointment objects which include the appointment start time, chair, and pattern as I’ve defined above.
  2. List of provider schedule objects which is their working hours for a chair or chairs.
  3. List of blockout objects for lunch, breaks, etc. for a chair or chairs.
  4. Appointment to be scheduled. An object with a pattern as defined above.

If it matters, I’m using Javascript with moment.js.

Javascript – using form input value within a modal

I keep getting this error: Uncaught TypeError: Cannot set properties of null (setting ‘innerHTML’)

or: Uncaught TypeError: Cannot set properties of null (setting ‘textContent’)

When trying to change the text of an anchor tag after a modal opens.

Here’s the modal:

 <!-- Success Modal -->
    <div class="modal-container" id="modal">
        <div class="modal-main">
            <img
                src="./assets/images/icon-success.svg"
                alt="success image"
            />
            <h1 class="modal-header">Thanks for subscribing!</h1>
            <p>
                A confirmation email has been sent to
                <a href="#" id="modal-email">test</a>. Please open it and
                click the button inside to confirm your subscription.
               
            </p>
        </div>
        <button id="dismiss-btn">Dismiss message</button>
    </div>

The Form:

   <form id="form">
            <label for="email">Email address</label>
            <input
                type="email"
                name="email"
                id="email"
                placeholder="[email protected]"
            />
            <button id="button">Subscribe to monthly newsletter</button>
        </form>

and the Javascript:

const form = document.getElementById("form");
const btn = document.getElementById("button");
const dismissBtn = document.getElementById("dismiss-btn");
const modal = document.getElementById("modal");
const modelEmail = document.getElementById("model-email");

form.addEventListener("submit", function (e) {
    e.preventDefault();
    modal.style.display = "block";

    let formData = new FormData(this);
    let inputValue = formData.get("email");

    console.log(inputValue);
    modelEmail.textContent = "example";
});

dismissBtn.onclick = function () {
    modal.style.display = "none";
};

The correct value appears in the console when console logging the inputValue, but I keep getting errors when trying to change the textContent of the anchor tag in the modal. Whether I use the inputValue or [in this case] the string of “example”, I keep getting the null error.

Cant run my code because of a uncaughtTypeError [duplicate]

Ok so here’s the deal, I am trying to make this shopping cart app; because why not? And I made my code exactly as it was meant to be done, but when I tried running it, the error report says there is some code that I have not made yet, or that there is noting within the innerHTML. Here’s how it reads “uncaughtTypeError; cannot set properties of null(setting innerHTML) I am using HTML, css, and JavaScript.

Heres the source code:

* {
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

body {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}

.header {
  height: 80px;
  width: 70%;
  background-color: goldenrod;
  border-radius: 3px;
  margin: 30px 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
}

.header .logo {
  font-size: 30px;
  font-weight: bold;
  color: #fff;
}

.cart {
  display: flex;
  background: #fff;
  justify-content: space-between;
  align-items: center;
  padding: 7px 10px;
  border-radius: 3px;
  width: 80px;
}

.cart p {
  height: 22px;
  width: 22px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 22px;
  background-color: goldenrod;
  color: #fff;
}

.container {
  display: flex;
  width: 70%;
  margin-bottom: 30px;
}
<!Doctype html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>cart</title>
  <link rel="stylesheet" href="macally.css">
</head>

<body>
  <div class="header">
    <p class="logo">Bomber Jacket</p>

    <div class="cart"><svg xmlns="http://www.w3.org/2000/svg" width="21" height="21" fill="currentColor" class="bi bi-cart4" viewBox="0 0 16 16">
  <path d="M0 2.5A.5.5 0 0 1 .5 2H2a.5.5 0 0 1 .485.379L2.89 4H14.5a.5.5 0 0 1 .485.621l-1.5 

6A.5.5 0 0 1 13 11H4a.5.5 0 0 1-.485-.379L1.61 3H.5a.5.5 0 0 1-.5-.5M3.14 5l.5 2H5V5zM6 

5v2h2V5zm3 0v2h2V5zm3 0v2h1.36l.5-2zm1.11 3H12v2h.61zM11 8H9v2h2zM8 8H6v2h2zM5 8H3.89l.5 2H5zm0 

5a1 1 0 1 0 0 2 1 1 0 0 0 0-2m-2 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0m9-1a1 1 0 1 0 0 2 1 1 0 0 0 0-2m-2

 1a2 2 0 1 1 4 0 2 2 0 0 1-4 0"/>
</svg>
      <p id="count">0</p>
    </div>
  </div>
  <div class="container">
    <div class="root"></div>
    <div class="sidebar">
      <div class="head">
        <p>My cart</p>
      </div>
      <div id="cartItem">Your cart is empty</div>
      <div class="foot">
        <h3>Total</h3>
        <h2 id="total">$ 0.00</h2>
      </div>
    </div>
  </div>

  <script type="text/javascript">
    const product = [{
        id: 0,
        image: 'product/sonic.jpg',
        title: 'Sonic outfit kids',
        price: 30,
      },
      {
        id: 1,
        image: "product/bomber-jacket.jpg",
        title: "bomber-jacket",
        price: 65,
      },
      {
        id: 2,
        image: "product/echo.jpeg",
        title: "amazon echo device",
        price: 50,
      }
    ];

    const categories = [...new Set(product.map((item) => {
      return item
    }))]

    let i = 0;
    document.getElementById('root').innerHTML = categories.map((item) => {
      let {
        image,
        title,
        price
      } = item;

      return (
        `<div class='box'>
                        <div class='img-box'>
                            <img class='images' src=${image}></img>
                            </div>
                            <div class= 'bottom'>
                            <p>${title}</p>
                            <h2>$ ${price}.00</h2>` +
        "<button onclick= 'addtocart(" + (i++) + ")'>Add to cart</button>" +
        `</div>
                            </div>`
      )
    }).join('')
  </script>
</body>

</html>

I tried running it, but I dosent do anything, I have alredy reviewed the procedure to make sure I wrote my code correctly and I did. I just cant fugure out what I am missing.

How to interact with the content of an iframe (specifically with images here)

I know this question has been asked before but my situation is a bit more complicated as it involves switching between the iframes kinda?

Basically i have a main page called index.html
Here is it’s code:
https://codepen.io/doresolre/pen/NWoZVOL

<style> 
.main {
    height: 480px;
    width: 753px;
    background-image: url('https://files.catbox.moe/boh6j7.jpg');
    position: relative;
}

.main iframe {
    border: none;
    border: none;
    position: absolute;
    top: 35px;
    left: 7px;
    width: 739px;
    height: 439px;
</style>    
    <div class="wrapper">
        <div class="header">
            <a href="home.html" target="content"><img src="https://files.catbox.moe/2ec24l.gif" class="header-image"></a>
            <div class="menu">
                <a href="entrence.html" target="content">Home</a> / 
                <a href="test2.html" target="content">Portfolio</a> / 
                <a href="about.html" target="content">Interests</a> / 
                <a href="links.html" target="content">More</a>
            </div>
        </div>
        <div class="main">
            <iframe name="content" src="entrence.html"></iframe>
        </div>
    </div>
</body>
</html>

As you can see inside of index.html there’s an iframe that switches between pages but the outside of the iframe stays the same.

Now, one of the pages that takes place in the iframe is a photo gallery. When you click on the photo at the top left, another pop-up draggable window appears with another iframe that tell you more about the picture like this:
https://codepen.io/doresolre/pen/NWoZVeO

    <script>
        window.onload = function () {
            var draggableDiv = document.getElementById("myWindow");
            var specificImage = document.getElementById("specificImage");
            var closeButton = document.querySelector(".red");
          
            specificImage.addEventListener("click", function () {
                draggableDiv.style.display = "block"; // Display the window on click
            });
          
           closeButton.addEventListener("click", function () {
                draggableDiv.style.display = "none"; // Hide the window on red button click
            });

            var posX = 0,
                posY = 0;
            var draggable = false;

            draggableDiv.addEventListener("mousedown", function (event) {
                draggable = true;
                posX = event.clientX - draggableDiv.offsetLeft;
                posY = event.clientY - draggableDiv.offsetTop;
            });

            window.addEventListener("mousemove", function (event) {
                if (draggable) {
                    draggableDiv.style.left = event.clientX - posX + "px";
                    draggableDiv.style.top = event.clientY - posY + "px";
                }
            });

            window.addEventListener("mouseup", function () {
                draggable = false;
            });
        };
    </script>
 <section class="tiles-a">
        <ul>
            
            <li>
                <a href="#" id="specificImage" style="background: url('my image'); background-size: cover;">
                </a>
            </li>
            
            <li>
                <a href="#" style="background: url('my image'); background-size: cover;">
                </a>
            </li>
            
            <li>
                <a href="#" style="background: url('my image'); background-size: cover;">
                </a>
            </li>
            
            <li>
                <a href="#" style="background: url('my image'); background-size: cover;">
                </a>
            </li>
            
            <li>
                <a href="#" style="background: url('my image'); background-size: cover;">
                </a>
            </li>
            
            <li>
                <a href="#" style="background: url('my image'); background-size: cover;">
                </a>
            </li>
            
        </ul>
    </section>
  
</body>

</html>



However, since the second iframe is included in another iframe it ends up looking like this:failed iframe in frame
To give you an idea of what i’d like it to look like this is another site a found that has the same idea: https://prevuefrix.neocities.org
Here, when you click on view a pop up opens with a draggable besides the index page

So basically my problem is I’d like for the window page (=the second iframe) to be outside of both the iframes, even tho it appears when you click an image that’s inside the first iframe if that makes sense (i’ll answer any comments if you need more explaining)

How to stop modal from going to top of screen on button click

I am having a persistent issue regarding jquery modals. Whenever I click on the button with the name test, the modal does show up as I want it to do but it goes to the very top of the screen. Here is the primary code:

index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <link rel="stylesheet" href="assets/style.css">
    <link href='https://unpkg.com/[email protected]/css/boxicons.min.css' rel='stylesheet'>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/devicons/[email protected]/devicon.min.css">
    <script src="//code.jquery.com/jquery-3.7.1.min.js"></script>
    <link rel="stylesheet" href="assets/jquery/jquery-modal-master/jquery.modal.min.css" ></link>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-modal/0.9.2/jquery.modal.min.js"></script>
    <title>Local Portfolio</title>
</head>

<body>

<div class="card">
                <div class="info">
                    <h1>Java Paint</h1>
                    <img src="imgs/java_paint.png" alt="Java Paint">
                    <a href="#java_paint">More Information</a>
                    <button id = "java_paint_modal" type="button">Test</button>
                </div>
</div>


 <form id="java_paint" class="modal">
        <h2>About</h2>
        <p>
            A painting app programmed in Java using the Swing Library and Eclipse IDE. Allows the user to draw with a size adjustable pencil as well as changing the its color,
            picking a color from the screen and storing it for later use via the rectangle icon in the menu, erase contents as well as drawing a stroke adjustable line and with more features to come in the forseeable future
        </p> 
    </form>
</body>

script.js:


$(document).on('click','#java_paint_modal', function(event) {
    event.preventDefault();
    console.log("greetings")
    $("#java_paint").modal();
});

Keep in mind that i intially used an anchor tag but even thought i switched to a button, it still goes to the top of the screen

I am running this on the Opera GX browser incase it could be a browser issue

To see the issue in action, here is the repo and the website

Creating Chrome Extension that generates a popup when highlighting text

I’m trying to create a Chrome extension that generates a popup on the webpage (not the browser extension popup) whenever text is highlighted on any page. The popup should, ideally, come up right near the selected text and should work on any p tag elements on any page. I’m having a hard time creating this (I’m new to JavaScript and running into various issues).

The popup should perform like it does in this codepen when you highlight text: https://codepen.io/jankees/pen/YzrpdVb (taken from another Stack Overflow post)

Here’s the JS code from that Codepen:

if (!window.x) {
    x = {};
}

x.Selector = {};
x.Selector.getSelected = function() {
    var t = '';
    if (window.getSelection) {
        t = window.getSelection();
    } else if (document.getSelection) {
        t = document.getSelection();
    } else if (document.selection) {
        t = document.selection.createRange().text;
    }
    return t;
}

var pageX;
var pageY;

$(document).ready(function() {
    $(document).bind("mouseup", function() {
        var selectedText = x.Selector.getSelected();
        if(selectedText != ''){
            $('ul.tools').css({
                'left': pageX + 5,
                'top' : pageY - 55
            }).fadeIn(200);
        } else {
            $('ul.tools').fadeOut(200);
        }
    });
    $(document).on("mousedown", function(e){
        pageX = e.pageX;
        pageY = e.pageY;
    });
});

I’m running into several noob errors so explanations on how to do this (for example, how to implement this across multiple pages vs. a static HTML file like the codepen) would be hugely beneficial.

Thank you in advance!

Regex – Strip out commas and spaces from ’empty’ address fields

I am using a third party address lookup service that provides address data in the following format:

'addr line one, , , , city, county, postcode, addr line one, addr line two, , , city, county, postcode, addr line one, , , , city, county, postcode, addr line one, addr line two ,addr line three, addr line four, city, county, postcode'

As you can see from the data, often there are ’empty’ fields that are still delimited by a comma followed by a space.

I am looking to produce the following output:

'addr line one, city, county, postcode, addr line one, addr line two, city, county, postcode, addr line one, city, county, postcode, addr line one, addr line two, addr line three ,addr line four, city, county, postcode'

I have two choices, either a recursive replace function that replaces , , with ,
or use a regex to filter the string.

I would imagine that the regex would be the better solution, but I am at a loss as to how to create a regex that would filter this string correctly.