Jquery counter with decimal on scrolling animated

Why when I make a scrolling for the page the value of the counter changes and does not remain fixed? “animated jquery”

  
>! jquery links 

   <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/waypoints/4.0.1/jquery.waypoints.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Counter-Up/1.0.0/jquery.counterup.min.js"></script>

The counter

    <h2 class="counter">11.40</h2>
    <h2 class="counter">3.40</h2>
    <h2 class="counter">5.40</h2>
    <h2 class="counter">43.40</h2>
    <h2 class="counter">41.40</h2>
>! I want the value to not change when I scroll the page
<script>
    $(document).ready(function(){
        $(".counter").counterUp({
            delay: 100,
            time: 1200
        })
    })
</script>

JavaScript – Dynamic module imports – Query

I am working on modularizing the scripts. Consider the following project hierarchy.

Project hierarchy snapshot

My files look like this

  1. index.html
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>Learn EcmaScript</title>
    <script src="script.js" type="module" defer></script>
  </head>
  <body></body>
</html>
  1. script.js
import math from './scripts/math.js';
console.log("3 + 4 = ", math.add(3, 4));
  1. scripts/math.js
import { add } from './add.js';
import { subtract } from './subtract.js';
import { multiply } from './multiply.js';
import { divide } from './divide.js';

export default {
  add,
  subtract,
  multiply,
  divide,
};
  1. scripts/add.js
export const add = (x, y) => Number(Number(x) + Number(y));
  1. scripts/subtract.js
export const subtract= (x, y) => Number(Number(x) - Number(y));
  1. scripts/multiply.js
export const multiply= (x, y) => Number(Number(x) * Number(y));
  1. scripts/divide.js
export const divide = (x, y) => Number(Number(x) / Number(y));

When I run the code using live server – the output is fine.
My concern here is related to the application performance.

Chrome DEV Tools snapshot

I am using only math.add() and I need only add.js to be loaded. Rest of the scripts (i.e., subtract.js, multiply.js, divide.js) are unnecessary here. But in the chrome dev tools I can see all of the scripts loading.

I tried to use Dynamic import syntax and modified the math.js file as below

math.js

export default {
  add: () => import('./add.js').then((m) => m.add),
  subtract: () => import('./subtract.js').then((m) => m.subtract),
  multiply: () => import('./multiply.js').then((m) => m.multiply),
  divide: () => import('./divide.js').then((m) => m.divide),
};

then the output is like below

Dynamic import output snapshot

Though the scripts are loaded on demand, I am unable to get the output properly. How could I do the code refactor here to get proper output with on demand script load?
(Let’s consider only the default export scenario)

Continue rotation on image without skipping back to top position

I have been trying for ages to make this javascript-code continue the rotation of the pane-element from where it currently is when clicking and dragging on the rotation button. Now it skips back to top-position first, then I am able to rotate it. I just can’t seem to make it.
Any help on this is really appriciated!

Codepen:
https://codepen.io/MrSounds/pen/zYLzdYJ

 //ROTATION 
  let rotationHistory = [];
  var $rotateBtn = $('#pane_center');
  const $rotationInput = $('#rotation');
  const $pane = $('#pane');
  const input = document.getElementById('rotation');

document.addEventListener('mouseup', function() {
  let rotation = pane.style.transform ? parseInt(pane.style.transform.match(/-?d+/g)[0]) : 0;
  rotation = (rotation % 360 + 360) % 360;
  input.value = rotation;
});

// Update the input field with the current rotation of the pane
$rotationInput.val(parseInt($pane.css('transform').split(/[()]/)[1]) || 0);

// Update the rotation of the pane when the input value changes
document.getElementById('rotation').addEventListener('input', function() {
  const rotationInput = document.getElementById('rotation');
  const rotation = parseInt(rotationInput.value, 10);
  document.getElementById('pane').style.transform = 'rotate(' + rotation + 'deg)';
});
  
    function get_degrees(mouse_x, mouse_y) {
  const pane = $('#pane');
  const radius  = pane.outerWidth() / 2;
  const center_x    = pane.offset().left + radius;
    const center_y  = pane.offset().top + radius;

  const radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
    const degrees   = Math.round((radians * (180 / Math.PI) * -1) + 100);

    return degrees;
    }
  
