Cannot move to previous slide in a JavaScript Slider

let currentIndex = 0;
const slides = document.querySelectorAll('.slide');
const totalSlides = slides.length;

function updateSlides() {
  slides.forEach((slide, index) => {
    if (index < currentIndex) {
      slide.style.width = '0%';
      slide.style.left = '0%';
      slide.style.opacity = '0';
      slide.style.visibility = 'hidden';
      slide.style.transition = 'all 0.5s ease-out';
    } else if (index === currentIndex) {
      slide.style.right = '100%';
      slide.style.opacity = '1';
      slide.style.visibility = 'visible';
      slide.style.transition = 'all 1s ease-out';
    } else {
      slide.style.opacity = '1';
      slide.style.visibility = 'visible';
      slide.style.transition = 'all 1s ease-out';

    }
  });
}

// Function for next slide (move forward)
function nextSlide() {
  if (currentIndex < totalSlides - 1) {
    currentIndex++;
    updateSlides();
  }
}

// Function for previous slide (move backward)
function prevSlide() {
  if (currentIndex > 0) {
    currentIndex--;
    updateSlides();
  }
}

// Event listeners for the navigation buttons
document.querySelector('.next-button').addEventListener('click', nextSlide);
document.querySelector('.prev-button').addEventListener('click', prevSlide);

// Optionally, use the automatic slider function (if you want both auto and manual navigation)
//setInterval(() => {
//  nextSlide(); // This will trigger auto-sliding
//}, 3000);
.prev-button, .next-button {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  background-color: rgba(0, 0, 0, 0.5);
  color: white;
  border: none;
  padding: 10px;
  cursor: pointer;
  font-size: 1.5em;
  z-index: 10;
}

.prev-button {
  left: 10px;
}

.next-button {
  right: 10px;
}

.slider-container {
  width: 100%;
  overflow: hidden;
  position: relative;
  height: 280px;
}

.slider {
  position: relative;
  height: 100%;
  width: 100%; /* Enough space for all 4 slides */
  display: flex;
  transition: transform 3s ease-in-out;
}

.slide {
  position: absolute;
  height: 100%;
  transition: width 3s ease-in-out, left 3s ease-in-out;
}

.slide.yellow {
  z-index: 4;
  left: 0%;
   width: calc(100% - 60px);
}

.slide.pink {
  z-index: 3;
  left: 0%; 
    width: calc(100% - 40px);
}

.slide.blue {
  z-index: 2;
  left: 0%; 
  width: calc(100% - 20px);
}

/* The background slide */
.slide.green {
  z-index: 1;
  left: 0%; 
  width: 100%;
}
<!-- Navigation buttons -->
  <button class="prev-button">Previous</button>
  <button class="next-button">Next</button>

<div class="slider-container">
    <div class="slider">
      <div class="slide yellow" style="background-color: #ffea92"><div class="content">yellow</div></div> <!-- 1. Slide -->
      <div class="slide pink" style="background-color: #e2c6e0"><div class="content">pink</div></div> <!-- 2. Slide -->
      <div class="slide blue" style="background-color: #b9d7f3"><div class="content">blau</div></div> <!-- 3. Slide -->
      <div class="slide green" style="background-color: #8ebf1e"><div class="content">green</div></div> <!-- 4. Slide -->
     
    </div>
  </div>

Hello,

I have a slider with different layers. Later, some text will be inserted in the layers. The layers should look like sheets lying on top of each other. With the buttons for previous and next I want to jump between the layers.

The Next-Button works fine. Previous-Button does not work. What is wrong? Thanks for your advice.

Alternatives to iFrames to prevent third party cookie blocking, with minimal effort for clients?

I have a platform on mydomain.com

My clients have their own websites i.e client.com, and they embed my page into their website using an iFrame so that customers can navigate through a checkout flow.

My page tries to read the session cookie through the iFrame, which results in third party blocks (because of the domain jump).

I can solve this by having each client create a subdomain subdomain.client.com and point this towards my domain with a CNAME. Now the cookie is considered first party, but it feels like a bit of a workaround and requires network configuration from the client.

