How to modify size of the custom cursor when click ? (On React)

I’ve made a custom cursor on my react app, but I would like to animate it when the user click. Like to decrease the size or something like that. The cursor is in a components that I’ve call on my Index.js file. Can someone help me please ?

Here’s the Custom Cursor component :

`import React, { useRef } from ‘react’

function CustomCursor() {

const cursorRef = useRef(null)

React.useEffect(() => {
    document.addEventListener('mousemove', (event)=>  {
        const {clientX, clientY} = event;
        const mouseX = clientX - cursorRef.current.clientWidth /2;
        const mouseY = clientY - cursorRef.current.clientHeight /2;
        cursorRef.current.style.transform = `translate3d(${mouseX}px, ${mouseY}px, 0)`
    })
}, [])

return (

)
}

export default CustomCursor`

the css class in detail

I’ve try to make this css class but it’s not working :

ul li:hover ~ .custom-cursor { width: 10px; height: 10px; }

How to move the mouse with webshot function inside a dygraph widget

I’m stuck because I can not achive what I want with a dygraph widget created in R.

I have this time series.

#library(xts)
dts <- xts::xts(c(10508,8465,3175,3816,4532,2735,2534,9541,8253,9962),
order.by = seq(from = as.Date("2022-02-01"), to = as.Date("2022-11-01"), by = "month"))

I can plot it in a dygraph widget

#library(dygraph)
object <- dygraph((dts),
                      ylab = "") %>% 
        dyRangeSelector(height = 20, strokeColor = "") %>%
        dyOptions(fillGraph = FALSE, stackedGraph = FALSE, drawGrid = FALSE, strokeWidth = 3) %>%
        dyHighlight(highlightSeriesOpts = list(strokeWidth = 3,highlightCircleSize = 10))

and save it in a html page.

#library(htmlwidgets)
saveWidget(object, "temp.html", selfcontained = FALSE)

Now, I would like to take a screenshot of the plot. I know I can do it with

webshot::webshot(url = "images/temp.html", file = "screenshot.png")

No problem with that. But I should hover the mouse near the last data point before the screenshot, because I would like the chart to show the information of the last point in the legend.

I have tried with

webshot::webshot(url = "images/temp.html", file = "screenshot.png"),
eval = "this.mouse.click(1781, 109);")

I got the X,Y coordinates injecting the following code in the inspection frame of the page.

<html onclick="display(event)">
function display(event) {
         let X = event.clientX;
         let X = event.clientX;
         alert = (X + Y);
      }

But it does not seem to work.
I get
enter image description here

but I would like something like this
enter image description here

Actually, I would like to hover the last point regardless the time series.

I know it could be done with ggplot and save me a lot of steps but the dygraph is mandatory and I would like to get the static plot from it.
I know also that it is maybe more of a javascript or casperjs question. If so I wouldn’t mind repeat the question in the appropriate forum.

In advance, thank you very much for your help.

How to add aria-label to carousel buttons

I’m using a carousel slider with jQuery and it automatically adds owl-prev and owl-next classes as shown below.

How can I add role="prev" and role="next" to the buttons just as with the classes so as to improve accessibility?

<div class="owl-nav">
 <button role="presentation" class="owl-prev"><i class="icofont-simple-left"></i></button>
 <button role="presentation" class="owl-next"><i class="icofont-simple-right"></i></button>
</div>

Lit Web Component – Trying to select element

