Complex SVG progress bar animation

I have an svg shield compound from two path. I need to create progress bar like this: enter image description here

Shield should fills clockwise with green starting from the center at the top.
Unfortunatly I don’t have any expirience working with svgs. All that I found – was dash+offset trick that kinda could work with two correct strokes (I think two, because outer and inner part are not the same) and they should move simultaneously and also from corret position from the top.

Maybe someone works with highcharts and they are flexible enough for that task?
Or should I ask a designer for correct path/parts of path? Any suggestions would help

Thank you

<svg xmlns="http://www.w3.org/2000/svg" id="b" viewBox="0 0 208 256"><g id="c"><g id="d"><path d="M104.008,230.733c34.201-19.594,53.976-31.944,65.831-43.87,10.089-10.149,14.161-19.658,14.161-37.101V53.467c-.462-.213-.987-.446-1.59-.704-14.122-5.86-59.818-22.552-75.371-28.132-2.049-.587-2.812-.63-3.102-.63-.137,0-.854.027-2.9.609-1.425.523-3.092,1.133-4.956,1.816-18.825,6.897-57.753,21.16-70.689,26.42-.522.217-.983.416-1.392.598v96.319c0,9.414,1.253,16.008,3.303,21.237,2.011,5.129,5.262,10.15,10.888,15.797,11.888,11.934,31.67,24.279,65.818,43.937ZM95.55,253.553C24.65,212.861,0,195.992,0,149.762V52.668c0-13.264,5.718-17.642,16.264-22.02,13.307-5.418,52.881-19.916,71.606-26.775,2.194-.804,4.101-1.503,5.647-2.07,3.431-1.03,6.862-1.803,10.42-1.803,3.684,0,7.115.773,10.546,1.803,14.739,5.279,62.387,22.663,77.253,28.845,10.546,4.507,16.264,8.756,16.264,22.02v97.094c0,46.23-24.523,63.228-95.55,103.791-3.304,1.674-6.48,2.447-8.513,2.447s-5.083-.773-8.387-2.447Z" style="fill:#0a0b0c; fill-rule:evenodd; stroke-width:0px;"/></g></g></svg>

In React, In Single components inputs re-render all time on change one input value

The issue I’m facing is related to how React handles state updates and re-renders. When you change the value of one field in your form (name, email, or phone), all three input components re-render because they all depend on the same formData state. React re-renders the entire component when the state changes, which is why all inputs re-render, even if only one field’s value has changed.

In below, if you change value of name all 3 input components will be re-render.