If I was to re-architect this from scatch, what options do I have in a world away from iFrames? Can Web Components or Javascript Widgets help me overcome this problem, without requiring network configuration from the client, or are there other modern approaches which don’t require cookies for auth etc?

Getting connection timeout when connecting to mysql container [duplicate]

I am new to NodeJS and I am not able to connect to Mysql container no matter what I do.
I have given the credentials and other information related to the error below.
When I try with the container-ip I’ll get the below error
I am using mysql2 version 1.6.1

Even if the credentials are proper , I am not able to reach my MySQL server.
I can reach it from the CLI.

Database connection failed: Error: connect ETIMEDOUT
    at PoolConnection._handleTimeoutError (C:UsersAkhilDownloads1-connecting-our-app1-connecting-our-appnode_modulesmysql2libconnection.js:169:17)
    at listOnTimeout (node:internal/timers:594:17)
    at process.processTimers (node:internal/timers:529:7) {
  errorno: 'ETIMEDOUT',
  code: 'ETIMEDOUT',
  syscall: 'connect',
  fatal: true
}

My MySQL config looks like this

const mysql = require(“mysql2”);

const pool = mysql.createPool({
  host: "172.17.0.2",
  user: "root",
  database: "node-db",
  password: "mypass123",
  port: 3306,
  connectTimeout: 10000,
  waitForConnections: true,
});

module.exports = pool.promise();

I used it like this,

const pool = require("../util/database");

