Add a class to this div and remove it after a while in Javascript

Is there a way to do this in Javascript?
What I am trying to do is, when on click of a div then add a class “active” and remove it after a while. When adding active class to it’s parent div then I am going to play with some content within it’s div.

I am able to do it in jQuery but I am able to do exactly in Javascript.

This is the code I wrote in jQuery.

HTML

<div class="main-wrapper">
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
      <div class="content" onclick="showMessage()">
        Content div
      </div>
  </div>

jQuery

jQuery('.content').on("click", function () {
  jQuery(this).addClass("active");
    setTimeout(RemoveClass, 5000);
    });
    function RemoveClass() {
     jQuery(this).removeClass("active");
  }

This is in Javascript I am trying but it’s working only for one item.

 function showMessage(){
     document.querySelector(".content").classList.toggle("active");
   setTimeout(() => {
     document.querySelector(".content").classList.toggle("active");
   }, 600)
 }

need some easy solutions with short code in string compression in js

Here I have created a program for string compression, so for input chars = [“a”,”a”,”b”,”b”,”c”,”c”,”c”] we are getting output like 6 characters [“a”,”2″,”b”,”2″,”c”,”3″]. So I have created a program using the array approach, which is very lengthy and complex too. Is there any solution using the two-pointer or recursion approach to solve that program with very little code and efficiency? Can you please provide that with very short code? The code is given below.

var compress = function(chars) {
 if (!chars.length) {
    return 0;
  }
   let j = 0;                 
  let cur = chars[0];        
  let counter = 0;         
   for (let i = 0; i <= chars.length; i++) {
  
    if (chars[i] === cur) {
      counter++;              
    } else {
      // Otherwise, add the current character and count to the compressed array
      chars[j] = cur;        
      if (counter > 1) {
        const s = counter.toString();
        for (let k = 0; k < s.length; k++) {
          chars[++j] = s[k];  
        }
      }
      j++;                  
      cur = chars[i];      
      counter = 1;           
    }
   }
   return j
};
console.log(compress ('aaaabbc'))//a4b2c

I keep getting a console error of “Uncaught SyntaxError: Unexpected end of input”. In javascript [closed]

I’m trying to create a function where you input a list of words as a arugment and the function returns only the words that are a Palindrome. Side note a palindrome is a word, phrase, or sequence that reads the same backward as forward, for example EYE. Here is the code I have so far