I am trying to transform this element into a standard web component using Lit. (https://www.w3schools.com/howto/howto_js_image_comparison.asp)

I totally new to Lit and to web components and am struggling to select elements from the shadow DOM. Right now, I am stuck with the var x inside the initComparisons() function. I am aware that the document object does not exist in the shadow dom and must be replaced by renderRoot, however, I am not sure either If I am selecting the elements the right way or what does replace the window object… Do you notice something wrong with this code? I am stuck at the first lines of the initComparisons() function as x always returns null no matter what I do….

Any help will be appreciated.

Thank you very much.

import {
  LitElement,
  css,
  html,
} from "https://cdn.jsdelivr.net/gh/lit/dist@2/all/lit-all.min.js";

export class Comparator extends LitElement {
  static properties = {
    baseImage: "",
    imageWidth: "",
    imageHeight: "",
    altImage: "",
  };

  // Define scoped styles right with your component, in plain CSS
  static styles = css`
    * {
      box-sizing: border-box;
    }

    .img-comp-container {
      position: relative;
      height: 200px; /*should be the same height as the images*/
    }

    .img-comp-img {
      position: absolute;
      width: auto;
      height: auto;
      overflow: hidden;
    }

    .img-comp-img img {
      display: block;
      vertical-align: middle;
    }

    .img-comp-slider {
      position: absolute;
      z-index: 11;
      cursor: ew-resize;
      /*set the appearance of the slider:*/
      width: 40px;
      height: 40px;
      background-color: #2196f3;
      opacity: 0.7;
      border-radius: 50%;
    }

    .border-slider {
      position: absolute;
      z-index: 10;
      cursor: ew-resize;
      /*set the appearance of the slider:*/
      width: 5px;
      height: 130%;
      background-color: red;
      opacity: 1;
    }

    .border-slider::after {
      content: url("./separator.svg");
      position: absolute;
      width: 30px;
      height: 30px;
      background: red;
      top: calc(50% - 15px);
      left: calc(50% - 15px);
    }
  `;

  constructor() {
    super();
    // Declare reactive defaults
    this.baseImage = "https://api.lorem.space/image/house?w=800&h=600";
    this.altImage = "https://api.lorem.space/image/house?w=800&h=600";
    this.imageWidth = "800px";
    this.imageHeight = "600px";
  }

  connectedCallback() {
    super.connectedCallback();
    this.initComparisons();
  }

  // Render the UI as a function of component state
  render() {
    return html`
      <div class="img-comp-container">
        <div class="img-comp-img">
          <img
            src="${this.baseImage}"
            width="${this.imageWidth}"
            height="${this.imageHeight}"
          />
        </div>
        <div id="img-comp-overlay" class="img-comp-img">
          <img
            src="${this.altImage}"
            width="${this.imageWidth}"
            height="${this.imageHeight}"
          />
        </div>
      </div>
    `;
  }

  //HELPER FUCTIONS GO HERE
  initComparisons() {
    var x, i;
    /*find all elements with an "overlay" class:*/
    x = this.renderRoot.querySelector("#img-comp-overlay");
    for (i = 0; i < x.length; i++) {
      /*once for each "overlay" element:
      pass the "overlay" element as a parameter when executing the compareImages function:*/
      compareImages(x[i]);
    }

    function compareImages(img) {
      var slider,
        img,
        clicked = 0,
        w,
        h;
      /*get the width and height of the img element*/
      w = img.offsetWidth;
      h = img.offsetHeight;
      /*set the width of the img element to 50%:*/
      img.style.width = w / 2 + "px";
      /*create slider:*/
      slider = this.renderRoot.createElement("DIV");
      slider.setAttribute("class", "border-slider");
      /*insert slider*/
      img.parentElement.insertBefore(slider, img);
      /*position the slider in the middle:*/
      slider.style.top = h / 2 - slider.offsetHeight / 2 + "px";
      slider.style.left = w / 2 - slider.offsetWidth / 2 + "px";
      /*execute a function when the mouse button is pressed:*/
      slider.addEventListener("mousedown", slideReady);
      /*and another function when the mouse button is released:*/
      this.renderRoot.addEventListener("mouseup", slideFinish);
      /*or touched (for touch screens:*/
      slider.addEventListener("touchstart", slideReady);
      /*and released (for touch screens:*/
      window.addEventListener("touchend", slideFinish);
      function slideReady(e) {
        /*prevent any other actions that may occur when moving over the image:*/
        e.preventDefault();
        /*the slider is now clicked and ready to move:*/
        clicked = 1;
        /*execute a function when the slider is moved:*/
        window.addEventListener("mousemove", slideMove);
        window.addEventListener("touchmove", slideMove);
      }
      function slideFinish() {
        /*the slider is no longer clicked:*/
        clicked = 0;
      }
      function slideMove(e) {
        var pos;
        /*if the slider is no longer clicked, exit this function:*/
        if (clicked == 0) return false;
        /*get the cursor's x position:*/
        pos = getCursorPos(e);
        /*prevent the slider from being positioned outside the image:*/
        if (pos < 0) pos = 0;
        if (pos > w) pos = w;
        /*execute a function that will resize the overlay image according to the cursor:*/
        slide(pos);
      }
      function getCursorPos(e) {
        var a,
          x = 0;
        e = e.changedTouches ? e.changedTouches[0] : e;
        /*get the x positions of the image:*/
        a = img.getBoundingClientRect();
        /*calculate the cursor's x coordinate, relative to the image:*/
        x = e.pageX - a.left;
        /*consider any page scrolling:*/
        x = x - window.pageXOffset;
        return x;
      }
      function slide(x) {
        /*resize the image:*/
        img.style.width = x + "px";
        /*position the slider:*/
        slider.style.left = img.offsetWidth - slider.offsetWidth / 2 + "px";
      }
    }
  }
}

customElements.define("image-compare", Comparator);

React native operation btw 2 floats

I want to do the subtraction between 2 floats. Everything works only when I enter a “,” in my input to make a subtraction between 2 floats, I get NaN (Not a Number). Only I don’t really understand how this is possible ^^
I tried several things like parseFloat in case they are strings or Number.

If someone could explain me?

There is my code:

 const [alertPrice, setAlertPrice] = useState(0.0);
    
    return (

 <TextInput
        style={styles.input}
        placeholderTextColor="#fff"
        keyboardType="numeric"
        maxLength={5}
        onChangeText={(text) => {
                                      props.handleChange("targetPrice", text);
                                      setAlertPrice(text);
                                    }}
       value={alertPrice}
  />
        <Text
             style={{
                  left: width * 0.35,
                  bottom: height * 0.02,
                  color: "grey",
             }}
        >
            Economiser{" "}
              {item.actual_price && alertPrice
              ? (console.log(
              "calcul: ", Number(
               item.actual_price - alertPrice).toFixed(2)
               ),
              parseFloat(item.actual_price) -
              parseFloat(alertPrice)).toFixed(2)
              : "N/A"}{" "}
               €
        </Text>
        );

Thanks you in advance guys !

How to Disable/prevent/hide the Vue component (div-tag)?

I am trying to disable the VUE component based on the user access settings. Now, I am able to hide the component from the UI, but after every re-render, the component is getting active. I don’t just want to hide the component; I want to prevent the user from clicking the component. I couldn’t find the exact solution to my problem. Thank you in advance.

This is the route and beforeEach route condition:

 {
    path: "/settings/overview",
    name: "SettingsOverview",
    component: PageSettingsOverview,
    meta: {
      requiresAuth: true,
      showComponent: true,
      componentAccessPermissions: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
    },
  },

**beforeEach**

 const currentLogUser = store.getters["auth/currentUser"];
    if (
      currentLogUser !== null &&
      to?.meta?.componentAccessPermissions !== undefined
    ) {
      for (let i = 0; i < currentLogUser.teams.length; i++) {
        const team = currentLogUser.teams[i];
        const valPermissions = team.permissions
          .filter((item) => {
            return to.meta.componentAccessPermissions.includes(
              item.permissionType
            );
          })
          .map((item) => {
            return item.permissionType;
          });
        const allowAccess = to.meta.componentAccessPermissions.every((i) =>
          valPermissions.includes(i)
        );
        if (!allowAccess) {
          to.meta.showComponent = false;
        } else {
          to.meta.showComponent = true;
        }
      }
    }

VueFile:

<div class="col-12 col-md-4" v-if='$route.meta.showComponent' @click.prevent>
        <router-link class="card" to="/administration" >
          <div class="card-img-top">
            <i class="hi hi-people" />
          </div>
          <div class="card-body">
            <h5 class="card-title">Teams & Users</h5>
          </div>
        </router-link>
      </div>

Check if Polygon will be accepted by MongoDB collection with spatial index

I have a lot of operations that involve bulk inserting self generated polygons into a mongodb collection that contains a 2dsphere index. Sometimes these polygons have self intersections or crossing edges result in the bulk insert failing. As far as I know, these need to be fixed before I try again to insert them into the collection (if we can ignore these errors that might be a suitable solution too).

Is there a way to identify these errors before I attempt to bulk insert? So for example, I generate the polygon geometry, pass the newly created polygon through a function that would return the same error as if I had uploaded it to the database.

Content inserting as a string

I’m trying to append this “Free Delivery” message on my site but its getting injected as a string rather than an html

var isOnPDP = window.location.href.match("https://l1556639c1dev-store.occa.ocs.oraclecloud.com/occ-live/park-up/105243");
var freeDeliveryMessage = "<div class='awaFreeDelContainer'><span class='check'>&check;</span> Your order qualifies for FREE delivery</div>";
if(isOnPDP){
    if($(".MiniCart__SubTotalAmount").textContent.substr(1)>= 250){
    //  if($(".awaFreeDelContainer").length == 0){
        $(".MiniCartItems").append(freeDeliveryMessage);
    }
}
else{
    $(".awaFreeDelContainer").remove();
}

I was expecting the delievry message to be created as a normal HTML

How to get a substring from an input field and pass the result into another input field

I’m trying to extract a certain string value from a QR code which is inputted in a QRcode input field and I want the extracted value of string to pass it to another input field, but I’m not getting the result that I want. Instead, the result only shows in DIV elements.

  <script>      
     $(document).ready(function(){
     $("#QRcode").blur(function(){
       var str = $("#QRcode").val().substring(0,10);
    $("#pkg").html(str);
      });   
   });
 </script>
<div class="mb-3">  
  <label><b>Package:</b></label>
      <div type="text"  id="pkg" name="Package" class="form-control"></div>**==> script only works in here.
      <input type="text"  id="pkg" name="Package" class="form-control"> **==> I want the result to show in this field.

Understanding an if else statement

I have this piece of coding, however, I do not quite understand how the if-else statements have been used in terms of the description of the assignment: “Given a string s, find the first non-repeating character in it and return its index. If it does not exist, return -1

Especially need help understanding:

if (charCounts[char]) {
charCounts[char]++;
} else }
charCounts[char] = 1