exports.getIndex = async (req, res, next) => {
  try {
    const connection = await pool.getConnection();
    console.log("Database connection successful");

    // Add connection info to request object
    req.dbStatus = {
      connected: true,
      timestamp: new Date().toISOString(),
    };

    connection.release();
    next();
  } catch (error) {
    console.error("Database connection failed:", error);
    req.dbStatus = {
      connected: false,
      error: error.message,
      timestamp: new Date().toISOString(),
    };
    next();
  }

Docker command I used to create the Mysql container:

docker run --name mysql -p 3306:3306 -v C:/Users/Akhil/Downloads/mysql-data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD="mypass123" -d --restart always mysql

C:UsersAkhil>docker inspect -f '{{range.NetworkSettings.Networks}}{{.IPAddress}}{{end}}' mysql
'172.17.0.2'

I have attached the scroll event to table based on the scrollTop Value, what other way can I attach a scroll event to table without scrollTop?

I’m implementing virtual scrolling in JS by attaching the scroll event based on scrollTop value. even a slight change in the scrollTop value will trigger the Scroll Event.

So whenever the scroll Event triggers it fetches data and re-renders rows. But that is too much fetching and re-rendering for every slight scroll. So I’m wondering is there a way we can attach the scroll event to the table without the use of ScrollTop value ?.

Is there a way to notify a web socket if they are not permitted to subscribe using spring-security?

For the full repo look here

I have the following…

    @Bean
    fun messageAuthorizationManager(
        messages: MessageMatcherDelegatingAuthorizationManager.Builder
    ): AuthorizationManager<Message<*>> {
        messages
            // Next 2 lines are required for requests without auth.
            // Remove these if all paths require auth
            .simpTypeMatchers(SimpMessageType.CONNECT).permitAll()
            .simpTypeMatchers(SimpMessageType.DISCONNECT).permitAll()
            .simpDestMatchers("/topic/greetings", "/app/hello").authenticated()
            .simpDestMatchers("/topic/status", "/app/status").permitAll()
            .anyMessage().authenticated()
        return messages.build()
    }
    @MessageMapping("/hello")
    @SendTo("/topic/greetings")
    fun greeting(message: TestMessage): Greeting {
        logger.info(message.toString())
        return Greeting("Hello, " + message.name + "!")
    }

    @MessageMapping("/status")
    @SendTo("/topic/status")
    fun status(message: String): String {
        return "Status: $message"
    }

However, when I try to consume these in JS like

    const subscribeToGreetings = useCallback(() => {
        if (!client || !client.active) return;

        setCanRetryGreetings(false);
        console.log('Attempting to subscribe to greetings...');
        client.subscribe('/topic/greetings',
            (message) => {
                console.log('Received greeting:', message);
                setMessages(prev => [...prev, `Greeting: ${message.body}`]);
            },
            {
                onError: (err) => {
                    console.error('Subscription error frame:', err.command, err.headers, err.body);
                    setMessages(prev => [...prev, `Permission denied: Cannot subscribe to greetings (${err.headers?.message || 'Unknown error'})`]);
                    setCanRetryGreetings(true);
                }
            }
        );
    }, [client]);

On the front end I just see

Attempting to subscribe to greetings…

I never actually see the onError part run. On the backend I do see….

2025-02-07T12:59:38.360-05:00 DEBUG 50220 --- [websocket] [nio-7443-exec-4] .s.m.a.i.AuthorizationChannelInterceptor : Failed to authorize message with authorization manager org.springframework.security.messaging.access.intercept.MessageMatcherDelegatingAuthorizationManager@30c62bbb and result AuthorizationDecision [granted=false]
2025-02-07T12:59:38.360-05:00 DEBUG 50220 --- [websocket] [nio-7443-exec-4] o.s.w.s.m.StompSubProtocolHandler        : Failed to send message to MessageChannel in session da876e1d-f266-eb9f-08e4-8dc7e068b0fa
...
Caused by: org.springframework.security.access.AccessDeniedException: Access Denied
    at org.springframework.security.messaging.access.intercept.AuthorizationChannelInterceptor.preSend(AuthorizationChannelInterceptor.java:75) ~[spring-security-messaging-6.4.2.jar:6.4.2]

So what am I missing why isn’t the front end getting notified that their request to subscribe has failed?

How can I add Docusign EnvelopeID in a custom href text field in a Docusign Template / Envelope?

I created a template in Docusign with multiple fields, one of them is a custom href field that opens a new tab to a custom application (https://mycustomapp.com). I want to be able to map the envelopeID as a query parameter into that url but I’m unable to do so in the UI, I’m setting the value of my field like this: https://mycustomapp.com?envelopeID=[[EnvelopeID]] but this doesn’t work. Is there a workaround for this or do I need to do it another way through the Docusign API?

Where is the context state set in React Context?

I’ve created an app that stores user information in firebase.

The main profile page consumes the data via a hook that retrieves the data from firebase/storage. What I’m trying to do in this page is get the profile data from the hook and set the profile data in the actual context. I realize this may not be the right now but it’s what’s been prescribed by ChatGPT.

export const ProfileForm = () => {
  const [profile, setProfile] = useState({
    username: "",
    bio: "",
    gender: "",
    sexo: "",
    edu: "",
    drinking: "",
    smoking: "",
    dob: "",
  });
  const [showLogin, setShowLogin] = useState(false);
  const { userProfile, setUserProfile } = useGetUserProfile();
  const { userProfileContext, setUserProfileContext } = useUserProfile()

  useEffect(() => {
    if (userProfile) {
      setProfile(userProfileContext);
    }
  }, [userProfile, setUserProfile]);

  const { showAlert } = useContext(AlertContext);

  return (
    <>
      <form onSubmit={handleSubmit(onSubmit)} noValidate>
        <Box display="flex" justifyContent="flex-end" p={2}>
          <Button
            variant="contained"
            color="secondary"
            onClick={async () => {
              await signOut(auth);
              window.location.href = "/login";
            }}
            sx={{
              borderRadius: "50%",
              width: 80,
              height: 80,
            }}>
            <span role="img" aria-label="logout">
              Logout
            </span>
          </Button>
        </Box>
        <Box mt={0} display="flex" justifyContent="center">
          <img
            src={profilePlaceholder}
            alt="Profile Placeholder"
            style={{ maxWidth: "100%", height: "auto" }}
          />
          <Box sx={{ flexDirection: "column" }}>
            <Typography
              ml={2}
              fontSize={{ base: "sm", md: "lg" }}
              color="white"
              sx={{ fontSize: "2rem" }}>
              {profile?.username || ""}
            </Typography>
            <Button
              variant="contained"
              size="small"
              onClick={() => setShowLogin(true)}
              sx={{ marginTop: 2, background: "white", color: "black" }}>
              Edit Profile
            </Button>
          </Box>
        </Box>
        <Card
          variant="outlined"
          sx={{
            display: "flex",
            flexDirection: "column",
            gap: 2,
            p: 2,
            maxWidth: 300,
            margin: "20px auto 20px auto",
          }}>
          <FormControl>
            <TextField
              id="bio"
              label="User Bio"
              multiline
              autoFocus
              rows={4}
              value={profile?.bio || ""}
              name="bio"
              placeholder="Tell us about yourself"
              InputProps={{
                readOnly: true,
              }}
            />
          </FormControl>
          <FormControl required>
            <TextField
              label="*Date of birth"
              type="date"
              id="dob"
              name="dob"
              value={
                profile?.dob
                  ? new Date(profile?.dob).toISOString().split("T")[0]
                  : new Date().toISOString().split("T")[0]
              }
              InputProps={{
                readOnly: true,
              }}
            />
          </FormControl>
          <FormControl>
            <TextField
              id="gender"
              value={profile?.gender || ""}
              required
              fullWidth
              name="gender"
              label="Gender"
              InputProps={{
                readOnly: true,
              }}></TextField>
          </FormControl>
          <FormControl>
            <TextField
              id="sexo"
              value={profile?.sexo || ""}
              required
              fullWidth
              name="sexo"
              label="Sexual Orientation"
              InputProps={{
                readOnly: true,
              }}></TextField>
          </FormControl>
          <FormControl>
            <TextField
              id="edu"
              value={profile?.edu || ""}
              required
              label="Education"
              name="edu"
              InputProps={{
                readOnly: true,
              }}></TextField>
          </FormControl>
          <FormControl>
            <TextField
              id="drinking"
              required
              value={profile?.drinking || ""}
              label="Drinking"
              name="drinking"
              InputProps={{
                readOnly: true,
              }}></TextField>
          </FormControl>
          <FormControl>
            <TextField
              id="smoking"
              required
              value={profile?.smoking || ""}
              label="Smoking"
              name="smoking"
              InputProps={{
                readOnly: true,
              }}></TextField>
          </FormControl>
        </Card>
      </form>
      <EditProfileModal show={showLogin} close={() => setShowLogin(false)} />
    </>
  );
};

The profile page has an edit modal that edits the profile data and stores it in the backend.

MODAL

export const EditProfileModal = (props: any) => {
  const { userRef, setUserDbData } = usePostUserProfileToDb();
  const { userStorageData, setUserStorageData } = usePostUserProfileToStorage();
  const { userProfile, setUserProfile } = useGetUserProfile();

  const [profile, setProfile] = useState({
    username: "",
    bio: "",
    gender: "",
    sexo: "",
    edu: "",
    drinking: "",
    smoking: "",
    dob: "",
  });

  useEffect(() => {
    if (userProfile) {
      setProfile(userProfile);
    }
  }, [userProfile, setUserProfile]);

  
  const handleSubmit = async (e: any) => {
    e.preventDefault();
    try {
      setUserStorageData(profile);
      setUserDbData(profile);
      props.close();
    } finally {
      setIsSubmitting(false);
    }
  };

And here is the context.

import React, { createContext, useState, useContext } from 'react';

const UserProfileContext = createContext(null);


export const UserProfileProvider = ({ children }) => {
  const [userProfileContext, setUserProfileContext] = useState(null);

  return (
    <UserProfileContext.Provider value={{ userProfile: userProfileContext, setUserProfile: setUserProfileContext }}>
      {children}
    </UserProfileContext.Provider>
  );
};

export const useUserProfile = () => {
  const context = useContext(UserProfileContext);
  if (!context) {
    throw new Error('useUserProfile must be used within a UserProfileProvider');
  }
  return context;
};

When I try to set the context in the hook I get the following error:

This expression is not callable.
  Type 'never' has no call signatures.
import { useEffect, useState } from "react";
import useGetUserId from "./useGetUserId";
import { app } from "../environments/environment";
import { doc, getDoc, getFirestore } from "firebase/firestore";
import { useUserProfile } from "../Context/UserProfileContext";

const useGetUserProfile = () => {
  type profile = {
    email: string;
    username: string;
    userBio: string;
    dob: Date;
    gender: string;
    sexo: string;
    education: string;
    drinkingHabits: string;
    smokingHabits: string;
  };

  const db = getFirestore(app);
  const userId: string | null = useGetUserId();
  const [isLoading, setIsLoading] = useState(true);
  const [userProfile, setUserProfile] = useState<any | null>(null);
  const { userProfileContext, setUserProfileContext } = useUserProfile()

  useEffect(() => {
    const userProfile = async () => {
      setIsLoading(true);
      try {
        const userRef = localStorage.getItem("PROFILE_INFO");
        if (userRef) {
          const profile: profile = JSON.parse(userRef);
          setUserProfile(profile);
          setUserProfileContext(profile)
        } else {
          if (userId) {
            const id = JSON.parse(userId);
            const userRef = await getDoc(doc(db, "users", id.user.uid));
            if (userRef.exists()) {
              const profile = userRef.data();
              setUserProfile(profile);
            }
          }
        }
      } catch (error) {
        console.log("error", error);
      } finally {
        setIsLoading(false);
      }
    };
    userProfile();
  }, [setUserProfile]);
  return {
    isLoading,
    userProfile, setUserProfile
  };
};

export default useGetUserProfile;

So I’m not sure what I’m doing wrong. Where exactly does the context value get set, only in the children? From the context children, do you retrieve the profile data from the hooks and then set it, or do you set the context data in the hooks?

mongoose with dynamic properties

pretty new to mongoose, I have my dropdown options in the structure below. This way the overall group holds the collection of dropdown options… a task page would have options for “status”, “result”, a user page have “typePhone”, etc.

what is the correct way build a Schema for such a structure? Thinking I’m going to have to transform it to the below somehow if I can’t store as is.

{
  "task": {
    "status": [
      {
        "key": 0,
        "text": "pending"
      },
      {
        "key": 1,
        "text": "in progress"
      },
      {
        "key": 2,
        "text": "completed"
      },
      {
        "key": 3,
        "text": "cancelled"
      }
    ],
    "result": [
      {
        "key": 0,
        "text": ""
      },
      {
        "key": 1,
        "text": "good"
      },
      {
        "key": 2,
        "text": "not good"
      },
      {
        "key": 3,
        "text": "who knows"
      }
    ]
  },
  "user": {
    "typePhone": [
      {
        "key": "1",
        "text": "Landline"
      },
      {
        "key": "2",
        "text": "Mobile"
      },
      {
        "key": "3",
        "text": "Other"
      }      
    ]
}

Set all the properties of a WebComponent element from a Json using an interface

I have a Card component and a Cards component. The Cards component groups a list of Card components that it obtains through an API. The problem is that I cannot fill all the properties of the Card component with the values ​​that I receive through the API in JSON format and using its corresponding iCard interface.

Card Interface:

export interface iCard {
    idx: number
    name: string
    value: string
    site: string
}

Card Component:

@customElement('sx-card')
export class AppCard extends LitElement implements iCard {
    @property({type: Number}) idx = 1;
    @property({type: String}) name = '';
    @property({type: String}) value = '';
    @property({type: String}) site = '';
    
    render() {
        return html`<span>${this.name}</span>`;
    }
}

Cards Component:

@customElement('sx-cards')
export class AppCards extends LitElement {
    connectedCallback(): void {
        super.connectedCallback();
        this.loadCards();
    }
    
    async loadCards(): void {
        let ajaxService = new AjaxService();
        let cards = await ajaxService.getCards();

        cards.forEach((card: iCard) => {
            let elCard: AppCard = document.createElement('sx-card') as AppCard;
            // This is where I need to pass the values ​​from the "card" response to the "elCard" component
            this.appendChild(elCard);
        });
    }
}

The Card component implements the iCard interface and the API response is an instance of the iCard interface, what I need is to pass the values ​​from the API response to the component. It seems to me that since the response is of type iCard and the component implements iCard there must be a better way than assigning them one by one.

And if you have any suggestions to improve the code I will appreciate it, I am learning TS.

How do import and use a TypeScript class from a module on my HTML page?

This seems like something so elementary, but I’ve wasted so much time struggling with it. I’ve gone through dozens of different resources, documents, and Stack Overflow questions, and if the answers I need were in there I missed them among the plethora of stated solutions that didn’t work. Any help will be very much appreciated. 🙂

So I’ve got a class in TypeScript. My goal is to be able to, in a script tag on an HTML page, create an instance of that class and call a function on it. For the sake of relevance, we’ll keep it simple:

import { MyDependency } from ...

export default class MyClass {
  constructor(...) {
     ...
  }

  doSomething() {
     var example = new MyDependency()
  }
}

In actuality, there’s many classes, in many files, which have dependencies on both one another and a variety of NPM packages. Through some convoluted methods that I’m looking to replace by asking this question, I know this code runs and can be executed in the browser. Just in case it’s relevant, here’s my tsconfig anyway:

{
  "compilerOptions": {
    ...
    "sourceMap": true,
    "target": "ES2017",
    "moduleResolution": "Node",
    "module": "UMD",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "lib": [ "esnext", "dom" ]
  }
  ...
}

We’re running webpack on this stuff. The webpack config looks like so:

module.exports = {
    entry: {
        "my-class": path.resolve(__dirname, "./ts/my-directory/my-class.ts"),
        "my-dependency": path.resolve(__dirname, "./ts/my-directory/my-dependency.ts")
    },
    module: {
        rules: [
            {
                test: /.tsx?$/,
                use: "ts-loader"
            },
            {
                test: /.m?js/,
                resolve: {
                    fullySpecified: false,
                },
            }
        ],
    },
    resolve: {
        alias: {
            'node_modules': "/node_modules"
        },
        extensions: [".tsx", ".ts", ".js", ".css"]
    },
    output: {
        filename: "[name].js",
        libraryTarget: "umd",
        library: "MyLibrary",
        libraryExport: "default",
        path: path.resolve(__dirname, "dist")
    },
};

Running webpack with this will successfully generate a my-class.js file.

Lastly, one example of an attempt to invoke this on a page:

<Script src="/dist/my-class.js"></Script>

<script type="module">
        var instance = new window.MyLibrary.MyClass()
        instance.doSomething()
</script>

This particular attempt is failing with a message that it cannot find the module for MyDependency, which is frankly further than most permutations have gotten. I’ve messed around with import, import(), require(), expose-loader, and various other things; usually I’m told either the my-class module does not exist, or that it does not contain an export called MyClass (which the generated my-class.js clearly does, so I guess the module wasn’t loading correctly?).

Any recommendations, again, will be much appreciated!

Get a Nonreactive Value from a Reactive Svelte Store

I have a component that pulls data from a Svelte Store. I access values throughout the component using $myStore.value or $myStore.readOnly. These are obviously reactive. When a user clicks on $myStore.value in a text input field, I open a modal where the user can change the value which, in turn, updates the store. The store can also be updated by a web hook that’s running in another process. This means that the modal value can be updated by the webhook while the user is editing it (which I don’t want). The goal is to have the last value take precedence. I’m spinning my wheels trying to find a way to send the current value to the modal, but have the modal’s displayed value be nonreactive and persist only until the modal is closed or edited.

I’ve tried variations of get(), snapshot() and inspect() which either don’t do what I want, or I’m using them incorrectly. For example:

import { get } from 'svelte/store'
export let myStore;
console.log($myStore.readOnly);  // This works
console.log(get(myStore.readOnly));  // This is undefined

What am I missing? There must be a simple way to get a nonreactive copy of a Store value at a point in time.

How should I edit the code for sending messages from Google Script to Discord?

function doPost(e) {
  // ตรวจสอบว่ามีข้อมูลส่งมาจาก Tradingview เข้ามาหรือไม่
  if (!e || !e.postData || !e.postData.contents) {
    return ContentService.createTextOutput("No POST data received.");
  }
  
  // Discord Webhook URL
  const discordWebhookUrl = "ME";
  
  // รับข้อความจาก post data และตัดช่องว่างหัวท้ายออก
  let inputMessage = e.postData.contents.trim();
  
  // ใช้ PropertiesService ในการเก็บสถานะ Trend (Bullish หรือ Bearish)
  const scriptProperties = PropertiesService.getScriptProperties();
  let currentTrend = scriptProperties.getProperty("currentTrend");
  
  // ตรวจสอบข้อความสำหรับเปลี่ยน Trend
  if (inputMessage === "Bullish") {
    currentTrend = "Bullish";
    scriptProperties.setProperty("currentTrend", currentTrend);
    // สามารถเลือกส่งข้อความแจ้งอัพเดท Trend ได้ (ถ้าต้องการ)
    // inputMessage = "Trend เปลี่ยนเป็น Bullish";
  } else if (inputMessage === "Bearish") {
    currentTrend = "Bearish";
    scriptProperties.setProperty("currentTrend", currentTrend);
    // inputMessage = "Trend เปลี่ยนเป็น Bearish";
  }
  
  // ตรวจสอบ Trade Signal เมื่อมี Trend อยู่แล้ว (ใช้ Trend เดิมจนกว่าจะเปลี่ยน)
  if ((inputMessage === "Buy" || inputMessage === "Strong Buy") && currentTrend === "Bullish") {
    inputMessage = "Long USDJPY TF1";
  } else if ((inputMessage === "Sell" || inputMessage === "Strong Sell") && currentTrend === "Bearish") {
    inputMessage = "Short USDJPY TF1";
  }
  
  // เตรียม payload สำหรับส่งไปยัง Discord
  let payload = {
    content: inputMessage
  };
  
  // กำหนด options สำหรับ UrlFetchApp.fetch
  let options = {
    method: "post",
    contentType: "application/json",
    payload: JSON.stringify(payload),
    muteHttpExceptions: true
  };
  
  // ส่งข้อความไปที่ Discord ผ่าน Webhook
  try {
    let response = UrlFetchApp.fetch(discordWebhookUrl, options);
    return ContentService.createTextOutput("Success: " + response.getContentText());
  } catch (error) {
    return ContentService.createTextOutput("Error: " + error);
  }
}

I need send massage only “Long USDJPY TF1” and “Short USDJPY TF1”.

“I tried editing the code, but when the program runs, it can send messages other than ‘Long USDJPY TF1’ and ‘Short USDJPY TF1’ to Discord, such as ‘Eat’, ‘Run’ from TradingView alerts. Since I’m a beginner, I’m slowly analyzing the code in GPT.”

How do I filter images from other pages in my image gallery so they show on the current page that I’m on?

Note: I don’t know anything about JavaScript and relied on chatGPT. Please provide the updated JavaScript with the new changes as I relied on chatGPT and wouldn’t know where to add the new changes, thank you!

I’m experiencing an issue with my JavaScript functionality on WordPress.

For example, if I’m on page 1 and I click the “Ruling Planet” filter button (the images with ruling planet data category are on page 6), it’s not showing images from other pages with that filter on page 1. It also applies to any other filter button I click where the images are on other pages. However, it works when I’m on the page. For example, when I’m on page 6 and I click the “Ruling Planet” filter button, it shows on page 6 because the images with that data category are already on page 6. I want the JavaScript functionality to filter images from the entire gallery (across all pages), but still show 20 images per page with the selected filters (not infinite scroll) and still make sure all my pages in the pagination show at the bottom of the page.

Note: I want to only stick to using the custom HTML blocks as I’m still new to WordPress. I don’t want to modify the theme files or anything like that.

I would really appreciate the help! Thank you in advance 🙂

(I tried doing this with chatGPT and it did infinite scroll and just completely removed my pagination numbers at the bottom so I gave up.)

Current JavaScript:

<script>
    document.addEventListener("DOMContentLoaded", () => {
        const filterButtons = document.querySelectorAll(".filter-btn");
        const galleryItems = document.querySelectorAll(".gallery-item");
        const urlParams = new URLSearchParams(window.location.search);
        let activeFilters = urlParams.getAll("filter");

        function applyFilters() {
            if (activeFilters.length === 0) {
                galleryItems.forEach(item => item.style.display = "block");
                return;
            }

            galleryItems.forEach(item => {
                const itemCategories = item.querySelector(".gallery-img").dataset.category.split(" ");
                const match = activeFilters.some(filter => itemCategories.includes(filter));
                item.style.display = match ? "block" : "none";
            });
        }

        if (activeFilters.length > 0) {
            activeFilters.forEach(filter => {
                const btn = document.querySelector(`.filter-btn[data-filter="${filter}"]`);
                if (btn) btn.classList.add("active");
            });
        }

        filterButtons.forEach(button => {
            button.addEventListener("click", () => {
                const filter = button.dataset.filter;
                button.classList.toggle("active");

                if (activeFilters.includes(filter)) {
                    activeFilters = activeFilters.filter(f => f !== filter);
                } else {
                    activeFilters.push(filter);
                }
                updateURL();
            });
        });

        function updateURL() {
            const url = new URL(window.location);
            url.searchParams.delete("filter");
            activeFilters.forEach(filter => url.searchParams.append("filter", filter));
            history.pushState(null, "", url);
            applyFilters();
        }

        const paginationLinks = document.querySelectorAll(".pagination a");
        paginationLinks.forEach(link => {
            link.addEventListener("click", e => {
                e.preventDefault();
                const pageUrl = new URL(link.href);
                activeFilters.forEach(filter => pageUrl.searchParams.append("filter", filter));
                window.location.href = pageUrl.toString();
            });
        });

        applyFilters();
    });
</script>

a app for that students learn programation [closed]

We are developing an app that allows to learn programming in an autonomous way, it is focused on people who find it difficult to learn in the traditional way, I want to know if the app can be relevant to learn with didactic games or other forms.

I want to know if an application with these features will be useful?

How to prevent CSS transitions from interrupting each other by any JS triggers?

such a situation:

1 background layer, 4 pictures that should replace each other in this background layer – in a time interval (4 sec) with a soft transition (1,5 sec), and 4 links/buttons which should trigger the necessary picture background on mouseover. The changed background should stay until the mouse leaves the button.

The problem: if I bring the mouse over a link while a transition (no matter how it’s triggered), the called background picture is set straight away and by a hard transition. How to prevent it?

I’m gonna put here shortened code where only the relevant things are:

HTML:

<div class="bg-image" id="bg-image-de-de"></div>
    <a class="experience-now" data-lang="DE" id="sphere1" onmouseover="imageOne();" onmouseleave="backToChangeBG();">Image 01</a>
    <a class="experience-now" data-lang="DE" id="sphere2" onmouseover="imageTwo();" onmouseleave="backToChangeBG();">Image 02</a>
    <a class="experience-now" data-lang="DE" id="sphere3" onmouseover="imageThree();" onmouseleave="backToChangeBG();">Image 03</a>
    <a class="experience-now" data-lang="DE" id="sphere4" onmouseover="imageFour();" onmouseleave="backToChangeBG();">Image 04</a>

CSS:

.bg-image {
    background-image: url(../_img/Picture1.jpg);
    transition-duration: 1500ms !important;
    transition-property: background-image;
    width: 100%;
    height: calc(100% - 50px);
    background-position: top center;
    background-repeat: repeat-y;
    background-size: cover;
    background-blend-mode: normal;
    background-color: #e6e6eb;
    position: fixed;
} 

JS:

var interval = 4; 
var bilderurl = new Array("_assets/_img/Picture1.jpg", "_assets/_img/Picture2.jpg", "_assets/_img/Picture3.jpg", "_assets/_img/Picture4.jpg");
var bilder = new Array();
let element = document.getElementById("bg-image-de-de");
for (i = 0; i < bilderurl.length; i++)
{
     bilder[i] = new Image;
     bilder[i].src = bilderurl[i];
}
i = 0;

function changebg()
{
     i++;
     if (i == bilderurl.length) i = 0; 
     element.style.backgroundImage = "url(" + bilderurl[i] + ")";
}
window.setInterval("changebg()", 1000 * interval);


function imageOne() {
    element.style.backgroundImage = "url(_assets/_img/Picture1.jpg)";
    element = null; 
};

function imageTwo() {
    element.style.backgroundImage = "url(_assets/_img/Picture2.jpg)";
    element = null; 
};

function imageThree() {
    element.style.backgroundImage = "url(_assets/_img/Picture3.jpg)";
    element = null;
};

function imageFour() {
    element.style.backgroundImage = "url(_assets/_img/Picture4.jpg)";
    element = null;
};

function backToChangeBG() {
    element = document.getElementById("bg-image-de-de");
};

Please help me, it really should be possible. Thankx in previous.
Yours,
Peter