Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

339
Views
create new class from HTMLDivElement and extend its prototype

I'm trying to extend HTMLDivElement prototype with a new method. However, I don't want to pollute the HTMLDivElement itself with my methods so I'm trying to create a new class that extends it.

export class ScrollableElement extends HTMLDivElement {
  scrollHorizontal(left: number) {
    this.scrollTo({ left, behavior: 'smooth' });
  }
}

I use this element for scrollable div's ref. However, whenever I try to call this method, I get error saying listRef.scrollHorizontal is not a function.

Is there any way to achieve this?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I've managed to do this using delegation as one comment below my question suggested.

Element class:

export class ScrollableElement {
  private _element: HTMLDivElement | null;

  constructor(element: HTMLDivElement | null) {
    this._element = element;
  }

  scrollHorizontal(left: number) {
    this._element?.scrollTo({ left, behavior: 'smooth' });
  }
}

Ref assignment to div:

const [scrollableEl, setScrollableEl] = useState<ScrollableElement | null>(null);

return <div ref={ref => setScrollableEl(new ScrollableElement(ref))} />

function scroll() {
  scrollableEl?.scrollHorizontal(100);
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!