$rotateBtn.on('mousedown touchstart', function (event) {
  $(document).off("mousemove touchmove", onMove);
  
  const click_degrees = get_degrees(event.pageX, event.pageY);

  $(document).bind('mousemove touchmove', click_degrees, function(event) {
    const pane = $('#pane');
    let degrees = get_degrees(event.pageX, event.pageY) - click_degrees;
    pane.css('transform', 'rotate('+degrees+'deg)');
    
  // Store the current rotation in the history array
  rotationHistory.push(degrees);
  });
});

  animate();

  function onUp(e) {       
  $(document).off("mousemove");
  $(document).off("touchend");
  $(document).on("mousemove", onMove);
  calc(e);
  clicked = null;
  }
  
  $('#undoBtn').on('click', function(event) {
  rotationHistory.pop();
  const previousRotation = rotationHistory[rotationHistory.length - 1] || 0;
  $('#pane').css('transform', 'rotate(' + previousRotation + 'deg)');
});
  
  $('#redoBtn').on('click', function(event) {
  const nextRotation = rotationHistory[rotationHistory.length] || 0;
  if (nextRotation) {
    $('#pane').css('transform', 'rotate(' + nextRotation + 'deg)');
    rotationHistory.push(nextRotation);
  }
});
  

`

How to establish communication between service-worker and main in Manifest V3

I am trying to build continuous communication between service-worker.js and main.js in order to post what data is received from an API to Google Documents, but I can’t figure out how to do it using Manifest V3. The first problem I’ve encountered is registering the service-worker like this:

if ('serviceWorker' in navigator) {
    window.addEventListener('load', () => {
        navigator.serviceWorker
            .register('/sw.js')
            .then((registration) => {
                console.log('Service worker registered:', registration);
            })
            .catch((error) => {
                console.error('Error registering service worker:', error);
            });
    });
}

but it always catches the error. From what I’ve understood, Manifest V3 registers the SW-s internally so I don’t need to worry about registration.

I’ve tried using Workbox but I can’t simply import it with importScripts and working with workbox-cli is too complex and in the end, I think is unnecessary.

Expected an empty string to return false in Javascript

I am trying to solve the CodeWars code challenge The Hashtag Generator
:

The marketing team is spending way too much time typing in hashtags.
Let’s help them with our own Hashtag Generator!

Here’s the deal:

  • It must start with a hashtag (#).
  • All words must have their first letter capitalized.
  • If the final result is longer than 140 chars it must return false.
  • If the input or the result is an empty string it must return false.

Examples

" Hello there thanks for trying my Kata"  =>  "#HelloThereThanksForTryingMyKata"
"    Hello     World   "                  =>  "#HelloWorld"
""                                        =>  false

This is my code:

function generateHashtag (str) {
   if (str == "") {return false;}
   else
     {
      let text = str.trim();
      const myArray = text.split(" ");
      let mot ="";
      let finalStr = ""
      for(let i=0; i< myArray.length; i++)
        {
          mot = myArray[i];
          mot = mot.charAt(0).toUpperCase() + mot.slice(1);
          finalStr =finalStr + mot;
        }
      if(finalStr.length >140){return false;}
      else {return "#"+finalStr;}
    }
}

This is the error I got:

Expected an empty string to return false: expected ‘#’ to equal false

I don’t understand why I get this error, as I have included the empty string check.

How to get the field name dynamically from the json object in javascript?

So this is the data I retrieved from api, and I would like to get more detail data from each of the filed in the object, like Name, Number, Select and so on.
But now the problem is the field name can be changed from the server side, so the ‘Name’ may become Title someday, and the Number can be changed to some other value in the future, so how should I do to specify them dynamically in the code instead of hard coded.
Any help would be appreciated!

enter image description here

Get user information in localstorage

I want the information to be stored individually in localStorage.
If the entered information is already available, do not receive the information again and give an alert. Is it possible to guide me, what should I do?

function handleSubmit(e) {
  e.preventDefault()
  let users = JSON.parse(localStorage.getItem("users") || "[]")
  users.push(values)
        
  localStorage.setItem('users', JSON.stringify(users))
        
  const loggeduser = JSON.parse(localStorage.getItem("users") || "[]");
  if (
    values.email === loggeduser.email &&
    values.password === loggeduser.password
  ) {
    alert("Emaill & Password is available!!!")
  } else {
    navigate("/");
  }
};

Several users are stored in one presentation and not separately.
The alert also works incorrectly.

How to insert links into a js file in django so that the function changes the style files?

I’m trying to make a button that changes the site to a dark/light theme. In vs code, my code works completely, but nothing happens in pycharm on django.

script.js file:

let switchMode = document.getElementById("switchMode");

switchMode.onclick = function () {
    let theme = document.getElementById("theme");

    if (theme.getAttribute("href") == "dark-mode.css") {
        theme.href = "light-mode.css";
    } else {
        theme.href = "dark-mode.css";
    }
}

button:

    <li class="nav-item" id="switchMode">
        <img class="header__moon" src="{% static "img/Moon.svg" %}" alt="" >
    </li>

How to call and pass information to a Python script in a Laravel 9 project?

I have an HTML form in my Laravel 9 project saved to the browser’s localStorage using JS (with jQuery). I also have a Python script that needs to take a CSV-formatted database, modify it based on the information from localStorage, and convert it to JSON. Lastly, I have a JavaScript file that takes the JSON and builds an HTML table. All of these parts work separately, but I’m having trouble integrating python into my Laravel 9 project.

What is the best way to call and pass information to a Python script within a Laravel 9 project?

Any help or guidance on this would be greatly appreciated. Thank you in advance!

Pass object and specify attribute to function for processing in javascript

So I want to define a function in javascript that takes an object emp:

    var emp = {
        firstName: "john",
        lastName: "smith"
    };
    capitalize(emp, "firstName");
    //emp.firstName is John

    capitalize(emp, "firstName");
    //emp.lastName is Smith

I specify which attribute to process

    funciton capitalize(employee, attribute)
    {
        // code to capitalize the sepecified attribute only
        return object;
    }

My current way of solving this is to specify a function for each attribute. But if it’s possible to specify an attribute for the function it would be shorter code and more dynamic.

I have searched for this concept, but I probably failed at specifying a good keywords for this problem.

Change the font/background color of dropdown created using Select2 in Angular?

I am working on a project. I want to change the background/font color of dropdown list I have created using select2. I want to change the color based on the ID or senlevel (sentivity level).

Below is the code where options have been created,

<select2 [data]="categoriesDropDownList" [value]="selectedCategoryId" [cssImport]="true" [options]="options"
(valueChanged)="onCategoryChange($event)">
</select2>

How to pass data to PrimeVue MenuItems

I have PrimeVue Menu as follows:

    <template>
       <div class="">
          <label class="text-slate-500 text-sm">Doctor Name</label>
          <div class="text-sm">{{ appointment.doctor.name }}</div>
       </div>
       <div>
          <span>
          <a href="#"><i class="pi pi-ellipsis-v" @click="toggle"></i></a>
          </span>
          <Menu ref="menu" :model="items" :popup="true" />
       </div>
    </template>

data() {
      return {

         items: [{
               label: 'Reschedule',
               command: (event) => {
                  this.rescheduleVisible = true
               },
            },
            {
               label: 'Mark Completed'
            },
            {
               label: 'Cancel Schedule'
            },
            {
               label: 'Generate Bill'
            },
            {
               label: 'Set Reminder'
            },
            {
               label: 'Send Message'
            },
         ]

      }
      methods: {

         toggle(event) {
            console.log(event)
            this.$refs.menu[0].toggle(event);
         }
      }

I am using this menu in an appointment listing. Now when I click on the Reschedule menu item, I need to get the corresponding appointment ID so that I can pass it to the modal popup, that will be visible by setting rescheduleVisible as true. How this can be done ?

React MUI Alert not displaying with SnackBar

I created a custom Alert as shown below, but when I add Snackbar, it is not displaying. Here is the part that I changed, the rest is the same:

AlertPopup:

const AlertPopup = () => {
  const { text, type } = useAlert();

  if (text && type) {
    return (

      // when I use this, the message is displayed
      // <Alert variant="filled" severity={type} sx={{}}>
      //   {text}
      // </Alert>

      // when I use this, the message is NOT displayed
      <Stack spacing={2} sx={{ width: '100%' }}>
      <Snackbar autoHideDuration={6000}>
      {/* <Alert severity={type} sx={{ width: '100%' }}> */}
      <Alert variant="filled" severity={type} >
        {text}
      </Alert>
      </Snackbar>
      </Stack>

    );
  } else {
    return <></>;
  }
};

Here is the other parts of the implementation. I did not changed anything as there is not specific component for Alert:

AlertContext:

const ALERT_TIME = 6000;
const initialState = {
  text: "",
  type: "",
};

const AlertContext = createContext({
  ...initialState,
  setAlert: () => {},
});

export const AlertProvider = ({ children }) => {
  const [text, setText] = useState("");
  const [type, setType] = useState("");

  const setAlert = (text, type) => {
    setText(text);
    setType(type);

    setTimeout(() => {
      setText("");
      setType("");
    }, ALERT_TIME);
  };

  return (
    <AlertContext.Provider
      value={{
        text,
        type,
        setAlert,
      }}
    >
      {children}
    </AlertContext.Provider>
  );
};

useAlert:

const useAlert = () => useContext(AlertContext);

export default useAlert;

So, what is missing with this implementation?