const [formData, setFormData] = useState({ name: '', email: '', phone: '';

<FormInput
                    label="Name"
                    placeholder="Enter name"
                    id="name"
                    value={formData.name}
                    onChange={handleChange}
                />

                <FormInput
                    label="Email"
                    placeholder="Enter email"
                    type='email'
                    id="email"
                    value={formData.email}
                    onChange={handleChange}
                />

                <FormInput
                    label="Phone"
                    placeholder="Enter phone"
                    type='number'
                    id="phone"
                    value={formData.phone}
                    onChange={handleChange}
                />

FormInput.jsx

import { forwardRef} from "react";
import { cx } from "../../utils/helper";

export const commonInputCss = "w-full border border-neutral-300 rounded-xl p-4 outline-none text-text-700 placeholder:text-text-disabled bg-white disabled:bg-text-disabled disabled:cursor-not-allowed disabled:opacity-50 disabled:placeholder:text-main-black";

const FormInput = forwardRef(({
    label, type = "text", id, inputCss, ...props
}, ref) => {

    return (
        <div className={cx("relative flex flex-col gap-y-1")}>
            {label && (
                <label htmlFor={id} className={cx(
                    "text-text-700 text-sm text-medium",
                    labelCss
                )}>
                    {label}
                </label>
            )}

            <input
                type={type}
                name={id}
                id={id}
                ref={ref}
                {...props}
                className={cx(
                    commonInputCss,
                    inputCss,
                )}
            />
        </div>
    );
});

export default FormInput;

But, do we need to re-render all to change one property value?

JS returs a false negative when evaluating two strings on the first run only [duplicate]

I am tring to write a program to work with speech recognition but my program returns a false negative on its first run when evaluating two strings that are identical and should return true but they returned a false on the first try.

the function is fired after the speech recognition returns a Result.

var textResult = "text string";
var modeCommands = ['text', 'text one', 'text two'];
var command = null;

function loop(textResult, modeCommands, command) {
  console.log('loop function:', textResult, "modeCommands", modeCommands, "command", command);
  var commandPieces;
  const ObjectKeys = Object.keys(modeCommands);
  var resultPieces = textResult.split(' ');
  for (var i = 0; i < ObjectKeys.length; i++) {
    const arr = modeCommands[ObjectKeys[i]];
    for (var j = 0; j < arr.length; j++) {
      commandPieces = arr[j].split(' ');
      if (!command) {
        // the false negative happens on this evaluation 
        console.log('Comparing: resultPieces[0]', resultPieces[0].toString().toLowerCase().trim(), 'and commandPieces[0]', commandPieces[0].toString().toLowerCase().trim());
        if (resultPieces[0].toString().toLowerCase().trim() == commandPieces[0].toString().toLowerCase().trim()) {
          command = 'Success YaY';
        }
      }
    }
  }
  return command
}
var Result = loop(textResult, modeCommands, command);

// loop is supposed to return a string 'Success YaY' but when the user talks into the mic and speech recognition returns a result, and this function runs as a result of that, the evaluation of the two strings above returns a false negative for the first result returned aftecognition fires. after that everything works fine.
console.log('Result', Result)

Open Web Analytics JS Issue

I just installed Open Web Analytics on my web server. I followed the installation steps as per the official GitHub page, and it was successfully installed on the server.

In the web pages where I want to add the tracker, I’m using the default JS code from the GitHub page to load the tracker (after replacing owa_baseUrl with my domain and the site_id):

<script type="text/javascript">
//<![CDATA[
var owa_baseUrl = 'http://your.domain.com/path/to/owa/';
var owa_cmds = owa_cmds || [];
owa_cmds.push(['setSiteId', 'your_site_id']);
owa_cmds.push(['trackPageView']);
owa_cmds.push(['trackClicks']);
owa_cmds.push(['trackDomStream']);

(function() {
    var _owa = document.createElement('script'); _owa.type = 'text/javascript'; _owa.async = true;
    _owa.src = owa_baseUrl + 'modules/base/js/owa.tracker-combined-min.js';
    var _owa_s = document.getElementsByTagName('script')[0]; _owa_s.parentNode.insertBefore(_owa, _owa_s);
}());
//]]>
</script>

From what I understand, I should now be able to initialize tracker objects with:

OWATracker = new OWA.tracker();

However, OWA is not defined.

Assistance 2 google maps API errors

apologies I’m new to coding.

I have a webflow project that has some custom code which integrates google maps API with some basic javascript but I’m getting 2 warnings in the console that I really need help fixing.

I would truly appreciate the help from anyone on how I can solve this or even how I can generally improve on this code.

The Warnings:

1.

js?v=3.53.2,exp&key=…vvMFq3_8ccilrI0:266 Google Maps JavaScript API has been loaded directly without loading=async. This can result in suboptimal performance. For best-practice loading patterns please see https://goo.gle/js-api-loading
Ufa@js?v=3.53.2,exp&key=…vvMFq3_8ccilrI0:266

2.

js?v=3.53.2,exp&key=…vvMFq3_8ccilrI0:201 As of February 21st, 2024, google.maps.Marker is deprecated. Please use google.maps.marker.AdvancedMarkerElement instead. At this time, google.maps.Marker is not scheduled to be discontinued, but google.maps.marker.AdvancedMarkerElement is recommended over google.maps.Marker. While google.maps.Marker will continue to receive bug fixes for any major regressions, existing bugs in google.maps.Marker will not be addressed. At least 12 months notice will be given before support is discontinued. Please see https://developers.google.com/maps/deprecations for additional details and https://developers.google.com/maps/documentation/javascript/advanced-markers/migration for the migration guide.

The code:

<!-- Map container -->
<div id="map" style="height: 400px; width: 100%;"></div>

<!-- CMS Collection List (hidden) -->
<div id="locationsList" style="display:none;">
  <!-- Webflow will populate this with Collection List Items -->
</div>

<script>
function initMap() {
    const customIcon = {
        url: 'https://cdn.prod.website-files.com/65722a8eff588d8e12dca16b/658d71462c0ec7b8fc92aad6_Untitled-9-01.svg',
        scaledSize: new google.maps.Size(30, 30),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(15, 15)
    };

    let map;
    let currentInfoWindow = null;

    // Check if the map container exists
    const mapDiv = document.getElementById('map');
    if (!mapDiv) {
        console.error('Map container not found');
        return;
    }

    // Snazzy Maps style array
    const snazzyMapStyle = [
        // ... Your existing style array ...
    ];

    map = new google.maps.Map(mapDiv, {
        zoom: 14,
        center: {lat: 35.231706, lng: 23.682403}, // Paleochora center
        styles: snazzyMapStyle,
        zoomControl: true,
        mapTypeControl: false,
        scaleControl: true,
        streetViewControl: false,
        rotateControl: false,
        fullscreenControl: true
    });

    const locationItems = document.querySelectorAll('[data-location-item]');
    const locations = Array.from(locationItems).map(item => ({
        name: item.querySelector('[data-location-name]').textContent,
        lat: parseFloat(item.querySelector('[data-location-lat]').textContent),
        lng: parseFloat(item.querySelector('[data-location-lng]').textContent),
        description: item.querySelector('[data-location-description]').textContent,
        imageUrl: item.querySelector('[data-location-image]').getAttribute('src') || item.querySelector('[data-location-image]').textContent,
        link: item.querySelector('[data-location-link]').getAttribute('href')
    }));

    // Store the HTML template as a constant
    const infoWindowTemplate = document.getElementById('infowindow-template').innerHTML;

    locations.forEach(location => {
        console.log('Location Image URL:', location.imageUrl); // Debug log
        
        const marker = new google.maps.Marker({
            position: {lat: location.lat, lng: location.lng},
            map: map,
            title: location.name,
            icon: customIcon
        });

        marker.addListener('click', () => {
            if (currentInfoWindow) {
                currentInfoWindow.close();
            }

            const infoWindowContent = infoWindowTemplate
                .replace('id="location-name">', `id="location-name">${location.name}`)
                .replace('id="location-description">', `id="location-description">${location.description}`)
                .replace(/src="[^"]*"/, `src="${location.imageUrl}"`)
                .replace('id="location-link" href="#"', `id="location-link" href="${location.link}"`);

            console.log('Info Window Content:', infoWindowContent); // Debug log

            const infoWindow = new google.maps.InfoWindow({
                content: infoWindowContent
            });

            infoWindow.open(map, marker);
            currentInfoWindow = infoWindow;
        });
    });

    map.addListener('click', () => {
        if (currentInfoWindow) {
            currentInfoWindow.close();
            currentInfoWindow = null;
        }
    });
}

// Load Google Maps API script dynamically
function loadGoogleMapsAPI() {
    const script = document.createElement('script');
    script.src = 'https://maps.googleapis.com/maps/api/js?v=3.53.2,exp&key=AIzaSyB52I0sX29SAyRXqb07vvMFq3_8ccilrI0';
    script.async = true;
    script.defer = true;
    script.onload = initMap;  // Call initMap after the script has loaded
    document.head.appendChild(script);
}

// Ensure the DOM is loaded before loading the Google Maps API
document.addEventListener('DOMContentLoaded', loadGoogleMapsAPI);
</script>

What the code should do:

Google Maps Integration in Webflow

This code integrates Google Maps into a Webflow project, creating an interactive map with custom markers and info windows. Here’s a breakdown of its functionality:

  1. HTML Structure:

    • A div with id “map” is used as the container for the Google Map.
    • A hidden div with id “locationsList” is presumably used to store location data from a Webflow Collection List.
  2. Map Initialization (initMap function):

    • Creates a new Google Map instance.
    • Sets the initial center to Paleochora (latitude 35.231706, longitude 23.682403).
    • Applies custom styles (Snazzy Maps style, which is commented out in the provided code).
    • Configures map controls (zoom, scale, fullscreen enabled; street view, rotate, map type disabled).
  3. Location Data Processing:

    • Retrieves location data from Webflow Collection List items.
    • Each location includes: name, latitude, longitude, description, image URL, and link.
  4. Marker Creation and Info Windows:

    • Creates a marker for each location on the map.
    • Sets up click listeners for each marker.
    • Uses a template (not provided in the code snippet) to create custom info windows.
    • Opens an info window when a marker is clicked, closing any previously opened info window.
  5. Map Click Handling:

    • Closes the currently open info window when clicking elsewhere on the map.
  6. Google Maps API Loading (loadGoogleMapsAPI function):

    • Dynamically loads the Google Maps JavaScript API.
    • Uses a Promise to handle successful loading or errors.
  7. Initialization on DOM Content Loaded:

    • Waits for the DOM to be fully loaded before initializing the map.
    • Catches and logs any errors during the API loading process.
  8. Security Note:

    • I know the API key is exposed even though it’s restricted but can’t find a better solution using webflow. If a clever solution exists I’m all ears.

This implementation allows for a custom-styled map with location markers pulled from a Webflow Collection, providing an interactive and visually appealing map experience for users.

View page here

This is the code:

I’ve tried to fix error 2 by replacing google.maps.Marker with google.maps.marker.AdvancedMarkerElement

But this then results in the following error:

map:67 Uncaught TypeError: Cannot read properties of undefined (reading 'AdvancedMarkerElement')at map:67:47at Array.forEach (<anonymous>)at HTMLScriptElement.initMap (map:64:15)(anonymous)   @   map:67initMap   @   map:64load      loadGoogleMapsAPI   @   map:112

Vitest not picking up my mocked environment variables when testing axios call

I’ve got the following function:

import axios from 'axios'

const apiKey = import.meta.env.VITE_KEY
const apiURL = import.meta.env.VITE_URL

const headers = {
  'key': apiKey,
  'host': apiURL.replace('https://', '')
}

export const getData = async () => {
  return axios.get(apiURL + '/items', { headers: headers })
    .then(response => response)
}

I’m trying to write a test for it like this:

import { getData } from '@/services/api.js'
import axios from 'axios'

vi.mock('axios')

vi.stubEnv('VITE_KEY', 'mockApiKey')
vi.stubEnv('VITE_URL', 'https://mockApiUrl')

const mockHeaders = {
  'x-rapidapi-key': import.meta.env.VITE_KEY,
  'x-rapidapi-host': import.meta.env.VITE_URL.replace('https://', '')
}

test('getData is working', async () => {
  const mockData = [
    { name: 'mockData' }
  ]

  axios.get.mockResolvedValueOnce({ data: { data: mockData } })

  const data = await getData()

  expect(data).toEqual(mockData)
  expect(axios.get).toHaveBeenCalledWith(import.meta.env.VITE_URL + '/items', { headers: mockHeaders })
})

But the test is failing because axios.get is using the real environment variables as headers instead of the those mocked in the tests with stubEnv. Why are the test environment variables not being picked up?

Go through an object to sum the number of children

I feel like this is an easy solve, but I’ve been stuck for a while, so thought I’d reach out for help.

I have an array of objects as per below.

songs = [
{ track_name: "name of track" , track_genres: ["chamber pop","indie pop"] },
{ track_name: "name of track 2" , track_genres: ["dutch r&b","indie soul", "indie pop"] },
{ track_name: "name of track 3" , track_genres: ["indie pop","chamber pop","indie soul"] }
]

I will then make a “mapping” object so each child gets a parent genre assigned to them. I shall be doing this manually (if you have ideas on doing it automatically through code, that’d be great too, but not the core issue for the question)

genres = [
{
name: "Pop",
children: [{name:"Chamber Pop"},{name:"Indie Pop"}]
},
{
name: "R&B",
children: [{name:"Dutch R&B"}]
},
{
name: "Soul",
children: [{name:"Indie Soul"}]
}
]

I now want to run through all tracks in “songs” and populate the size in the respective children of genres. Ideal Output should be:

genres = [
{
name: "Pop",
children: [{name:"Chamber Pop", size:2},{name:"Indie Pop", size:3}]
},
{
name: "R&B",
children: [{name:"Dutch R&B", size:1}]
},
{
name: "Soul",
children: [{name:"Indie Soul", size:2}]
}
]

Any help on this would be appreciated. I’ll be using javascript for this, happy to use lodash/underscore as well if it’s more efficient.

I know how to loop through tracks, but once I have a particular child genre, I’m not able to efficiently map it to the genres variable

react-router stays on login-page instead of dashboard route

My goal was to create protected routes. This now kinda works but I manually need to refresh the page for it to navigate me to the dashboard after logging in. At the moment all that happens is: I log in, get the success toast and it tries to navigate to the dashboard but it lands back on the landing page. Then I need to reload the page manually to access the dashboard.

routes.jsx

import React, { useContext } from 'react';
import { UserContext } from './context/userContext';
import {
    BrowserRouter as Router,
    Route,
    Routes,
    Navigate,
} from 'react-router-dom';
import Dashboard from './pages/dashboard';
import Landingpage from './pages/landingpage';
import Profile from './pages/profile';
import Login from './pages/auth/login';
import Register from './pages/auth/register';
import Friends from './pages/friends';
import Notifications from './pages/notifications';
import { Loader } from 'lucide-react';

function MyRoutes() {
    const { user, loading } = useContext(UserContext);

    if (loading) {
        return <Loader />;
    }

    return (
        <Router>
            <Routes>
                {user ? (
                    <>
                        <Route path='/dashboard' element={<Dashboard />} />
                        <Route path='/profile' element={<Profile />} />
                        <Route path='/friends' element={<Friends />} />
                        <Route
                            path='/notifications'
                            element={<Notifications />}
                        />
                        <Route
                            path='*'
                            element={<Navigate to='/dashboard' />}
                        />
                    </>
                ) : (
                    <>
                        <Route path='/' element={<Landingpage />} />
                        <Route path='/login' element={<Login />} />
                        <Route path='/register' element={<Register />} />
                        <Route path='*' element={<Navigate to='/login' />} />
                    </>
                )}
            </Routes>
        </Router>
    );
}

export default MyRoutes;

userContext.jsx

import React, { createContext, useState, useEffect } from 'react';
import axios from 'axios';

export const UserContext = createContext();

export const UserContextProvider = ({ children }) => {
    const [user, setUser] = useState(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        setLoading(true);
        axios
            .get('/profile')
            .then((response) => {
                if (response.data.success) {
                    setUser(response.data.user);
                } else {
                    setUser(null);
                }
            })
            .catch(() => {
                setUser(null);
            })
            .finally(() => {
                setLoading(false);
            });
    }, []);

    return (
        <UserContext.Provider value={{ user, setUser, loading, setLoading }}>
            {children}
        </UserContext.Provider>
    );
};

authContoller.jsx (backend route /profile)

const getProfile = async (req, res) => {
    logger.info(texts.INFO.ATTEMPTING_PROFILE_RETRIEVAL);
    const { token } = req.cookies;

    if (token) {
        jwt.verify(
            token,
            'idsfu&ASUDIhiedUioGYUYFHIUGTygbhbhY3427HS',
            {},
            async (err, decoded) => {
                if (err) {
                    logger.warn(texts.WARNINGS.INVALID_TOKEN);
                    return res.json({ error: texts.WARNINGS.INVALID_TOKEN });
                }

                try {
                    const user = await User.findById(decoded.id).select(
                        '-password -goals'
                    );
                    if (!user) {
                        logger.warn(texts.WARNINGS.USER_NOT_FOUND);
                        return res
                            .status(404)
                            .json({ error: texts.WARNINGS.USER_NOT_FOUND });
                    }

                    logger.info(texts.SUCCESS.USER_LOGGED_IN(user.username));
                    res.json({ success: true, user });
                } catch (error) {
                    logger.error(
                        texts.ERRORS.ERROR('user profile retrieval', error)
                    );
                    res.status(500).json({
                        error: texts.ERRORS.USER_PROFILE_RETRIEVAL,
                    });
                }
            }
        );
    } else {
        logger.warn(texts.WARNINGS.NO_TOKEN_FOUND);
        res.json(texts.WARNINGS.NO_TOKEN_FOUND);
    }
};

login.jsx (only the logic)

const [data, setData] = useState({
        emailOrUsername: '',
        password: '',
    });
    const { setUser } = useContext(UserContext);
    const navigate = useNavigate();
    const { addToast } = useToast();

    const loginUser = async (event) => {
        event.preventDefault();
        const { emailOrUsername, password } = data;
        try {
            const { data } = await axios.post('/login', {
                emailOrUsername,
                password,
            });

            if (data.error) {
                addToast(data.error, 'error');
            } else {
                setUser(data.user);
                setData({});
                navigate('/dashboard');
                addToast('Login erfolgreich!', 'success');
            }
        } catch (error) {
            addToast(
                'Login fehlgeschlagen. Bitte versuchen Sie es erneut. ' + error,
                'error'
            );
        }
    };```

How to load google map javascript API in phantom js?

I am trying to load google map JavaScript API in phantom js but failed to load.

`var page = require('webpage').create();

//Handle console messages
page.onConsoleMessage = function(msg) {
    console.log('Console: ' + msg);
};

page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3';
// Handle errors
page.onError = function(msg, trace) {
    console.error('Error: ' + msg);
    trace.forEach(function(t) {
        console.error('  -> ' + t.file + ': ' + t.line);
    });
};

page.onResourceError = function(resourceError) {
    console.log('Resource error: ' + resourceError.url + ' - ' + resourceError.errorString);
};

//Handle resource received events
page.onResourceReceived = function(response) {
    console.log('Resource received:');
    console.log('  URL: ' + response.url);
    console.log('  Status: ' + response.status);
    console.log('  Time: ' + response.time + ' ms');
    console.log('  Content type: ' + response.contentType);
};
page.open('URL/map1.html', function(status) {
    if (status === 'success') {
        console.log('Page loaded successfully.'+status);
        window.setTimeout(function() {
            console.log(google);
             if (typeof google !== 'undefined' && typeof google.maps !== 'undefined') {
                 console.log('Page loaded successfully.');
             }
            page.render('map11.jpg');
            phantom.exit();
        }, 20000); // Wait for 10 seconds
    } else {
        console.log('Failed to load the page');
    }
});
`

I tried this code URL/map1.html has code to create google map but failed satisfying my requirement.
I need a solution for the same

How to build an application for managing technical vehicle information with user authentication? [closed]

I’m currently working on a project for my Information Technology degree to create an application that manages technical vehicle information. The application will have two types of users: admins and regular users. Admins need the ability to add, modify, and delete vehicle data, while users should be able to log in and view this data.

Requirements and Considerations:

User Roles:

*Admins: Can manage vehicle information.
*Users: Can view vehicle information.

Features Needed:

*User authentication (login/logout).
*CRUD operations for vehicle information.
*Search and filter functionality.

As this is my first big project, I’m unsure where to start and would greatly appreciate any guidance. At this stage I have some experience with Python, C++ and JavaScript.

I’d appreciate any insights on the architecture, libraries, or frameworks that might be useful for this application. Thank you!

At this stage I am only planning and want a general idea of what I should do to implement this application.

Eslint to throw an error when promise is being assigned to a variable [duplicate]

I’ve had so many cases where what I mean to do was const a = await b() but I forget to add await and spending more than I should to figure out why the response body is empty. I’m wondering if there is an eslint rule I can add for this. In rare cases where I want to assign a Promise to a variable, I’m willing to add a disable eslint line comment.

async function test() {
    return Promise.resolve('something')
}

router.get(
    '/something',
    (req: Request, res: Response) => {
        const user = test()
                ^^^ here I want to see an error for assigning a promise to a variable
        return user
    }
)

Right now I have following rules which non of them seem to cover my requirement.

    "promise/always-return": "error",
    "promise/no-return-wrap": "error",
    "promise/param-names": "error",
    "promise/catch-or-return": "error",
    "promise/no-native": "off",
    "promise/no-nesting": "error",
    "promise/no-promise-in-callback": "error",
    "promise/no-callback-in-promise": "error",
    "promise/avoid-new": "off",
    "promise/no-new-statics": "error",
    "promise/no-return-in-finally": "error",
    "promise/valid-params": "error",
    "promise/no-multiple-resolved": "error",
    "@typescript-eslint/no-floating-promises": "error",
    "@typescript-eslint/no-misused-promises": [
      "error",
      {
        "checksVoidReturn": false
      }
    ],

How to rotate thumbs on touchy?

How can I add support for mobile devices maybe any jquery swipe or any other way?
Here is my fiddle

Thumbs rotation is working fine the only problem is in mobile devices I have to click to rotate but instead I want to rotate on swipe.

Is there any way to correct my code for both desktop and mobile devices?
Thanks

I have tried with touchstart but it doesn’t work.

jQuery(document).ready(function($) {
    var t = null,
        r = !1;
    $("body").on("mouseenter", ".thumbs", function(e) {
        var o = jQuery(this);
        if (r = !1, void 0 != o.data("thumbs")) {
            var u = o.data("thumbs").split(","),
                i = u.length,
                a = 1;
            t = null, clearTimeout(t), (t = function() {
                0 == r && (o.find("img").attr("srcset", u[a]), a <= i && (a == i && (a = 0), setTimeout(t, 500), a++))
            })()
        }
    }).on("mouseleave", ".thumbs", function(e) {
        r = !0, t = null;
        for (var o = setTimeout(";"), u = 0; u < o; u++) clearTimeout(u);
        var i = $(this).find("img"),
            a = i.attr("src");
        i.attr("srcset", a)
    }).on('touchstart', ".thumbs", function(e) { 
        r = !0, t = null;
        for (var o = setTimeout(";"), u = 0; u < o; u++) clearTimeout(u);
        var i = $(this).find("img"),
            a = i.attr("src");
        i.attr("srcset", a)
        })
});

‘event’ is deprecated.ts(6385)

So I’m currently having issues getting around this ‘event’, from what I’ve currently read i need to pass it through an event handler function as when used in external JS ‘event’ is for windows.event.

var tablinks = document.getElementsByClassName("tab-links");
var tabcontents = document.getElementsByClassName("tab-contents");
function opentab(tabname) {
    for (tablink of tablinks) {
        tablink.classList.remove("active-link")
    }
    for (tabcontent of tabcontents) {
        tabcontent.classList.remove("active-tab");
    }
    event.currentTarget.classList.add("active-link");
    document.getElementById(tabname).classList.add("active-tab");
}

Something along the lines of..

tablink.addEventListener('click', function(event) {
    opentab(event, 'active-tab');

Would someone care to break this down for me?
Appreciate it.

Attempted to replace the code using event handler.

Don’t allow the google sheet user to change the data after entering once except sheet owner

in sheet "FMS" i am trying to apply a script from chat-gpt for column AA:AB. there are prefilled data before applying the script. that is working the wrong way. the user to whom i have shared the file is allowed to change the prefilled data in column AA while in column AB is it is not allowing to fill even empty cells.

what i want is prefilled data should also be protected and the non empty cells should allow to enter data only once. no one can change the data except the file owner. i am not familiar with the scripts. i have pasted the script in line 487. please modify that accordingly.
text

Ajax call says Failed to load resource: the server responded with a status of 500 (Internal Server Error) in laravel

Without ajax call If I call api with the help controller function then the api function is working fine and giving me the data, but If I call the same function with ajax call then I am getting the above error. Please help me to solve this issue.

const dateInput= document.getElementById('dateInput');  
const selectedDate = new Date(dateInput.value); 
    
$.ajax({
    type: 'get',
    url: '{{route("demo.function")}}',
    data: {
        'date' : selectedDate.toISOString().split('T')[0]
    },
    success: function(data) {
    var info = data.info;
    console.log("Information: " + info);
},
    error: function(error) {
        console.log(error,'There is some error here!');
    }
});

If demo.function route is callilng from my controller, demoFunction will be called when I am working with databased it working fine. But When I am doing the below thing, it’s not working: Failed to load resource: the server responded with a status of 500 this error I am getting. but when I testing api to get the data it working fine. but when with help of ajax request I am calling the function for getData it’s not wokring.

After calling the function in controller like this:

public function demoFunction(Request $request){
        $date = $request->input('date');
        $info = getData($date); // Api call function
        return response()->json(['message' => 'Data processed successfully', 'info'=> $info]);
    }

For getting Data from api:

public function getData($date){

    for($i=0; $i<21; $i++){
        $Payload = {
            // my data
        }
        
        try {
                    // Send the request
                    $response = $client->request('POST', 'http://xx.xx.xx.xx/my-ws/dynamic-data.html', [
                        'headers' => [
                            'Content-Type' => 'text/xml; charset=utf-8',
                        ],
                        'body' => $Payload,
                    ]);
        } catch (Exception $e) {
                    return response()->json(['error' => 'Request is not successfull'], 500);
        }

        $info[] = [
            'info' => $response->getBody();
        ];
    }

    return $info;
}

Thanks in Advance.