function uniqueChar(s) {
    const charCounts = [];

    for (let i = 0; i < s.length; i++) {
        const char = s[i]; 
        if (charCounts[char]) { 
            charCounts[char]++; 
        } else {
            charCounts[char] = 1; 
        }
    }
    for (let j = 0; j < s.length; j++) {
        const char = s[j];
        if (charCounts[char] === 1) {
            return j;
        } 
    }
    return -1;
}
console.log(uniqueChar("loveleetcode"));

JS create HTML element from AJAX json [duplicate]

I’m receiving through an AJAX GET request bytes series corresponding to an img. My ultimate goal is to convert these bytes into an image and to display it on the webpage (without refreshing).
All the AJAX part is working perfectly, I’m receiving the data and had verified it through console log printing. But, when I’m trying to generate an html element with the raw data (in bytes, not the img yet), I does not work.

<script>
    $(document).ready(function(){
    
    setInterval(function(){
        $.ajax({
            type: 'GET',
            url : "/checkview",
            success: function(response){
                //console.log(response)
                let textC = response
            },
            error: function(response){
                alert('An error occured')
            }
        });
    },10000);
    })
    document.body.onload = addElement;
        function addElement() {
        // create a new div element
        const newDiv = document.createElement("div");

        // and give it some content
        const newContent = document.createTextNode(textC);

        // add the text node to the newly created div
        newDiv.appendChild(newContent);

        // add the newly created element and its content into the DOM
        const currentDiv = document.getElementById("div1");
        document.body.insertBefore(newDiv, currentDiv);
}
    </script>

