How to keep range selected when using input in js

I am using an contenteditable div and i want to change the font size of selected range by typing font size in an input. But when i click on input after selecting a range it deselects.

function changeFontSize() {
    let fontSize = `${document.getElementById('size').value}px`
    let input = document.getElementById('size')
    var selection = window.getSelection();
    console.log(fontSize)
    if (selection.rangeCount) {
        var range = selection.getRangeAt(0);
        var content = range.extractContents();
        var span = document.createElement('span');
        span.style.fontSize = fontSize;
        range.insertNode(content);

The font size of selected range should change every time I change the value in input and the range should remain selected at that time.

Is it possible to add text with angle brackets at the front and end without it being detected as an element? [duplicate]

I’m trying to add text to my site that includes angle brackets (for example: “<a_username>”), but it keeps getting recognized as an element.

Is there anyway to prevent that?

In my code, I’m trying to write a <p> that says:

<p><span><server> Welcome.</span></p>

but obviously, <server> is being detected as an element.

Continue Watching Section Displays All Videos Instead of Last Clicked Video – JavaScript/HTML

I’m working on a web application where users can watch videos, and I have a “Continue Watching” section that should display the last clicked video. However, instead of showing only the last clicked video, it’s displaying all eight videos in the “Continue Watching” space.

I’ve tried to implement a logic that saves the last clicked video in the lastWatchedVideos array and updates the “Continue Watching” section accordingly. Unfortunately, it seems to be loading all videos rather than just the last one.

Here’s the relevant JavaScript code snippet responsible for handling video clicks and updating the “Continue Watching” section:

 <script>
      let loaded = false;
      let currentPage = 1;
      const videosPerPage = 8; // Display only 4 videos
      let loadedVideos = [];
      let lastWatchedVideos = [];

      if (localStorage.getItem('lastWatchedVideos')) {
        lastWatchedVideos = JSON.parse(localStorage.getItem('lastWatchedVideos'));
      }

      function setDefaultInfo(videoId) {
        // Function to set default information if details are not available
        const videoTitle = document.getElementById(`video-title-${videoId}`);
        const videoDescription = document.getElementById(`video-description-${videoId}`);
        const videoThumbnail = document.getElementById(`video-thumbnail-${videoId}`);

        if (videoTitle && videoDescription && videoThumbnail) {
          videoTitle.innerText = "No Title Found";
          videoDescription.innerText = "No Description Found";

          videoThumbnail.src = `images/thumbnails/${videoId}.jpg`;
          videoThumbnail.alt = "Video Title";
          videoThumbnail.className = "video-thumbnail";

          console.log(`Default info set for video ${videoId}`);
        }
      }

      function playVideo(videoId) {
        if (!loaded) {
          const videoPlayer = document.getElementById('video-player');
          const videoTitle = document.getElementById(`video-title-${videoId}`);
          const videoDescription = document.getElementById(`video-description-${videoId}`);
          const videoThumbnail = document.getElementById(`video-thumbnail-${videoId}`);

          if (videoPlayer && videoTitle && videoDescription && videoThumbnail) {
            fetch(`details/${videoId}.json`)
              .then((response) => {
                if (!response.ok) {
                  throw new Error(`HTTP error! Status: ${response.status}`);
                }
                return response.json();
              })
              .then((data) => {
                console.log('Fetched data:', data);

                const { title, description, thumbnail, videoSrc } = data;

                if (videoSrc) {
                  videoPlayer.src = videoSrc;
                }

                videoTitle.innerText = title || 'No Title Found';
                videoDescription.innerText = description || 'No Description Found';
                videoThumbnail.src = thumbnail || `images/thumbnails/${videoId}.jpg`;

                loaded = true;
              })
              .catch((error) => {
                console.error('Error fetching video details:', error);
                setDefaultInfo(videoId);
              });
          } else {
            console.error(`One or more elements not found for video ${videoId}`);
          }
        } else {
          console.log(`Video ${videoId} clicked or loaded.`);
        }

        // Add the following lines to track the last four videos
        if (!lastWatchedVideos.includes(videoId)) {
            // Save the clicked video in user data
            lastWatchedVideos.unshift(videoId);
            if (lastWatchedVideos.length > 4) {
                lastWatchedVideos.pop();
            }

            // Save updated lastWatchedVideos to localStorage
            localStorage.setItem('lastWatchedVideos', JSON.stringify(lastWatchedVideos));
        }

        // Update the "Continue Watching" section
        updateContinueWatching();
      }
      
      function updateContinueWatching() {
          const continueWatchingSection = document.getElementById('continue-watching');
          continueWatchingSection.innerHTML = '<div id="video-player">Continue Watching:</div>';

          if (lastWatchedVideos.length === 0) {
              displayNoVideosMessage(continueWatchingSection);
              return;
          }

          const lastVideoId = lastWatchedVideos[0];

          const videoCard = document.createElement('div');
          videoCard.classList.add('video-card', 'continue-watching');
          videoCard.onclick = () => playContinueWatchingVideo(lastVideoId);

          fetchVideoDetails(lastVideoId).then((data) => {
              if (!data) {
                  displayNoVideosMessage(continueWatchingSection);
                  return;
              }

              const { title, description, thumbnail } = data;

              videoCard.innerHTML = `
                  <img src="${thumbnail || `images/thumbnails/${lastVideoId}.jpg`}" alt="Video ${lastVideoId}" class="video-thumbnail" />
                  <div class="video-details">
                      <div class="video-title">${title || 'No Title Found'}</div>
                      <div class="video-description">${description || 'No Description Found'}</div>
                  </div>
              `;

              continueWatchingSection.appendChild(videoCard);
          });
      }



      function playContinueWatchingVideo(videoId) {
        // Add specific logic for "Continue Watching" videos if needed
        // This function will be called when clicking on a "Continue Watching" video card
        playVideo(videoId);
      }

      // Function to fetch video details
      function fetchVideoDetails(videoId) {
        return fetch(`details/${videoId}.json`)
          .then((response) => {
            if (!response.ok) {
              throw new Error(`HTTP error! Status: ${response.status}`);
            }
            return response.json();
          })
          .catch((error) => {
            console.error('Error fetching video details:', error);
            return {};
          });
      }

      // Ensure that the lastWatchedVideos array is updated on page load
      window.addEventListener('DOMContentLoaded', () => {
        if (loadedVideos.length === 0) {
          displayAllVideosMessage();
          updateContinueWatching();
        }
      });

      function loadVideos() {
        for (let i = 1; i <= videosPerPage; i++) {
          const videoIndex = (currentPage - 1) * videosPerPage + i;
          if (!loadedVideos.includes(videoIndex)) {
            playVideo(`video${videoIndex}`);
            loadedVideos.push(videoIndex);
          }
        }
      }

      function handleScroll() {
        const lastVideoCard = document.querySelector('.video-card:last-child');
        const lastCardOffset = lastVideoCard.offsetTop + lastVideoCard.clientHeight;
        const pageOffset = window.pageYOffset + window.innerHeight;

        if (pageOffset > lastCardOffset - 100 && !loaded) {
          loaded = true;
          loadVideos();
          currentPage++;
        }
      }

      function displayAllVideosMessage() {
        const videoContainer = document.getElementById('video-container');
        const message = document.createElement('p');
        message.innerText = 'All videos in our database are loaded! :p';
        videoContainer.appendChild(message);
      }

      // Check if all videos are loaded and display a message
      window.addEventListener('DOMContentLoaded', () => {
        if (loadedVideos.length === 0) {
          displayAllVideosMessage();
        }
      });

      function toggleSideMenu() {
        const sideMenuOverlay = document.getElementById('side-menu-overlay');
        const sideMenu = document.getElementById('side-menu');

        if (sideMenuOverlay.style.display === 'block' || sideMenu.style.display === 'block') {
          sideMenuOverlay.style.display = 'none';
          sideMenu.style.display = 'none';
        } else {
          sideMenuOverlay.style.display = 'block';
          sideMenu.style.display = 'block';
        }
      }

      function closeSideMenu() {
        const sideMenuOverlay = document.getElementById('side-menu-overlay');
        const sideMenu = document.getElementById('side-menu');

        sideMenuOverlay.style.display = 'none';
        sideMenu.style.display = 'none';
      }

      function displayNoVideosMessage(continueWatchingSection) {
        const message = document.createElement('p');
        message.innerText = 'No videos found!';
        continueWatchingSection.appendChild(message);
      }

      // Initial load of videos
      loadVideos();

      // Add scroll event listener
      window.addEventListener('scroll', handleScroll);
    </script>


I’ve also included the main structure of the HTML and JavaScript code, but the issue seems to be in the logic for updating the “Continue Watching” section.

Any help or suggestions on how to fix this issue would be greatly appreciated. Thank you!

Creating an employee roster in Python or JS? [closed]

I’m trying to create an interactive roster for my company which includes various locations and staff qualification, using python or JS code. For example, I work for an aircraft maintenance firm where engineers need to be moved to different locations and have different aircraft specialization that impact the operation.

10 Engineers qualified on various Airbus and Boeing aircraft that need to be moved throughout 5 airport locations. Each airport has particular requirements. For example, airport one needs Boeing 737, and airport two needs Airbus A320. If I move engineers, how will it affect the operation.

Does that make sense? Not sure if its even possible, just wanted to reach out to the professionals here.

Thanks in advance

I searched online through forums.

Im Try to use touch in java script web aplication, but im stuck in a detail

Im trying to make a java script game, I started following a tutorial, but now I’m going to do it for mobile and for some reason I can’t change the movement of the player from the keys to touch, I’ve even tried GPT, but even it didn’t help me, my code has this part commented in English, because I’m learning the language and part of it in Portuguese because I’m Brazilian

var DIRECTION = {
    IDLE: 0,
    UP: 1,
    DOWN: 2,
    LEFT: 3,
    RIGHT: 4
};
 
var rounds = [5, 5, 3, 3, 2];
var colors = ['#1abc9c', '#2ecc71', '#3498db', '#8c52ff', '#9b59b6'];
 
// The ball object (The cube that bounces back and forth)
var Ball = {
    new: function (incrementedSpeed) {
        return {
            width: 18,
            height: 18,
            x: (this.canvas.width / 2) - 9, 
            y: (this.canvas.height / 2) - 9,
            moveX: DIRECTION.IDLE,
            moveY: DIRECTION.IDLE,
            speed: incrementedSpeed || 7 
        };
    }
};
 
// The ai object (The two lines that move up and down)
var Ai = {
    new: function (side) {
        return {
            width: 18,
            height: 180,
            x: side === 'left' ? 150 : this.canvas.width - 150,
            y: (this.canvas.height / 2) - 35,
            score: 0,
            move: DIRECTION.IDLE,
            speed: 8
        };
    }
};
 
var Game = {
    initialize: function () {
        this.canvas = document.querySelector('canvas');
        this.context = this.canvas.getContext('2d');
 
        this.canvas.width = 1400;
        this.canvas.height = 1000;
 
        this.canvas.style.width = (this.canvas.width / 2) + 'px';
        this.canvas.style.height = (this.canvas.height / 2) + 'px';
 
        this.player = Ai.new.call(this, 'left');
        this.ai = Ai.new.call(this, 'right');
        this.ball = Ball.new.call(this);
 
        this.ai.speed = 5;
        this.running = this.over = false;
        this.turn = this.ai;
        this.timer = this.round = 0;
        this.color = '#8c52ff';
 
        Pong.menu();
        Pong.listen();
    },
 
    endGameMenu: function (text) {
        // Change the canvas font size and color
        Pong.context.font = '45px Courier New';
        Pong.context.fillStyle = this.color;
 
        // Draw the rectangle behind the 'Press any key to begin' text.
        Pong.context.fillRect(
            Pong.canvas.width / 2 - 350,
            Pong.canvas.height / 2 - 48,
            700,
            100
        );
 
        // Change the canvas color;
        Pong.context.fillStyle = '#ffffff';
 
        // Draw the end game menu text ('Game Over' and 'Winner')
        Pong.context.fillText(text,
            Pong.canvas.width / 2,
            Pong.canvas.height / 2 + 15
        );
 
        setTimeout(function () {
            Pong = Object.assign({}, Game);
            Pong.initialize();
        }, 3000);
    },
 
    menu: function () {
        // Draw all the Pong objects in their current state
        Pong.draw();
 
        // Change the canvas font size and color
        this.context.font = '50px Courier New';
        this.context.fillStyle = this.color;
 
        // Draw the rectangle behind the 'Press any key to begin' text.
        this.context.fillRect(
            this.canvas.width / 2 - 350,
            this.canvas.height / 2 - 48,
            700,
            100
        );
 
        // Change the canvas color;
        this.context.fillStyle = '#ffffff';
 
        // Draw the 'press any key to begin' text
        this.context.fillText('Tecle para começar ',
            this.canvas.width / 2,
            this.canvas.height / 2 + 15
        );
    },
 
    // Update all objects (move the player, ai, ball, increment the score, etc.)
    update: function () {
        if (!this.over) {
            // If the ball collides with the bound limits - correct the x and y coords.
            if (this.ball.x <= 0) Pong._resetTurn.call(this, this.ai, this.player);
            if (this.ball.x >= this.canvas.width - this.ball.width) Pong._resetTurn.call(this, this.player, this.ai);
            if (this.ball.y <= 0) this.ball.moveY = DIRECTION.DOWN;
            if (this.ball.y >= this.canvas.height - this.ball.height) this.ball.moveY = DIRECTION.UP;

            // On new serve (start of each turn) move the ball to the correct side
            // and randomize the direction to add some challenge.
            if (Pong._turnDelayIsOver.call(this) && this.turn) {
                this.ball.moveX = this.turn === this.player ? DIRECTION.LEFT : DIRECTION.RIGHT;
                this.ball.moveY = [DIRECTION.UP, DIRECTION.DOWN][Math.round(Math.random())];
                this.ball.y = Math.floor(Math.random() * this.canvas.height - 200) + 200;
                this.turn = null;
            }
 
            // If the player collides with the bound limits, update the x and y coords.
            if (this.player.y <= 0) this.player.y = 0;
            else if (this.player.y >= (this.canvas.height - this.player.height)) this.player.y = (this.canvas.height - this.player.height);
            // Move ball in intended direction based on moveY and moveX values
            if (this.ball.moveY === DIRECTION.UP) this.ball.y -= (this.ball.speed / 1.5);
            else if (this.ball.moveY === DIRECTION.DOWN) this.ball.y += (this.ball.speed / 1.5);
            if (this.ball.moveX === DIRECTION.LEFT) this.ball.x -= this.ball.speed;
            else if (this.ball.moveX === DIRECTION.RIGHT) this.ball.x += this.ball.speed;
 
            // Handle ai (AI) UP and DOWN movement
            if (this.ai.y > this.ball.y - (this.ai.height / 2)) {
                if (this.ball.moveX === DIRECTION.RIGHT) this.ai.y -= this.ai.speed / 1.5;
                else this.ai.y -= this.ai.speed / 4;
            }
            if (this.ai.y < this.ball.y - (this.ai.height / 2)) {
                if (this.ball.moveX === DIRECTION.RIGHT) this.ai.y += this.ai.speed / 1.5;
                else this.ai.y += this.ai.speed / 4;
            }
 
            // Handle ai (AI) wall collision
            if (this.ai.y >= this.canvas.height - this.ai.height) this.ai.y = this.canvas.height - this.ai.height;
            else if (this.ai.y <= 0) this.ai.y = 0;
 
            // Handle Player-Ball collisions
            if (this.ball.x - this.ball.width <= this.player.x && this.ball.x >= this.player.x - this.player.width) {
                if (this.ball.y <= this.player.y + this.player.height && this.ball.y + this.ball.height >= this.player.y) {
                    this.ball.x = (this.player.x + this.ball.width);
                    this.ball.moveX = DIRECTION.RIGHT;
                }
            }
 
            // Handle ai-ball collision
            if (this.ball.x - this.ball.width <= this.ai.x && this.ball.x >= this.ai.x - this.ai.width) {
                if (this.ball.y <= this.ai.y + this.ai.height && this.ball.y + this.ball.height >= this.ai.y) {
                    this.ball.x = (this.ai.x - this.ball.width);
                    this.ball.moveX = DIRECTION.LEFT;
                }
            }
        }
 
        // Handle the end of round transition
        // Check to see if the player won the round.
        if (this.player.score === rounds[this.round]) {
            // Check to see if there are any more rounds/levels left and display the victory screen if
            // there are not.
            if (!rounds[this.round + 1]) {
                this.over = true;
                setTimeout(function () { Pong.endGameMenu('Winner!'); }, 1000);
            } else {
                // If there is another round, reset all the values and increment the round number.
                this.color = this._generateRoundColor();
                this.player.score = this.ai.score = 0;
                this.player.speed += 0.5;
                this.ai.speed += 1;
                this.ball.speed += 1;
                this.round += 1;
            }
        }
        // Check to see if the ai/AI has won the round.
        else if (this.ai.score === rounds[this.round]) {
            this.over = true;
            setTimeout(function () { Pong.endGameMenu('Game Over!'); }, 1000);
        }
    },
 
    // Draw the objects to the canvas element
    draw: function () {
        // Clear the Canvas
        this.context.clearRect(
            0,
            0,
            this.canvas.width,
            this.canvas.height
        );
 
        // Set the fill style to black
        this.context.fillStyle = this.color;
 
        // Draw the background
        this.context.fillRect(
            0,
            0,
            this.canvas.width,
            this.canvas.height
        );
 
        // Set the fill style to white (For the paddles and the ball)
        this.context.fillStyle = '#ffffff';
 
        // Draw the Player
        this.context.fillRect(
            this.player.x,
            this.player.y,
            this.player.width,
            this.player.height
        );
 
        // Draw the Ai
        this.context.fillRect(
            this.ai.x,
            this.ai.y,
            this.ai.width,
            this.ai.height 
        );
 
        // Draw the Ball
        if (Pong._turnDelayIsOver.call(this)) {
            this.context.fillRect(
                this.ball.x,
                this.ball.y,
                this.ball.width,
                this.ball.height
            );
        }
 
        // Draw the net (Line in the middle)
        this.context.beginPath();
        this.context.setLineDash([7, 15]);
        this.context.moveTo((this.canvas.width / 2), this.canvas.height - 140);
        this.context.lineTo((this.canvas.width / 2), 140);
        this.context.lineWidth = 10;
        this.context.strokeStyle = '#ffffff';
        this.context.stroke();
 
        // Set the default canvas font and align it to the center
        this.context.font = '100px Courier New';
        this.context.textAlign = 'center';
 
        // Draw the players score (left)
        this.context.fillText(
            this.player.score.toString(),
            (this.canvas.width / 2) - 300,
            200
        );
 
        // Draw the paddles score (right)
        this.context.fillText(
            this.ai.score.toString(),
            (this.canvas.width / 2) + 300,
            200
        );
 
        // Change the font size for the center score text
        this.context.font = '30px Courier New';
 
        // Draw the winning score (center)
        this.context.fillText(
            'Round ' + (Pong.round + 1),
            (this.canvas.width / 2),
            35
        );
 
        // Change the font size for the center score value
        this.context.font = '40px Courier';
 
        // Draw the current round number
        this.context.fillText(
            rounds[Pong.round] ? rounds[Pong.round] : rounds[Pong.round - 1],
            (this.canvas.width / 2),
            100
        );
    },
 
    loop: function () {
        Pong.update();
        Pong.draw();
 
        // If the game is not over, draw the next frame.
        if (!Pong.over) requestAnimationFrame(Pong.loop);
    },
 
    listen: function () {
        var canvas = document.querySelector('canvas');

        // Adicione este trecho de código no início do seu script
        canvas.addEventListener('touchstart', function (event) {
            handleTouch(event.touches[0]);
        });

        canvas.addEventListener('touchmove', function (event) {
            handleTouch(event.touches[0]);
        });

// ...

var firstTouch = true;  // Adicione esta variável global para controlar o primeiro toque

// ...

function handleTouch(touch) {
    // Verifique a posição do toque em relação à altura da tela
    var metadeDaTela = canvas.height / 2;
    var toqueY = touch.clientY;

    // Move o jogador com base na posição do toque
    if (toqueY < metadeDaTela) {
        Pong.player.move = DIRECTION.UP;
    } else {
        Pong.player.move = DIRECTION.DOWN;
    }
}

canvas.addEventListener('touchstart', function (evento) {
    if (firstTouch) {
        Pong.running = true;
        window.requestAnimationFrame(Pong.loop);
        firstTouch = false;
    }

    handleTouch(evento.touches[0]);
});

canvas.addEventListener('touchmove', function (evento) {
    handleTouch(evento.touches[0]);
});

canvas.addEventListener('touchend', function () {
    Pong.player.move = DIRECTION.IDLE;
});

// ...




    },
 
    // Reset the ball location, the player turns and set a delay before the next round begins.
    _resetTurn: function (victor, loser) {
        this.ball = Ball.new.call(this, this.ball.speed);
        this.turn = loser;
        this.timer = (new Date()).getTime();
 
        victor.score++;
    },
 
    // Wait for a delay to have passed after each turn.
    _turnDelayIsOver: function () {
        return ((new Date()).getTime() - this.timer >= 1000);
    },
 
    // Select a random color as the background of each level/round.
    _generateRoundColor: function () {
        var newColor = colors[Math.floor(Math.random() * colors.length)];
        if (newColor === this.color) return Pong._generateRoundColor();
        return newColor;
    }
};
 
var Pong = Object.assign({}, Game);
Pong.initialize();

I tried to move the player with the touch, and I expected that when I pressed the player’s position would follow the position of the touch that I set to be read

Increasing 3D Model fidelity with three.js from Blender

I am building a website using react and I imported a 3d model I made in Blender to my website using three.js. Everything is working fine, the basics of the model are ok, but it just seems like the rendering quality is not the same as in some examples I see online.
So I was wondering if there are ways to improve the model’s fidelity, textures resolution and the lightning (which makes the most diference).

This is a comparasion between a scene I found online (https://henryheffernan.com/), and my current model (my model is the 2nd image).

enter image description here
enter image description here

I exported my model form blender in the .gltf format, I then generated a .js file from the .gltf file using the npx gltfjsx command.

Smooth animate in a back-to-top button

I am using this code to make a back-to-top button:

$('body').prepend('<a href="#" class="back-to-top"></a>');

var amountScrolled = 300;

$(window).scroll(function() {
    if ( $(window).scrollTop() > amountScrolled ) {
        $('a.back-to-top').fadeIn('slow');
    } else {
        $('a.back-to-top').fadeOut('slow');
    }
});

$('a.back-to-top').click(function() {
    $('html, body').animate({scrollTop: 0}, 700);
    return false;
});

It works perfectly.

Now I want to apply the same script to another button already created in a tool panel (not from a .prepend)

I have managed to do it and it also works perfectly with a few changes. Everything except the animation smoothing: .animate({scrollTop: 0}, 700);

The 700 smoothing only works on the prepend button but not on a ready-made one.

What part am I omitting?

Using Realm, and JavaScript how do I access data in Atlas

I am attempting to incorporate Realm into a mobile app and am able to successfully use authentication:


App.jsx
...
export default AppWrapper = () => {
  return (
    <AppProvider id={"devicesync - xxxxx"}>
      <RealmProvider>
        <ContextProvider>
          <App />
        </ContextProvider>
      </RealmProvider>
    </AppProvider>
  );
};
...


Realm.jsx

import Realm from "realm";

Realm.flags.THROW_ON_GLOBAL_REALM = true;

const app = new Realm.App({ id: "devicesync-xxxxx" });

export default app;


This is my model:

import Realm from "realm";

export class ProjectSchema extends Realm.Object {
  static primaryKey = "_id";
  static schema = {
    name: "Project",
    primaryKey: "_id",
    properties: {
      _id: "uuid",
      area: "string",
      customer: "string",
      customercontact: "string",
      rigcompany: "string",
      projectname: "string",
      description: "string",
      projectedstartdate: "date",
      actualstartdate: "date",
      expectedduration: "int",
      actualduration: "int",
      status: "string",
      statusdate: "date",
      comment: "string",
      latdec: "double",
      longdec: "double",
    },
  };
}


Here is my partial code to access the data:

...
import { Realm, useQuery, useRealm } from "realm";
import Project from "../models/projectModel";

const ActiveProjects = () => {
  const [activeProjects, setActiveProjects] = useState([]);

  const projectList = useQuery(Project);
  console.log("projectList", projectList);
...

I get the following error when trying to access data in Atlas:
_realm.useQuery is not a function

How do I set an HTML element to not be displayed with JavaScript if one of its child elements contains a certain string or key word

Just kind of a curiosity project. ROBLOX has a ton of “Simulator” games and I’d like to make an extension that would look through the titles of games on the Discovery page and set the container for that game to “display: none”. The format is always “” and then child elements, so setting the HTML object with the name of the game in it to “display: none” would make the whole box for the game’s information disappear.

I don’t know much JavaScript, so I haven’t really tried anything yet. Basically everything is learning for me here.

Select a certain element from a .map array in react

I am new to react and have come across this problem. I have an Array list with at total of 4 items with content inside them. Each item has an id with its respective number 1-4. Is there any way that I can display specific item along with its contents using .map? For Example just display

“YOUR VISION. OUR REALITY.”
“Innovators in creating landing pages, With eye catching designs guaranteed to boost your business.”

const paraContent = [
  {
    heading: "YOUR VISION. OUR REALITY.",
    content:
      "Innovators in creating landing pages, With eye catching designs guaranteed to boost your business.",
    id: 1,
  },
  {
    heading: "YOUR VISION. OUR REALITY",
    content:
      "In 2023 Tlax generated as an idea in order to facilitate modern landing pages. December 2023 was when Tlax began to rise from the ground up. Slowly setting its prsence in the digital market..",
    id: 2,
  },
  {
    heading: "OUR MISSION",
    content:
      "Our mission at Tlax is to create simple and eye catching websites in order to meet personal needs and goals. From portfolio websites boosting your hiring probabilites to buisnisses websites advertising your services. Our goal in the end is to leave you with satisfaction and joy. Thats our moral code here at Tlax.",
    id: 3,
  },
  {
    heading: "ANGEL INFANTE",
    content:
      "Meet the face behind Tlax Web Design! Angel Infante is an aspiring programmer who is creative and enthusiastic about collaboration. Angel loves helping others in any way he can. He aspires to make everyone's day a bit better, and with his set of skills, creating websites in order to fulfill that joy was his calling.",
    id: 4,
  },
];



<div>
 <img src={shortArrow} alt="shortArrow"/>
   {paraContent.map((para, index)=>{
    return <Paragraph {...para} key={0} />
   })}
</div>

const Paragraph = (props) => {
  const {heading, content} = props;
  console.log(props);
  return(
    <div className="para">
      <h1 className="p-heading">{heading}</h1>
      <p className="p-content">{content}</p>
    </div>
  );
};

I tried implementing the key in my parameters but that resulted unsuccessful.

POSTGRES_URL connection string not working for localhost database

This connection string is giving me an error (pasted at the bottom) when I include it in the .env.local file of my Svelte app.

POSTGRES_URL="postgres://myusername:mypassword@localhost:5432/mydatabasename"

(I’ve substituted ‘mypassword’ etc, but the real one doesn’t have anything weird about it like weird characters)

I have tried all of the following and they all work …

  • pgAdmin connects ok to that postgres db on localhost 5432

  • pg_isready works ok

> pg_isready -d 'postgres://myusername:mypassword@localhost:5432/mydatabasename'
> localhost:5432 - accepting connections
  • psql works ok
psql -d 'postgres://myusername:mypassword@localhost:5432/mydatabasename' -c "Select 1"

 ?column? 
----------
        1
(1 row)
  • Vercel DB connection string in the same file .env.local – works ok
POSTGRES_URL="postgres://default:vmU398umcu89@ep-aaaaaa-a-aaaaa-aaaaa-pooler.us-east-1.postgres.vercel-storage.com/verceldb"

I have also tried breaking the connection string in different ways …

 myusername -> myusernamexx -> same error as below
 mypassword -> mypassworxx  -> same error as below
 removing password          -> same error as below
 localhost  -> localhostxx  -> "VercelPostgresError: VercelPostgresError - 'invalid_connection_string'"
 5432 -> 5000               -> same error as below
 removing port              -> same error as below
 mydatabase -> mydatabasxx  -> same error as below

I have watched the local database terminal window while I was breaking things. If I do a psql with a garbage username then the database log shows FATAL: database "garbageuser" does not exist. But, nothing I do in the .env.local file causes any output in the database output.

Thank you in advance for any help.

The error I get in my Svelte App …

node:events:492
      throw er; // Unhandled 'error' event
      ^

AggregateError
    at internalConnectMultiple (node:net:1114:18)
    at afterConnectMultiple (node:net:1667:5)
Emitted 'error' event on WebSocket instance at:
    at emitErrorAndClose (/Users/tee/Documents/Projects/myappsvelte/node_modules/ws/lib/websocket.js:1016:13)
    at ClientRequest.<anonymous> (/Users/tee/Documents/Projects/myappsvelte/node_modules/ws/lib/websocket.js:864:5)
    at ClientRequest.emit (node:events:514:28)
    at TLSSocket.socketErrorListener (node:_http_client:495:9)
    at TLSSocket.emit (node:events:514:28)
    at emitErrorNT (node:internal/streams/destroy:151:8)
    at emitErrorCloseNT (node:internal/streams/destroy:116:3)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
  code: 'ECONNREFUSED',
  [errors]: [
    Error: connect ECONNREFUSED ::1:443
        at createConnectionError (node:net:1634:14)
        at afterConnectMultiple (node:net:1664:40) {
      errno: -61,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '::1',
      port: 443
    },
    Error: connect ECONNREFUSED 127.0.0.1:443
        at createConnectionError (node:net:1634:14)
        at afterConnectMultiple (node:net:1664:40) {
      errno: -61,
      code: 'ECONNREFUSED',
      syscall: 'connect',
      address: '127.0.0.1',
      port: 443
    }
  ]
}

Node.js v20.10.0

How to use SVG icon as a prop in React

in Lucide icons, we can import for example Loader and Loader2 icons and pass them as a prop to our component. Let’s assume that I have two svg icons and I’d like to use them in a similar way as a prop to my custom React component and call it as below. How can I do that?


interface ButtonProps {
    icon: WhatToPutHere?
}

export const Button = ({icon}: ButtonProps) => {
    return <button><icon className="icon"/></button>
}

Woes dealing with syntax error while using Promises in Javascript

I am an “old school” system analyst / programmer and I’ve struggling for days with a problem related to Promises in Javascript. I am at my wits end …
Here’s the code I am having problems with:

          return fetch("bad://" + url)
                 .then((response) => {
                     var subst = response;
                     if (!response.ok) {
                        var emsg = "<span style='color:red'><b>ERROR</b></span>[" + response.status + "]: " + url;
                        subst = new Response(emsg, String);
                     }
                     return subst;
                  })
                 .then(response => response.text())
                 .then((html) => {
                     return extractHtml(html, url);
                  })
                 .then((html) => {
                     if (!el.parentNode) {
                        return;
                     }
                     el.insertAdjacentHTML("beforebegin", html.repeat(repeat));
                     el.parentNode.removeChild(el);
                     return(url);
                  })
                 .catch((error) => {
                     console.error('Failed to fetch(): ' + error.message);
                     return;
                  })

I keep getting a SYNTAX ERROR stating “unexpected token ‘)'”. I need help to figure out why there’s a syntax error im the code above. For that matter, the code is being used in a web page.
Funny enough, the followuing code does NOT yield a syntax error (??):

          return fetch("bad://" + url)
                 .then((response) => {
                     var subst = response;
                     if (!response.ok) {
                        var emsg = "<span style='color:red'><b>ERROR</b></span>[" + response.status + "]: " + url;
                        subst = new Response(emsg, String);
                     }
                     return subst;
                  })
                 .then(response => response.text())
                 .then((html) => {
                     return extractHtml(html, url);
                  })
                 .then((html) => {
                     if (!el.parentNode) {
                        return;
                     }
           
           el.insertAdjacentHTML("beforebegin", html.repeat(repeat));
           el.parentNode.removeChild(el);
           return(url);

Yes, ‘”bad://” + url’ is coded on purpose in order to test error handling.
Thanks in advance …

Single quote in js string retruning Unexpected identifier error

Following code is in asp file of VBscript language:

Response.Write("[" & LCase(booConfirmationEmail) & ", '" & strAgtEmailAddress & "']")

This code returning a ajax response to javascript as an array .
Whenever there is single quote(') in strAgtEmailAddress variable its returning Unexpected identifier error.
I know that I can use Replace(strAgtEmailAddress,"'", "&apos;") to avoid this.
But is there any other so similar character wont cause this issue?

Please provide solution if you applied before