How to highlight a word on mouseover in text in a React app

How to highlight a word on mouseover in text in a React app

const text = data[data.length - 1] !== undefined ? data[data.length - 1].taskText : null;

 const [hilightWord, setHilightWord] = useState(false);

  const hightlight = (text, hilightWord) => {
    if (!hilightWord) return text;

    const regex = new RegExp(`(${hilightWord})`, "gi");

    return text.split(regex).map((substring, i) => {
      return (
        <span className={styles.highlight} key={i}>
          {substring}
        </span>
      );
    });
  };


<p className={styles.text} onMouseMove={() => setHilightWord(true)} onMouseLeave={() => setHilightWord(false)}>{hightlight(text, hilightWord)}</p>

Sticky Section Not Working in Elementor Stacked Card Scroll

I’m trying to create a stacked card scroll effect in Elementor using custom CSS and JavaScript (based on a YouTube tutorial). However, the section above the cards (main container) isn’t sticking to the top during the scroll animation; it moves with the scroll.

The tutorial- [https://www.youtube.com/watch?v=7RhQq-DfIqI&list=PLJ2-MeNkZFN5E9KCLvbwSv2Uu7lElogPt&index=33&t=360s]

I’ve followed the tutorial steps carefully but still encounter this issue. I’ve searched online for solutions but haven’t found anything relevant.

As a beginner, inspecting every line of code is challenging. Could you please help identify potential issues in the CSS or JavaScript code that might be causing the sticky section to malfunction? Any suggestions on where to modify the code to achieve the desired effect (sticky section until animation starts) would be greatly appreciated.

Code Snippets:

CSS

selector{
    --card-scroll-height: 400;
    --card-rotate: 12;
}
selector .mdw-active-card{
    transform: translateY(-100vh) rotate(-60deg) !important;
    transition:1s;
    visibility: hidden;
    transform-origin: bottom left;
}
selector > .e-con,
selector > .e-container,
selector > .e-con-inner > .e-con,
selector > .e-con-inner > .e-container{
    position: sticky;
    top:0;
}

JavaScript

<script src="https://code.jquery.com/jquery-3.7.1.js"></script>

<script>

if(!MDWNonce100){
    
var MDWNonce100 = true

$(document).ready(function() {
    
var previousScrollTop = [],
cards = [],
cardScrollHeight = [],
cardRotate = [],
cardContainer = [],
stickyTop = [],
stickyCon = []


// Sliding crads on scroll

function cardSlideUp(){

$('.mdw-stacked-card-area').each(function(i){
    
    var $this = $(this),
    scrollTop = $(document).scrollTop(),
    cardAreaTop = $this.offset().top,
    index = Math.floor((scrollTop - cardAreaTop - stickyTop[i]) / cardScrollHeight[i]),
    totalCards = cards[i].length
    
    cards[i].removeClass('mdw-active-card')
    cards[i].each(function(j){
        if( j <= index ) {
            $(this).addClass('mdw-active-card')
        }
        if(index >= -1 && index < totalCards - 1){
            $(this).css({
                'transform': `rotate(${ -1*j*cardRotate[i] + (index+1)*cardRotate[i] }deg)`
            })
        }
    })
    
    previousScrollTop[i] = scrollTop
})

}


function setValues(){

$('.mdw-stacked-card-area').each(function(i){
    
    var $this = $(this)
    
    stickyTop[i] = 0
    
    if(stickyCon[i].outerHeight() > $(window).height()){
        stickyTop[i] = cardContainer[i].offset().top - stickyCon[i].offset().top - $(window).height()/2
    }
    stickyCon[i].css('top', -1*stickyTop[i])
    
    cardScrollHeight[i] = $this.css('--card-scroll-height') ? parseInt($this.css('--card-scroll-height').trim()) : 400
    cardRotate[i] = $this.css('--card-rotate') ? parseInt($this.css('--card-rotate').trim()) : 9
    
    
    // Rotating cards
    
    cards[i].each(function(j) {
        $(this).css({
            'transform': `rotate(-${j * cardRotate[i]}deg)`,
            'z-index': cards[i].length - j
        })
    })


    // Card area height
    
    $this.css('height', stickyCon[i].outerHeight() +  ((cards[i].length - 1) * cardScrollHeight[i]) + 'px' )
})

}

$(document).on('scroll', cardSlideUp)
$(window).on('resize', function(){
    setValues()
    cardSlideUp()
})


function init(){

$('.mdw-stacked-card-area').each(function(i){
    
    var $this = $(this)
    
    cards[i] = $this.find('.mdw-stacked-cards > .e-con, .mdw-stacked-cards > .e-container, .mdw-stacked-cards > .e-con-inner > .e-con, .mdw-stacked-cards > .e-con-inner > .e-container')
    stickyCon[i] = $this.children('.e-con, .e-container').eq(0)
    
    stickyCon[i].parents().each(function(){
        if( !$(this).is('html') ){ $(this).css('overflow', 'visible') }
    })
    
    previousScrollTop[i] = $(document).scrollTop()
    cardContainer[i] = $this.find('.mdw-stacked-cards')
})

setValues()
cardSlideUp()

}

init()
    
})
}
</script>

The Goal:
The goal is for a section to remain sticky at the top until the scrolling animation starts. However, the sticky section isn’t behaving as expected.

Functionality: During scrolling, the cards should rotate individually, creating a flowing animation. The parent container holding the cards container should remain fixed at the viewport until all cards have completed their rotation animations. This means cards will appear to ‘flow up’ when scrolling down and return to their original positions when scrolling back up.

the effect i’m trying to achive

Problem: The main section, intended to stay fixed at the top of the screen (sticky), isn’t working as expected. While the cards are animating correctly during scrolling, the main section and all its child elements are moving with the scroll instead of remaining fixed.
**
Additional Information:
Elementor version: 3.20.0
(i’m using Elemntors latest flex box container)

What could be causing the sticky section to malfunction in this scenario? Are there any adjustments in the CSS or JavaScript that might resolve the issue?

I’m aiming to achieve a smooth scrolling animation with a section remaining sticky until the card effects end.

ref.current.contains(event.target) always returns false

I have a component like this:

const ColumnTaskPrompt = () => {
 const promptRef = useRef<HTMLDivElement>(null);

 useClickOutside(promptRef, () => {
   console.log("do something";)
 });

 return (
   <div ref={promptRef} className={styles.prompt}>>
     <p>Some prompt 1</p>
     <p>Some prompt 2</p>
     <p>Some prompt 3</p>
   </div>
 );
};

And the standard hook useClickOutside (added console.log for clarity):

const useClickOutside = <T extends HTMLElement = HTMLElement>(
  ref: RefObject<T>,
  callback: () => void
) => {
  useEffect(() => {
    const handleClickOutside = (event: Event) => {
      if (ref.current && !ref.current.contains(event.target as Node)) {
        console.log(
          ref.current,
          event.target,
          ref.current.contains(event.target as Node)
        );

        callback();
      }
    };
    document.addEventListener("mousedown", handleClickOutside);
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [ref]);
};

Every time I click on the layout inside this ColumnTaskPrompt component – ref.current.contains(event.target), it returns false.

It also returns false when I click on any part of the layout outside of this component (which is correct).

first rectangle - ref.current, second - event.target, "contains" method returns false

I tried using createRef instead of useRef, however that did not work.

Trying to make a screen that fades in and out with a button click

Clicking a button should call mobileMenuToggle(), toggling an animation for mobileMenu to either fade in or fade out depending on the current status of the menu screen. When mobileMenu display is none, it should fade in, however when mobileMenu is a block, clicking the button should result in mobile menu fading out. When mobileMenu is active (block), mainBody should disappear. When mainBody is active (block), mobileMenu should disappear. Before any clicks, mobileMenu is set to “display: none”

It works the first two times the button is clicked, but on the third time it breaks. It starts playing only the fadeIn animation but both mobileMenu AND mainBody disappear. I suspect it has something to do with the event listener, but I am not really sure. Any help figuring this out would be greatly appreciated.

JS:

function mobileMenuToggle(){
    if (document.getElementById("mobileMenu").style.display == "none"){
        document.getElementById("mobileMenu").style.animationName = "fadeIn"
        document.getElementById("mobileMenu").style.display = "block"
        document.getElementById("mainBody").style.display = "none"
    }
    else if(document.getElementById("mobileMenu").style.display == "block"){
        document.getElementById("mainBody").style.display = "block"
        document.getElementById("mobileMenu").style.animationName = "fadeOut"
        document.getElementById("mobileMenu").style.display = "block" //trigger animation

        mobileMenu.addEventListener("animationend", () => {
            document.getElementById("mobileMenu").style.display = "none"
          });
    }
}

Remix No route matches URL

I have brand new Remix SPA project with simple nested route

  1. Home
  2. Protocol
  3. Protocol/[protocolId]

And I setup the project as shown in the repo https://stackblitz.com/~/github.com/pavankjadda/remix-vite-spa

All routes work except nested route protocol/[protocolId]. I did follow instructions from official docs: https://remix.run/docs/en/main/file-conventions/routes#folders-for-organization. You can see same Stackblitz preview.

Why is this Scraping Function returning an empty array?

const unirest = require("unirest");
const cheerio = require("cheerio");

const getOrganicData = () => {
  return unirest
    .get("https://www.google.com/search?q=apple+linkedin&gl=us&hl=en")
    .headers({
      "User-Agent":
        "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36",
    })
    .then((response) => {
      let $ = cheerio.load(response.body);

      let titles = [];
      let links = [];
      let snippets = [];
      let displayedLinks = [];

      $(".yuRUbf > a > h3").each((i, el) => {
        titles[i] = $(el).text();
      });
      $(".yuRUbf > a").each((i, el) => {
        links[i] = $(el).attr("href");
      });
      $(".g .VwiC3b ").each((i, el) => {
        snippets[i] = $(el).text();
      });
      $(".g .yuRUbf .NJjxre .tjvcx").each((i, el) => {
        displayedLinks[i] = $(el).text();
      });

      const organicResults = [];

      for (let i = 0; i < titles.length; i++) {
        organicResults[i] = {
          title: titles[i],
          links: links[i],
          snippet: snippets[i],
          displayedLink: displayedLinks[i],
        };
      }
      console.log(organicResults)
    });
};

getOrganicData();

I’m trying to write a function that will successfully scrape the first few links of a google search (for example, I can pass through the query “Javascript” and I want to get the first few results when that term is searched).

I found this blog https://serpdog.io/blog/scrape-google-search-results/ and followed it.
I ran the code on the website and it returned a blank array []. (I am using node js)
I attached the code, but it’s exactly the same as on the blog.

Any ideas on how to fix this? Or do you have a better way to get the first few search results from a search term?

Thanks!

I tried several different methods of getting the top search results, none of which worked.

My app is unable to write a docx file after being converted into a .exe file

I’ve written a simple program in Node.js / electron that reads an excel spreadsheet and then writes the data onto a docx template and creates a new docx file with when done. When I run my program with npm start it works perfectly but once I converted it into an exe file it is unable to do this function and i dont know why? The program will open and take me to the landing page i designed but these functions do not run. please help. thanks!

I’ve tried changing the permissions on the exe file to allow it access to read and write but that didnt work.

Mobile view toggles class but do not change element

I’ve searched a lot about this issue, however is slightly different from the others. Most of posts here relates to “toggle not working”, but mine toggle works, the problem is that it doesn’t change the view, it doesn’t open/close element.

Check the snippet below, you’ll see that does work on desktop but does not in mobile view.

Is there any special JS rule to make it works in mobile browsers or something related to touch screens? How to make it work?

  function toggleForm(event) {
    console.log("clicked");

    var form = document.getElementById('search-form');
    form.classList.toggle('hidden-form');

    console.log(form.classList);
  }
.hidden-form {
    display: none !important;
    height: auto !important;
}
<div onclick="toggleForm()" id="toggleButton">
  <h3>TITLE</h3>
</div>

<form action="#" id="search-form" class="hidden-form">
  TEXT
</form>

javascript onclick event, add +1 and -1 in quantity product

I tried to make a code with Jquery when I click the + button, the field quantity increases, and when I press the – button the quantity decreases, and it works

but when I press another color and size, the field jumps no longer +1
do +2

first round work

second round jump

However, this method still doesn’t work for me. Can anyone help? Thank you.

$('#partQuantity').on('click', "#plus" + data[k].Id, function(event) {
    event.preventDefault();
    var quantityInput = document.getElementById('qua' + data[k].SkuSizeId); // Assuming 'SkuSizeId' is the correct property
                                            
    if (quantityInput) {
        var currentValue = parseInt(quantityInput.value) || 1;

        if (currentValue < data[k].OnHand) {
            quantityInput.value = currentValue + 1;
        }
    } 
});
                                   
                                    

                                    
  $('#partQuantity').on('click', "#minus" + data[k].Id, function(event) {
event.preventDefault();

var quantityInput = document.getElementById('qua' + data[k].SkuSizeId); // Assuming 'SkuSizeId' is the correct property


var currentValue = parseInt(quantityInput.value);
if (currentValue > 1) {
    quantityInput.value = currentValue - 1;
 }

});

Android Webview touch event not trigged in iframe

This is an android project and I need to load a website in a webview.
And one more request here is the website needs to be loaded in a iframe.

This is done by the following step:

  1. create a webview
  2. I have a sample html file
  3. I load my sample html file
  4. I call wewbview.loadHTMLString(sampleHtmlString, "") to load the site from string;

Sample html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
    </style>
</head>
<body>
    <script>
        document.addEventListener('touchstart', function(event) {
            console.log("document touchstart");
        });
    </script>
</body>
</html>

And webview show all good on device also i can see touch event triggered.


Then I will add the iframe part:

  1. User input a url to load for example: “https://www.facebook.com”
  2. Still I load my sample html file
  3. Then I replace the PLACE HOLDER in sample file to the one user input for example: "https://www.facebook.com"
  4. Then call wewbview.loadHTMLString(sampleHtmlString, "");

Updated sample html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <style>
        .webview-container {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }
        iframe {
            width: 100%;
            height: 100%;
            border: none;
        }
    </style>
</head>
<body>
    <div class="webview-container" id="webview-container">
    </div>
    <script>
        function loadWebView(url) {
            var iframe = document.createElement('iframe');
            iframe.src = url;
            document.getElementById('webview-container').innerHTML = '';
            document.getElementById('webview-container').appendChild(iframe);
            iframe.onload = function() {
                console.log("iframe onload");
            };
        }

        document.addEventListener('touchstart', function(event) {
            console.log("document touchstart");
        });
        loadWebView('https://www.example.com');
    </script>
</body>
</html>

I can see the site loaded in iframe correctly but this time touchstart not trigggered when touched.

I searched few posts then tried:

function loadWebView(url) {
    var iframe = document.createElement('iframe');
    iframe.src = url;
    document.getElementById('webview-container').innerHTML = '';
    document.getElementById('webview-container').appendChild(iframe);
    iframe.onload = function() {
        console.log("iframe onload");
        iframe.contentWindow.document.addEventListener('touchstart', function(event) {
            console.log("iframe touchstart");
        });
    };
}

But still not working and I am getting the error in console:



Uncaught SecurityError: Failed to read a named property 'document' from 'Window': 
Blocked a frame with origin "null" from accessing a frame with origin 
"https://www.grandbrowser.com".  

The frame requesting access has a protocol of "about", 
the frame being accessed has a protocol of "https". 
Protocols must match.", source: about:blank (41)

I also tried to remove the "https:" from the url according to this post:

The frame requesting access has a protocol of “https”, the frame being accessed has a protocol of “http”. Protocols must match

But then the error in console is gone but the site will not load anymore.


Any advice on this issue will be appreciated, thanks in advance.

How can I achieve this with html and css?

I am creating a portfolio website for myself but i am a beginner in web dev. I wanted to create a section in my page at the bottom where the “start a project” box in the picture will be my about section and rest will be used as my footer for links and copyrights.enter image description here

It looks like this currently. i just need a background that is underneath the about section and starts from middle to the bottom and no margins for the background.

<section id="about">
    <div class="abt-content">
        <h2 class="abt-title">About Me 
            <i class="fa-regular fa-lightbulb"></i>
        </h2>
        <p class="abt-desc"></p>
    
</div>
</section>
#about {
    margin-left: 70px;
    margin-right: 5%;
    margin-bottom: 20%;
    padding: 80px 0px;
}

.abt-content {
    background-color: #232946;
    padding: 50px 0px;
    box-shadow: 0px 5px 10px rgba(0, 0, 0, 0.25);
    border-radius: 12px;

}

.abt-title {
    color: #fffffe;
    text-align: center;
    margin-bottom: 10px;
    font-family: montserrat, Verdana, Geneva, Tahoma, sans-serif;
    font-size: 35px;
    font-weight: 700;
}[enter image description here](https://i.stack.imgur.com/dUTIz.png)

Drilldown packed bubble chart to scatter plot not rendering in Highcharts

I have a packed bubble chart, and I want to drill down the bubbles to a scatter plot. Also as a bonus would love to be able to drill down the main bubble to a scatter plot which is a mix of all of the scatter plots, I am not sure if that is possible.

I am building this code using React. Right now. On drill down, the scatter plot is not rendering.

My code: component.js

import React, { useEffect, useState } from "react";
import { Spinner } from "react-bootstrap";
import "bootstrap/dist/css/bootstrap.min.css";
import ScatterChart from "./scatter";
import "./App.css";

const ScatterComponent = ({ data, filteredData }) => {
  const [loading, setLoading] = useState(true);
  const chartData = filteredData.length !== 0 ? filteredData : data;

  const bubbleSeries = [{"name":"ABC","data":[{"name":"page_views","value":6652301,
  "drilldown":"ABC - page_views"},{"name":"article_views","value":4812992,"drilldown":"ABC - article_views"},
  {"name":"visits","value":5116176,"drilldown":"ABC - visits"},]},
  {"name":"XYZ","data":[{"name":"page_views","value":16448241,"drilldown":"XYZ - page_views"},
  {"name":"article_views","value":10791478,"drilldown":"XYZ - article_views"},
  {"name":"visits","value":11921915,"drilldown":"XYZ - visits"},]}];

  const scatterSeries = [{"type":"scatter","id":"ABC - page_views",
  "data":[["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1]],},
  {"type":"scatter","id":"ABC - article_views",
  "data":[["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1]],},
  {"type":"scatter","id":"ABC - visits",
  "data":[["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1]],},
  {"type":"scatter","id":"XYZ - page_views",
  "data":[["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1]],},
  {"type":"scatter","id":"XYZ - article_views",
  "data":[["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1]],},
  {"type":"scatter","id":"XYZ - visits",
  "data":[["2024-02-27T00:00:00.000Z",1],["2024-02-26T00:00:00.000Z",1],["2024-02-27T00:00:00.000Z",1],["2024-02-28T00:00:00.000Z",1]],},
]
  


  useEffect(() => {
    const delay = setTimeout(() => {
      setLoading(false);
    }, 2000);

    return () => clearTimeout(delay);
  }, []);

  return (
    <div className="bubbleScatterTrends clearfix w-100 column">
      <h3 className="mt-1 ms-1" style={{ color: "#81b0d2" }}>
        <u>ABC-XYZ Breakdowns</u>
      </h3>
      {loading ? (
        <div className="text-center">
          <Spinner animation="border" variant="primary" />
          <Spinner animation="border" variant="secondary" />
          <Spinner animation="border" variant="success" />
          <Spinner animation="border" variant="danger" />
          <Spinner animation="border" variant="warning" />
          <Spinner animation="border" variant="info" />
          <Spinner animation="border" variant="light" />
          <Spinner animation="border" variant="dark" />
        </div>
      ) : (
        <div className="clearfix w-100 column">
          <div className="clearfix w-100 column">
            <div className="w-100 bubbleScatterCharts">
              <ScatterChart
                bubbleData={bubbleSeries}
                scatterData={scatterSeries}
              />
            </div>
          </div>
        </div>
      )}
    </div>
  );
};

export default ScatterComponent;

scatter.js

import React, { useMemo } from "react";
import Highcharts from "highcharts";
import HighchartsReact from "highcharts-react-official";
import highchartsAccessibility from "highcharts/modules/accessibility";
import highchartsExporting from "highcharts/modules/exporting";
import highchartsExportData from "highcharts/modules/export-data";
import highchartsPackedbubble from "highcharts/highcharts-more";
import dayjs from "dayjs";
import "dayjs/locale/es";

highchartsAccessibility(Highcharts);
highchartsExporting(Highcharts);
highchartsExportData(Highcharts);
highchartsPackedbubble(Highcharts);

const ScatterChart = ({ bubbleData, scatterData }) => {
  dayjs.locale("en");
  const addCommas = (x) =>
    x.toString().replace(/B(?<!.d*)(?=(d{3})+(?!d))/g, ",");

  const options = useMemo(
    () => ({
      chart: {
        type: "packedbubble",
        backgroundColor: "#283347",
      },
      exporting: {
        enabled: true,
      },
      navigation: {
        buttonOptions: {
          verticalAlign: "top",
          y: -10,
          x: -5,
        },
      },
      accessibility: {
        enabled: false,
      },
      credits: {
        enabled: false,
      },
      legend: {
        enabled: true,
        itemStyle: {
          color: "#fff",
        },
      },
      tooltip: {
        backgroundColor: "#283347",
        style: { color: "#fff" },
        formatter: function () {
          if (this.y !== undefined || this.key !== undefined) {
            let tooltip = `<span><b><u>${this.key}</u></b>: ${addCommas(
              this.y
            )}</span>`;
            return tooltip;
          }
        },
        useHTML: true,
      },
      plotOptions: {
        packedbubble: {
          minSize: "20%",
          maxSize: "100%",
          zMin: 0,
          zMax: 1000,
          layoutAlgorithm: {
            gravitationalConstant: 0.05,
            splitSeries: true,
            seriesInteraction: false,
            dragBetweenSeries: true,
            parentNodeLimit: true,
          },
          dataLabels: {
            enabled: true,
            format: "{point.name}",
            filter: {
              property: "y",
              operator: ">",
              value: 250,
            },
            style: {
              color: "black",
              textOutline: "none",
              fontWeight: "normal",
            },
          },
        },
      },
      series: bubbleData,
      drilldown: {
        series: scatterData,
      },
    }),
    [bubbleData, scatterData]
  );

  return <HighchartsReact highcharts={Highcharts} options={options} />;
};

export default ScatterChart;

My scatter plot is not rendering.

scatterplot