Hints: the data are supposed to be in the textC variable.

So, I tried first to:

alert(textC);

which worked perfectly. I got data in bytes displayed. But, it works only when written in the setInterval function. I tried this same command in the console, this error appeared:

VM288:1 Uncaught ReferenceError: textC is not defined
    at <anonymous>:1:7

Therefore, I suppose there is a mistake in my code. Please help !

How to create a function that check if two objects have the same properties? [javascript]

How can I create a function that return true if all the properties in two objects are the same? I have come up with the following code which will return true if at least one of the properties are the same. However if one of the properties are different, it should return false. Bear in mind that I’m in the learning process of JavaScript…Thank you!

function BuildAddress(street, city, zipCode) {
  this.street = street;
  this.city = city;
  this.zipCode = zipCode;
}

const address1 = new BuildAddress('a', 'b', 101);
const address2 = new BuildAddress('a', 'b', 101);

function areEqual(address1, address2) {
  for (let key in address1)
    for (let value in address2)
  if (address1[key] === address2[value]) return true;
  return false;
}

How to trigger textarea typing with jQuer Tampermonkey user script

I’m creating a freelancer.com auto-bidding bot. I’m doing this because I’m tired of bidding and I was looking for a solution to help me place my bid programmatically for the specific project skills. I have worked on the entire program on Tampermonkey and everything works fine as expected except the proposal is not submitting when I programmatically trigger click on the bid submit button.

