Auto pause/play on scroll Javascript autoplay video html5

I am attempting to create a video gallery on html5 with JS. I have it where you can scroll left to right between muted autoplay html5 videos and the videos will play/pause when scrolled onto/away from. This works fine.

Code Pen

The problem I am running into is when a user adjusts any of the html5 controls the autopause on scroll will no longer work. I am ok with turning off user video controls but I still need a way to toggle audio on/off. I added a button for it, but even when a user toggles the audio from the button, the on scroll pause/play JS stops working.

Hopefully, this makes sense. I appreciate any help!

the autoplay/pause Jquery I have:

$(window).scroll(function(){
  var scroll = $(this).scrollTop();
  scroll > 300 ? myvid.pause() : myvid.play()
}) ```

Java Instant.toEpochMilli() & Javascript Date.now() not in sync

I am trying to collect performance metrics for streaming data coming from a server process over websocket. The server is written in Java and the client is an Angular UI application.

The server stamps the sentAtTime on the message header just before it leaves the server using Java’s Instant.toEpochMilli(). The client records the receivedAtTime using Javascript’s Date.now() as soon as it picks the message up.

I then calculate time over the wire as NetworkLag = receivedAtTime - sentAtTime

Surprisingly the lag is negative sometimes upto -30 ms which is baffling me. I have checked that the maths isn’t wrong and I also get positive lag values. The only explanation I can think of is that the clocks on the server and client are somehow are not in sync. Have others seen something like this and what are the steps I could take to remediate the situation.

console.time vs window.performance.measure

Disclaimer: The following snippet can run slowly and/or lock up in most browsers due to a performance issue in the running library. However this illustrates an oddity that I can’t seem to resolve.

Question: Why in the below snippet is there such a significant difference in timing between console.time and window.performance.measure?

    import { unified } from "unified";
    import remarkParse from "remark-parse";
    import remarkRehype from "remark-rehype";
    import rehypeStringify from "rehype-stringify";

    const sourceMarkdown = `
    1${" ".repeat(75000)}2
    `;

    document.getElementById("source").innerHTML = sourceMarkdown;

    try {
      console.time("unified-pipeline");
      window.performance.mark("unified-pipeline");
      unified()
        .use(remarkParse)
        .use(remarkRehype)
        .use(rehypeStringify)
        .process(sourceMarkdown)
        .then((file) => {
          document.getElementById(
            "result"
          ).contentWindow.document.body.innerHTML = String(file);
          console.timeEnd("unified-pipeline");
          console.log(window.performance.measure("unified-pipeline"));
        });
    } catch (err) {
      document.getElementById("error").innerHTML = err;
    }

How to change the color of a text field in PDF?

I am making a pdf document using pdfrw. I can’t set text field color via javascript:

var textField1 = this.getField("textField1");

textField1.rect =[x1,y,x2,y2]            //working
textField1.value ='text'                 //working

textField1.textColor = color.green       //not working
textField1.fillColor = color.green       //not working

What could be the problem?

Deleting duplicates from an array of arrays

First question so I apologize for the format.
I was just curious to know as to how can you delete duplicates from an array that consists of arrays. Looking for the code in javascript

For e.g
[[ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 1, 1 ], [ 1, 2, 3 ]]

The result should be [[ 1, 1, 1] , [ 1, 2, 3]]

I do know how to remove duplicates from a simple array of values (strings or numbers)

Showing & Hiding Navbar Bug on Momentum-Based Touch Devices

I used the code below to add a simple navbar hiding and showing when a user scrolls up and down on a webpage.


const Navbar = () => {
  const [show, setShow] = useState(true);
  const [lastScrollY, setLastScrollY] = useState(0);

  const controlNavbar = () => {
    if (typeof window !== 'undefined') { 
      if (window.scrollY > lastScrollY) { // if scroll down hide the navbar
        setShow(false); 
      } else { // if scroll up show the navbar
        setShow(true);  
      }

      // remember current page location to use in the next move
      setLastScrollY(window.scrollY); 
    }
  };

  useEffect(() => {
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', controlNavbar);

      // cleanup function
      return () => {
        window.removeEventListener('scroll', controlNavbar);
      };
    }
  }, [lastScrollY]);

  return (
        <nav className={`active ${show && 'hidden'}`}>
        ....
        </nav>
  );
};

export default Navbar;

It works perfectly well on a desktop browser, but had a bug when testing it on my iphone (on both chrome and safari). On touch devices, when scrolling back to the top, there’s a little bounce animation where the scroll goes past the top of the page and then rubberbands back to the actual top of the page. This behaviour causes my event listener to register that the user scrolled down, and hides the navbar. Similarly, when the user scrolls to the bottom of the page, the rubberband effect causes my navbar event listener to register that the user scrolled up (when it bounces back) and shows the navbar. I hope I’m explaining this clearly (lol).

I’m trying to think of a solution, and the best one I came up with is to set the hiding and showing behaviour to work after a scroll of a certain number of pixels, so something like this.

if (window.scrollY > lastScrollY + 20){
   follow abovementioned logic...
}

But since the bounce amplitude is based on the user’s scroll speed, if the user scrolls really aggressively to the top of the window it definitely is going to bounce more than 20 pixels and therefore the same bug occurs.

I can’t seem to even find others facing this problem online, so any help would be appreciated!

Showing pagination component twice in one page not updating in sync

I have one pagination component that I am showing twice on the same page. When I click the pagination block to change pages the other block stays the same as its first render. I am wondering how can I keep them in sync?

It is important to mention the pagination components props are held in the parent component. One pagination block is in the parent and one is in the child of the parent but they both rely on the same props and trigger the same functions. How can I have them update in sync?

How to trigger a modal in the parent component based on the a button clicked from child component?

I have :

  • panelHeader.vue (child component)
  • index.vue (my main list view is the parent)

panelHeader.vue

<template>
    <v-row class="pl-5">
        <div class="panelHeader">
            <v-card elevation="0">
                <v-card-title>
                    <v-icon left x-large color="primary">{{ icon }}</v-icon>
                    <span class="font-weight-bold">{{ name }}</span>
                </v-card-title>

                <v-card-subtitle class="ml-1">{{ subTitle }}</v-card-subtitle>
            </v-card>

            <v-btn @click="btnClicked" v-if="name == 'Device Manager'" outlined class="blue--text mt-5 mr-8"> License Device </v-btn>
        </div>
    </v-row>
</template>
<script>
export default {
    props: {
        icon: String,
        name: String,
        subTitle: String
    },
    components: {},
    methods: {
        btnClicked() {
            this.$emit('btnClicked', true)
        }
    }
}
</script>

When clicked, I want to trigger a modal on my main index.vue

So I did that

<v-dialog @btnClicked="showModal" width="500px" class="d-flex justify-center">
    <v-card style="padding: 30px">
        <v-card-title class="red--text text--lighten-1 d-flex justify-center"> Delete </v-card-title>
        <v-card-text class="text-center">Are you sure you want to delete <strong> anythign </strong> ?</v-card-text>
        <v-card-actions class="d-flex justify-center">
            <v-btn small outlined color="darken-3 white--text" class="mx-2">No</v-btn>
            <v-btn small outlined @click="deleteConfirm()" class="mx-2 red--text">Yes</v-btn>
        </v-card-actions>
    </v-card>
</v-dialog>

Is this wrong ?

@btnClicked="showModal"

How to create only a starting tag of an HTML element using JS or jQuery?

I have a fixed wp sub-menu list that looks something like this:

<ul class="sub-menu" style="display:flex">
   <li class="open1col"><a>Treatment Trials</a></li>
   <li class=""><a>Alzheimer’s</a></li>
   <li class="close1col open2col"><a href="">Asthma</a></li>
   <li class=""><a>COVID-19 Treatment</a></li>
   <li class="close2col"><a>COPD</a></li>
</ul>

I’d like to wrap the first 3 and the last 2 elements into 2 <div class="sub-menu-col"> elements so that they make two different columns side-by-sidy.

This content is not editable by the way, i can only add classes to li tags.

I have tried jQuery like this:

var open1col='<div class="sub-menu-col">';
var close1col='</div><div class="sub-menu-col">';
var close2col='</div>'; 

    $( ".sub-menu li:first-child" ).before(open1col);
        
        $( ".sub-menu li:nth-child(3)" ).before(close1col);
            
        $( "sub-menu li:last-child" ).after(close2col); 
    });

but it immediately closed the div after the openning and the 3 <li> items fell outside.

How can I add only the opening and the closing tags as html strings?

Sentry erroring runtime with “Sentry Logger [error]: SentryError: SDK not enabled, will not capture event.”

I have Sentry setup which sort of works. I am trying to improve it and one of the issues is that I get his error rather randomly and I cannot catch what is happening to cause it.

I have Nest app, and call the forRoot method in AppModule:

const rootDir = __dirname || process.cwd();

@Module({
  imports: [
    SentryModule.forRoot({
      dsn: process.env.SENTRY_KEY,
      tracesSampleRate: 0.1,
      debug: true,
      normalizeDepth: 0, //Avoid normalizing contexts to achieve better explainability
      maxValueLength: 1024 * 10, //Increase maximum length of payload value to 10Kb
      integrations: [
        new RewriteFrames({
          root: rootDir,
        }) as any,
      ],
    }),
  ],
  controllers: [],
  providers: [],
})
export class AppModule {
  configure(consumer: MiddlewareConsumer): void {
    consumer.apply(Sentry.Handlers.requestHandler()).forRoutes({
      path: "*",
      method: RequestMethod.ALL,
    });
  }
}

The setup is using a middleware:

@Injectable({ scope: Scope.REQUEST })
export class SentryInterceptor implements NestInterceptor {
  constructor(private sentryService: SentryService) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<GenericRecord> {
    // start a child span for performance tracing
    const span = this.sentryService.startChild({ op: `route handler` });

    return next.handle().pipe(
      catchError((error) => {
        // capture the error, you can filter out some errors here
        Sentry.captureException(error, this.sentryService.span?.getTraceContext());

        // throw again the error
        return throwError(() => error);
      }),
      finalize(() => {
        span?.finish();
        this.sentryService.span?.finish();
      }),
    );
  }
}

My two main problems are:
1. I randomly get


Sentry Logger [error]: SentryError: SDK not enabled, will not capture event.
    at new SentryError (/node_modules/@sentry/src/error.ts:9:5)
    at NodeClient.BaseClient._processEvent (/node_modules/@sentry/src/baseclient.ts:543:34)
    at NodeClient.BaseClient._captureEvent (/node_modules/@sentry/src/baseclient.ts:504:17)
    at NodeClient.BaseClient.captureEvent (/node_modules/@sentry/src/baseclient.ts:163:12)
    at NodeClient.captureEvent (/node_modules/@sentry/src/client.ts:84:30)
    at Hub._invokeClient (/node_modules/@sentry/src/hub.ts:500:30)
    at Hub.captureEvent (/node_modules/@sentry/src/hub.ts:264:10)
    at Transaction.finish (/node_modules/src/transaction.ts:152:22)
    at Subscription.<anonymous> (/dist/apps/api/webpack:/apps/api/src/sentry/sentry.interceptor.ts:29:34)
    at Subscription.unsubscribe (/node_modules/rxjs/src/internal/Subscription.ts:92:22)

2. My errors get converted to 500 in Sentry

How can I validate the structure of HTTP Response in JavaScript? [closed]

How can I validate the structure of HTTP Reesponse in JavaScript?

Right now, the API is returning in the following structure:

{
  id:1,
  name: 'Bob',
  books: [1,2,3]
}

On successful API call from client side: I expect the response body to respect the above structure. How can I validate that the response indeed is returned in the agreed upon json format shown above. Values of each properties is irrelevant here.

For instance the following are all invalid:

  1. Invalid

    {
      id:1,
      full_name: 'Bob',
      books: [1,2,3]
    }
    
  2. Invalid

    {
      id:1,
      name: 'Bob'
    }
    
  3. Invalid

    {
      id:1,
      name: 'Bob'
    }
    

But the following are valid:

  1. Valid

    {
      id:1,
      name: 'Bob',
      books: [1,2,3]
    }
    
  2. Valid

    {
      id:1,
      name: null,
      books: []
    }
    
  3. Valid

    {
      id:null,
      name: null,
      books: null
    }
    

jest timeouts when calling a database query

I have a test file like this.

const { silBastan } = require("../database.js");
const axios = require('axios').default;

describe("authentication", () => {
  describe("when data schema is valid", () => {
    test("returns 201 response code if the user doesnt already exists", async () => {
      await silBastan();
      const response = await axios.post('http://localhost:8000/auth/register', {
        email: "my_email",
        password: "1234"
      });

      expect(response.status).toBe(201);
    });
  });
});

And silBastan is defined here like this

const pg = require("pg");

const client = new pg.Client();
async function silBastan() {
  return await client.query(`DELETE FROM account`);
}

Of course i made sure the server started and connected to the database before running the tests.
I wondered if there is something wrong with silBastan and tested it inside a express route handler like this

router.post('/register', async (req, res) => {
  const { email, password } = req.body;
  await silBastan();
  try {
    await db.createAccount(email, password);
    res.sendStatus(201);
  } catch (e) {
    res.status(400).json({ err: "Already exists" });
  }
});

and there was no timeout. And after this i returned another promise from silBastan like this:

async function silBastan() {
  // return await client.query(`DELETE FROM account`);
  return new Promise((resolve) => setTimeout(() => resolve(), 1000));
}

And again there is no timeout. I tried couple of other variations as well like these:

function silBastan() {
  return client.query(`DELETE FROM account`);
}
async function silBastan() {
  await client.query(`DELETE FROM account`);
}

Nothing worked i always get this message:

 thrown: "Exceeded timeout of 5000 ms for a test.
    Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."

I don’t think the problem is with the function because i would get the same behavior in the route handler too.

Re-render after drag and drop

If I drag and drop one element, then everything works fine, but if I add more elements, then everything does not work correctly.

I want to re-render all the elements after drag and drop. I don’t care about their order, as long as they are in the right columns.

Please tell me what I’m doing wrong.

codepen

const newTasks = document.querySelector('.trello__body--new')
const inProgress = document.querySelector('.trello__body--in-progress')
const completed = document.querySelector('.trello__body--completed')
const columns = document.querySelectorAll('.trello__body')

let currentDragItemID = null

const tasks = [
    { id: 1, text: 'Learn JS', status: 'new' },
    { id: 2, text: 'Learn React', status: 'new' },
    { id: 3, text: 'Learn TypeScript', status: 'new' },
    { id: 4, text: 'Learn Node.js', status: 'new' },
    { id: 5, text: 'Learn Next.js', status: 'new' },
]

const dragStart = event => {
    currentDragItemID = parseInt(event.target.getAttribute('task-id'))
    event.target.classList.add('trello__item--hide')
}

const dragEnd = event => (event.target.className = 'trello__item')

const columnDragOver = event => event.preventDefault()

const columnDragEnter = event => event.target.classList.add('trello__body--active')

const columnDragLeave = event => event.target.classList.remove('trello__body--active')

const columnDragDrop = event => {
    const status = event.target.getAttribute('status')

    const updatedTasks = tasks.map(task => {
        if (task.id === currentDragItemID) {
            return { ...task, status: status }
        }
        return task
    })

    event.target.classList.remove('trello__body--active')
    render(updatedTasks)
}

function render(array) {
    document.querySelectorAll('.trello__item').forEach(elem => elem.remove())

    array.forEach(item => {
        const task = document.createElement('div')
        task.className = 'trello__item'
        task.innerHTML = item.text
        task.setAttribute('task-id', item.id)
        task.draggable = true

        switch (item.status) {
            case 'new':
                newTasks.append(task)
                break
            case 'in-progress':
                inProgress.append(task)
                break
            case 'completed':
                completed.append(task)
                break
            default:
                break
        }

        task.addEventListener('dragstart', dragStart)
        task.addEventListener('dragend', dragEnd)
    })
}

render(tasks)

columns.forEach(item => {
    item.addEventListener('dragover', columnDragOver)
    item.addEventListener('dragenter', columnDragEnter)
    item.addEventListener('dragleave', columnDragLeave)
    item.addEventListener('drop', columnDragDrop)
})