> function aListOfPalindromeWords (str){
> 
> 
> const words = "a aa aaa aah aahed aahing aah saal aalii aaliis aals aam";
> 
> const myWords = words.split(" ");
> var reversedStr = "";
> 
> for (let i = 0; i < myWords.length; i++){
> for (j = myWords[i].length -1; i >=0; i--){
> reversedStr += myWords[i];
> 
>  {
> if (reversedStr === myWords[i]);
>    {
>  return myWord[i];
> 
>  }
> }
> }

I keep getting a console error of =”Uncaught SyntaxError: Unexpected end of input.

I tried to do a nested for loop to go iterate through the list of words and return the ones that are palindromes.

Content Security Policy – external affiliate links + Google Adsense

I’m currently working on a website/blog project, using HTML, CSS and JavaScript only.
I’m also using Google Adsense (inline ads + letting google place ads automatically) and affiliate links (from 1 source only).

When running a Lighthouse Report I get 100% in Best Practices, however, the message “Ensure CSP is effective against XSS attacks” got me scratching my head.

I’ve tried a few combinations to get the Content Security Policy (CSP) to work with Google Adsense but so far I’ve only been able to either completely block ads display or get error messages.

Code I used:

<meta http-equiv="Content-Security-Policy" content="script-src 'self' https://pagead2.googlesyndication.com; object-src 'self';">

I wonder if such Content Security Policy (CSP)is strictly necessary in my case.
So here is what I’m hoping to answer:

1- How can I implement the Content Security Policy (CSP) so it works with Google Adsense and how can I add the CSP for the affiliate program I use (assuming CSP is applicable in my case)?

Setting attributes by looping through object keys and values

I have an object that I loop through with Object.keys and for each of those keys I want to set attributes that are also defined in that Object as an array of a key.

My code loops through the objects, sets the attribute but the for loop only sets the last index as an attribute so that all elements have the same attribute.

const headerElements = [
  {
    pageLinksHeader: document.createElement("div"),
    class: "page-links-header",
  },
  {
    companyNameHeader: document.createElement("div"),
    class: "company-name-header",
  },
  {
    mainPageLink: document.createElement("a"),
    text: "example",
    link: "../../index.html",
  },
  {
    webPagesHeader: document.createElement("div"),
    class: "webpages-header",
  },
  {
    webPageTarieven: document.createElement("a"),
    webPageReserveren: document.createElement("a"),
    webPageContact: document.createElement("a"),
  },
  {
    webPagesLinks: [
      "../../tarieven.html",
      "../../reseveren.html",
      "./contact.html",
    ],
    webPagesText: ["Tarieven", "Reserveren", "Contact"],
  },
];

Object.keys(headerElements[4]).forEach((attr) => {
  for (let i = 0; i < 3; i++) {
    headerElements[4][attr].setAttribute(
      "href",
      headerElements[5].webPagesLinks[i]
    );
  }
});

I tried different loops like I a do while where I thought it would take the first index at least but all just set the last index (i=3) as the attribute.

As far as I understand the for loop, loops through at the first key and then the forEach function goes on and sets all element attributes to i=3 because the for loop does not exit or return anything when i=1.

I want to understand if I can make it loop through correctly or if it isn’t possible.

Why is my template not updated after data change in vue3

Here I have a vue project with vite and firebase.
The function for the data call is in a separate firebase.js file with lots of functions.

I call 2 function in Orders.vue that do:
1: get all the orders based of current email adress
2: get all the products based on that order

These are the 2 function that are being called.

async function getOrders() {
  const dateNow = new Date();
  const year = dateNow.getFullYear();
  const ordersRef = collection(
    db,
    "Users/" + auth.currentUser.email + "/orders/" + year + "/orders"
  );
  const ordersSnapshot = await getDocs(ordersRef);
  let IDS = {
    orders: [],
  };
  ordersSnapshot.forEach((doc) => {
    IDS.orders.push(doc.data());
    // getDoc()
    // console.log(doc.data());
  });
  return IDS.orders;
}

async function getOrdersProducts(ids) {
  // was working on this function
  let products = [];
  await ids.forEach((idList, inx) => {
    console.log(idList);
    products.push({
      items: [],
      order: inx,
      date: idList.dateOrdered
    })
    // console.log(idList.productsId);
    idList.productsId.forEach(async (id, index) => {
      if (id.includes("monitor")) {
        const productsRef = collection(db, "Products/electronics/monitors");
        const q = query(productsRef, where('title', '==', id))

        const productSnap = await getDocs(q)
        
        productSnap.forEach((prod) => {
          products[inx].items.push(prod.data())
        })
      } else if (id.includes('speaker')) {
        const productsRef = collection(db, "Products/electronics/speakers");
        const q = query(productsRef, where('title', '==', id))
        
        const productSnap = await getDocs(q);
        
        productSnap.forEach((prod) => {
          console.log(prod.data());
          products[inx].items.push(prod.data);
        })
      }
    });
  });
  // console.log(products);
  return products;
}

I call these functions inside Orders.vue which looks like this

<!-- page to get all the orders from this person -->
<script setup>
import { getAuth, onAuthStateChanged } from 'firebase/auth';
import { getOrders, getOrdersProducts } from '../../firebase'
import { onMounted, reactive, watch } from 'vue';
import { getStorage, getDownloadURL, ref } from 'firebase/storage';

const props = defineProps({
  user: String || null
})
const orders = reactive({
  list: []
})
const storage = getStorage()
const user = ref(false)

  getOrders().then((res) => {
      getOrdersProducts(res)
        .then( async (finalResult) => {
          console.log(finalResult);
          orders.list.push(finalResult)
        }).then(() => {
          // get the images and assign the correct image to the correct item
          console.log(orders.list[0]);

          for (let y = 0; y < orders.list.length; y++) {
            console.log(orders.list[0].items);
            for (let i = 0; i < orders.list[y].items.length; i++) {
              console.log('i = ' + i);
              getDownloadURL(ref(storage, 'products/' + orders.list[y].items[i].image))
                .then((url) => {
                    orders.list[y].items[i].image = url
                }).catch((err) => {
                    console.log(url);
                  console.log(err);
                })
            }


          }
        })
        .catch((err) => {
          console.log(err);
        })
    })
    .catch((err) => {
      console.log(err);
    })

// onMounted(() => {
//   if (props.user) {
//     asyncGetter()
//   }
// })

// asyncGetter()
</script>
<template>
  <div class="accountOrders">
    <h1>orders</h1>
    <!-- Was busy with rendering the order per user but did not have time for it yet -->
    <p v-if="orders.list">{{ orders.list }}</p>
    <div v-if="orders.list.length > 0" v-for="order in orders.list">
      <p>{{ order.date }}</p>
      <div v-if="order.items" v-for="product in order.items">
        <p>{{ product.title }}</p>
      </div>
    </div>
  </div>
</template>

<style lang="scss" scoped></style>

The problem is that my data does not render here:

  <div v-if="orders.list.length > 0" v-for="order in orders.list">
      <p>{{ order.date }}</p>
      <div v-if="order.items" v-for="product in order.items">
        <p>{{ product.title }}</p>
      </div>
    </div>

I tried to test if the second for loop was working and I found out that it doesn’t because orders.list[y].items.length returns 0

   for (let i = 0; i < orders.list[y].items.length; i++) {
              console.log('i = ' + i);
              getDownloadURL(ref(storage, 'products/' + orders.list[y].items[i].image))
                .then((url) => {
                    orders.list[y].items[i].image = url
                    console.log(url);
                }).catch((err) => {
                    
                  console.log(err);
                })
            }

p.s. I still have trouble fully understanding .then and vue proxy

How do i run Selenium(javascript) in Chrome extension development?

Developing a chrome extension where I collect information about the same product on different shopping sites. I am getting the price and name information of a product on Amazon, I want to learn the price information on other sites using Selenium.

const addProductImageTest = () =>{  
  const newProduct = {
  productImage : document.getElementById("landingImage").src,
  productPrice : document.getElementsByClassName("a-price aok-align-center")[0].children[0].innerText,
  productAvailability : document.getElementById("availability").children[0].innerText,
  productName : document.getElementById("productTitle").innerText,   
  };
    chrome.storage.sync.set({
    [product]: JSON.stringify([...allProducts, newProduct])
  });
 } 

The code above is the button click event that I use to get the data of the product on Amazon in contentScript.js.

const {By,Key,Builder,WebElement,JavascriptExecutor} = require("selenium-webdriver");
require("chromedriver");
const sleep = ms => new Promise(r => setTimeout(r, ms));

async function test_case_amazon(){  
    let chromeDriver = await new Builder().forBrowser("chrome").build();

    await chromeDriver.get("https://amazon.com.tr");
        await sleep(1000);
    await chromeDriver.findElement(By.xpath("//input[@name='field-keywords']")).sendKeys("Corsair iCUE 4000X RGB", Key.RETURN);
        await sleep(2000);
    await chromeDriver.findElement(By.id("sp-cc-rejectall-link")).click();
        await sleep(2000);
    await chromeDriver.findElement(By.xpath("//div[@data-component-type='s-search-result']")).click();
 let ege = chromeDriver.findElement(By.xpath("//span[@class ='a-price aok-align-center']/span")).getAttribute('innerText');

    await sleep(4000);       
    console.log(ege);
}
test_case_amazon();

This code is the part where I get the product’s data with Selenium. I want to use the Selenium code part in contentScript.js for different shopping sites, but I don’t know how to change the manifest.json file and import Selenium. Thanks in advance for help.

Nodejs event emitter implementation in Nextjs 13 or 14

How do i make nodejs event emitter object listen to emitted events globally within my nextjs13 application just like in normal nodejs environment?

I have a file post.js where a user creates a new post. I want to promptly return the response back to the user, emit an event where a handler function will listen to the emitted event in another file & perform some other tasks in the background like updating post tags count and then finally emitting an sse(server sent event) to client app to notify other connected clients.

First of all, i created a file known as eventEmitter.js where I created a single instance to be used within my application below;

    //eventEmitter.js

    import { EventEmitter } from 'node:events';

    const eventEmitter = new EventEmitter({captureRejections: true})

    export default eventEmitter;


    //post.js
  
    import eventEmitter from './eventEmitter'
  
    const insertPost = async() => {
       // perform db post insert
       
       //emit an event to be listened to perform a background task
       eventEmitter.emit("PING", "hello world");
       
       //return 
       return {id: 1, title: 'hello' }
   }
   

   insertPost()
   
   
    // this only works when the listener is in the same file with the emitted event
   eventEmitter.emit("PING", (ev) => {
        console.log(ev)
   });
   

    //listener.js
  
    import eventEmitter from './eventEmitter'
    // this doesn't work i.e the event is not captured in the file
   eventEmitter.emit("PING", (ev) => {
        console.log(ev)
   });
 //route.js
  export function GET(request: Request) {
       const responseStream = new TransformStream();
       const writer = responseStream.writable.getWriter();
       const encoder = new TextEncoder();
       //... other code
      
       // this doesn't work i.e the event is not captured in the file
      eventEmitter.emit("PING", (ev) => {
        console.log(ev)
     });
     
     // my streaming logic
}

My question is, how do i listen to the emitted event in other files like listener.js and route.js files other than just post.js file?

I want to listen to the emitted events globally within my nextjs app

The above works seamlessly in a nodejs environment and i expected it to work in nextjs environment too.

PS: I’m using nextjs App Router

Please help.

How to access data- via JQuery?

I want create buttons with index inside.

let battle_element = `<div class="Battle"> Battle: <button data-index="${battles_list[i].battle_index}">Battle</button></div>`;

$('#battles_list').append(battle_element);

$(".Battle").on("click", function() {
        console.log($(this).data('index'));
})

How to get this battle index?

Getting Fatal JavaScript invalid size error while converting my ciphertext data to base64 string

I am currently facing an issue with CryptoJS while working on a project that involves encrypting and decrypting 3D Model (gltf) data. The encryption part seems to be working fine, but when I try to convert the ciphertext to a Base64 string using CryptoJS.enc.Base64, I encounter a “Fatal JavaScript invalid size error” with the error code 169220804.

Here is the code,

// Encryption of gltf file
let plaintext = fs.readFileSync(inputFilePath, "base64");
let encryptedData = CryptoJS.AES.encrypt(plaintext, CryptoJS.enc.Utf8.parse(key.substring(0, 32)), { iv: iv });
let encryptedFinalData = ciphertext.ciphertext.toString(CryptoJS.enc.Base64); // Error on this line
fs.writeFileSync(encryptedFilePath, encryptedFinalData);
console.log(`Encrypted data saved to ${encryptedFilePath}`);

The above code is working fine for small size gltf file like 10Mb, getting below error for bigger file size like 100Mb

Here the Error,
Error I got

I don’t have deep understanding of terms like base64, utf-8 and AES encryption, so maybe I am doing something wrong here, Please help me solve this issue and also provide the best efficient ways of handling encryption/decryption tasks for gltf files

Here What I am Expecting:
Read the gltf file.
Encrypt the plaintext using AES encryption with a key (key) and an initialization vector (iv).
Convert the ciphertext to a Base64 string.
Save the encrypted data to a file (encryptedFilePath).

Creating a “external” timeline progress bar for video analysis

I am creating a small video analysis app, and I want to create a progress bar which is similar to the iphone functionality when cropping a video or image, there is a bar with vertical lines and you can then with touch scroll left or right and the settings change. I’m trying to make the same but with video, so when I scroll right it “goes forward” in the video timeline and when I go back it goes back. It’s the same as the video timeline on the iphone, but without the frames and instead vertical “lines” that extend horiztonally.

I’ve been trying to find any javascript libraries or existing work – but without any luck, so I’m hoping someone can help me get started here. I’m using video.js (does not need to be this), and then I’m targeting the progress bar and making an external version outside of the video, but I don’t know how to continue from there.

Here’s my current code, and images of what I’m trying to accomplish.

What I’m aiming for:
My goal

Iphone’s functionality:
Iphone editing options

<div class="col-4 ml-n4 mr-n4 pl-n4 container ">
    <div class="video-container" style="position: relative; overflow:hidden; width: 400px; height: 500px;">
    <div id="zoomContainer1" style="width: 100%; height: 100%;">
        <video
            id="series_1"
            class="video-js vjs-theme-sea vjs-nofull"
            preload="auto"
            width="400"
            height="500"
            poster=""
            controls
            muted
            loop
            autoplay
            data-setup='{
            "controls": false,
            "playbackRates": [0.3, 0.5, 1]
            }'
        >
            {% if videos %}
                <source src="{{ videos.0.url }}" type="video/mp4" />
            {% else %}
                <source src="" type="video/mp4" />
            {% endif %}
        </video>
    </div>
</div>


<!-- Custom Progress Bar for Player 1 -->
<div class="custom-progress-container">
  <div id="customProgressBar1" class="custom-progress-bar">
   <!-- Custom Timeline progress bar here -->
  </div>
</div>

/*************** PROGRESS BAR ***************/
.custom-progress-bar {
    background-color: #4d4d4d;
    height: 100%;
    width: 0%;
}

.custom-progress-container {
    flex-grow: 1;
    height: 10px; /* Adjust height as needed */
    background-color: #e0e0e0;
    display: flex;
    align-items: center;
}

Why all my elements are receiving the event listener changes from the last element iteration?

I am having a problem with applying a custom event listener to each element in my container.

HTML:

<div class='container'>
    <div class='button'>E</div>
    <div class='button'>X</div>
    <div class='button'>A</div>
    <div class='button'>M</div>
    <div class='button'>P</div>
    <div class='button'>LE</div>
</div>

Javascript simplification:

let containerChildren = Array.from(document.querySelector('.container').children);
let buttonArray = document.querySelectorAll('.button');

for (button of buttonArray) {
    classOnHovering(button);
}

function classOnHovering(button) {
    index = containerChildren.indexOf(button);
    animation = 'shine' + String(index);
    button.addEventListener('mouseenter', (e)=>{
        e.target.classList.add(animation);
    })
    button.addEventListener('mouseout', (e)=>{
        e.target.classList.remove(animation);
    })
    console.log(animation);
    //outputs: shine0; shine1; shine2; shine3; ...
}

I would expect that each element would toggle a custom class on hover.
As the “x” div being the second element, I would expect it to receive the class “Shine1” on mouseenter and it being removed on mouseout

Instead, if you hover while observing the elements class on dev tools, ALL of them are receiving the “Shine5” class. Why is it?
Shouldn’t the animation variable be passed as a value to the arrow function? Can someone explains why javascript behave this way?

(I hope this isn’t bad written, my first question here)

can anyone make home to go websites im flexible area

i am not be able to make it by html css and jsenter image description here

it is very hard to make ……………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………………..