Every time I trigger click submit button proposal, it says that the proposal is empty while is not. But if I type anything from the textarea even if it’s a space or anything then the proposal submits. Freelancer have a way of detecting if indeed a human typed on the textarea.

I’m looking for a way to trigger typing on the textarea such that I will trick textarea to think that a human typed the proposal, remember I have predefined proposals that I set the value on the textarea programmatically.

enter image description here

I have tried the following but they didn’t work

 $("textarea#descriptionTextArea").trigger( 'oninput' );
            $("textarea#descriptionTextArea").trigger( 'change' );
            
            $("textarea#descriptionTextArea").focus().trigger( $.Event("keydown", {
                which: 32
            }) ); 

This is the entire code for that specific problem

function tech_errands_auto_bid(){



        var project_title = tech_errands_get_project_title();
        var project_skills = tech_errands_get_project_skills();
        console.log( 'n' + project_title + 'n' )

        if( localStorage.getItem( project_title + ' - scroll' ) === null ){
            tech_errands_scroll_to_an_element( '.ProjectViewDetailsSkills' );
            localStorage.setItem( project_title + ' - scroll', project_title );
        } 

      

            var proposal; 

            if( project_title.indexOf( 'fix' ) >= 0 || project_title.indexOf( 'fixed' ) >= 0 ){
                proposal = tech_errands_get_proposal( fix_proposals );
            } else {
                proposal = tech_errands_get_proposal( proposals );
            }

           
           var proposal_data =  $( 'textarea#descriptionTextArea' ).val(); 

           if( tech_errands_form_input( proposal_data ) == '' ){
            $( 'textarea#descriptionTextArea' ).val( proposal + '                                                                                                                                                                                ' );

            $("textarea#descriptionTextArea").trigger( 'oninput' );
            $("textarea#descriptionTextArea").trigger( 'change' );
            
            $("textarea#descriptionTextArea").focus().trigger( $.Event("keydown", {
                which: 32
            }) ); 


            if( ! tech_errands_is_hourly() ){
                var amount = $( '#bidAmountInput' ).val(); 
                $( '.InputContainer.BeforeLabelPresent[_ngcontent-webapp-c206] .NativeElement[_ngcontent-webapp-c206]' ).val( amount );
                $( '#periodInput' ).val( 1 );
            }

        }

        $("textarea#descriptionTextArea").removeClass( 'IsInvalid ng-invalid' ).addClass( 'ng-valid' );


        $( '[_ngcontent-webapp-c288] [data-display=inline][data-color][_nghost-webapp-c102]' ).trigger( 'click' );

Styled output in Terminal Console with JS and Node.js [duplicate]

I am creating a JS RPG CLI game and I have a question about styled output.
Once executed, the script outputs a framed Welcome. I need that frame to be colored and the text within normal.

I need this: https://i.stack.imgur.com/XuYYK.png

I did it with the simple console.log():

    console.log(`
    +-----------------------------+
    |          Welcome !          |
    +-----------------------------+
    `)

And my output is: https://i.stack.imgur.com/EE5UF.png