GithubHelp home page GithubHelp logo

phuocng / html-dom Goto Github PK

View Code? Open in Web Editor NEW
6.5K 98.0 459.0 7.11 MB

Common tasks of managing HTML DOM with vanilla JavaScript. Give me 1 ⭐if it’s useful.

Home Page: https://phuoc.ng/collection/html-dom

License: MIT License

MDX 100.00%
dom document-object-model html dom-api typescript javascript dom-manipulation

html-dom's Introduction

HTML DOM

Story

Web development goes very fast. I still remember the moments when starting to use jQuery, Prototype, script.aculo.us, Zepto and many more.

Nowadays, even if our application is powered by modern tools such as Angular, Vue, React, Svelte, .etc, we have to deal with DOM. The frameworks encapsulate and hide the DOM management directly, but still give us a door to work with DOM via ref, event handlers.

If you develop or use a web component in any framework, you have to work with DOM at a certain level.

Knowing the browser DOM APIs and how to use them play an important role in web development. A website introducing the APIs, well-known problems, most popular questions could be very useful.

Features

  • No external library. Only native browsers' APIs
  • Small and easy to understand examples
  • Live demos
  • Many tips and good practices included
  • Many real use cases
  • Work with the modern browsers. Try to support Internet Explorer

About

This project is developed by Nguyen Huu Phuoc. I love building products and sharing knowledge.

Be my friend on

html-dom's People

Contributors

achilles1515 avatar aldi avatar dependabot[bot] avatar elkarouani avatar eran-nussbaum avatar franboud avatar jmidtlyng avatar kensan73 avatar konrud avatar krastand avatar llevequeblup avatar melsumner avatar millette avatar motss avatar neos21 avatar nsaicharan avatar nullcano avatar p45qu10u avatar phuocng avatar rzmk avatar simonw avatar sixeight avatar sotayamashita avatar souporserious avatar surajhell88 avatar tlthiem avatar welenofsky avatar wuzhengyan2015 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

html-dom's Issues

fix : syntax problem

In the file client\posts\distinguish-between-left-and-right-mouse-clicks\index.tsx , Line 22, nested use of ** ` **, resulting in run error ;

Old design

I was wondering which commit the design was changed in? I tried looking but I couldn't find it.

I miss this old design (but with the search box), and I wanted to run it locally.
image

Add: "Run code on window load"

I didn't see something like: "Run code on window load":

window.addEventListener('load', funtion () { ... });

if it is not there, probably it is a good idea to add it.

Thanks.

Support for colspan

I tried to implement the code on table with colspan attribute in one or more th in thead and it mixes all the table.
When drag, move and drop one or more columns by using a specific header cell, all the the columns that are under this cell should be moved, not just the first one.
This is a screenshot of the result, I am describing:
image
Any way to fix this?

"Execute code when the document is ready" is too naive

The current snippet is:

document.addEventListener('DOMContentLoaded', function(){
    ...
});

This works only if the user script is executed before the DOMContentLoaded event is fired. Proper solution should first check the current document.readyState and then either execute the callback immediately or subscribe to the event.

Copy to clipboard has accessibility implications

Hey, it's worth noting that https://htmldom.dev/copy-text-to-the-clipboard will have adverse effect for keyboard and screen reader users, as you're essentially moving the user's current focus away to the new textarea and then deleting it, leaving the focus in limbo/reset to the start of the page. It would be better perhaps to store the current document.activeElement first, and then setting focus() back to it afterwards.

Add return to scroll depth

Please add scroll return function to return the user to their previous scroll depth when navigating back.
On page unload: if depth is greater than 500: save scroll position in local storage or cookie.
var scrollPos = document.getElementById('someDiv').scrollTop(); If(scrollPos > 500){ localStorage.setItem("scrollPos", scrollPos); }

On page load: scroll to position.
if(localStorage.scrollPos){ document.getElementById('someDiv').scrollTop(localStorage.scrollPos); }

Problem when running the project

I clone the app on my computer, and after installing the dependencies by using 'npm install' and running the project by using 'npm run dev-server', i end up with the logs above :

html-dom@ dev-server C:\laragon\www\github-projects\html-dom
npm run copy && webpack-dev-server

html-dom@ copy C:\laragon\www\github-projects\html-dom
npm run copy:public && npm run copy:demo

html-dom@ copy:public C:\laragon\www\github-projects\html-dom
rimraf dist && mkdir dist && cp -rf public/* dist

html-dom@ copy:demo C:\laragon\www\github-projects\html-dom
cp -rf demo dist && NODE_ENV=production postcss vendors/[email protected]/tailwind.css -o dist/demo/styles.css

'NODE_ENV' n’est pas reconnu en tant que commande interne
ou externe, un programme exécutable ou un fichier de commandes.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! html-dom@ copy:demo: cp -rf demo dist && NODE_ENV=production postcss vendors/[email protected]/tailwind.css -o dist/demo/styles.css
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the html-dom@ copy:demo script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\KDragon\AppData\Roaming\npm-cache_logs\2020-04-02T13_20_53_205Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! html-dom@ copy: npm run copy:public && npm run copy:demo
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the html-dom@ copy script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\KDragon\AppData\Roaming\npm-cache_logs\2020-04-02T13_20_53_307Z-debug.log
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! html-dom@ dev-server: npm run copy && webpack-dev-server
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the html-dom@ dev-server script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\KDragon\AppData\Roaming\npm-cache_logs\2020-04-02T13_20_53_435Z-debug.log

Is there any problem here because its said that the problem not in my npm ?

Scroll to top of page doesn't move focus

Might be worth noting that https://htmldom.dev/scroll-to-top-of-the-page only scrolls to top visually. Keyboard/screenreader focus will still remain where it was (meaning that if for instance a keyboard user activated a "scroll to top" control, the page would scroll, but focus would still be on that control - and then a subsequent TAB would move focus to the next focusable element after the "scroll to top" control - and scroll that one back into view). There's no clean solution other than setting focus() explicitly back to something at the top/start of the document.

Help needed for dragging table rows

Hi, I'm looking at https://htmldom.dev/drag-and-drop-table-row/ and notice that on larger tables that the whole table appears when dragging a row. I'm guessing this is the clone-table, but is it possible to prevent this as well as have the table auto-scroll up or down as the user moves the dragging row outside of the table top/bottom?

To see the problem - try using a larger table as found on https://jsfiddle.net/Abeeee/9vd853hj/20/ and drag say row 19 up or down

delete does not take effect when remove the event handler

in "Attach or detach an event handler”

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>Static Template</title>
    <style></style>
  </head>
  <body>
    <button id="btn1">onclick</button>
  </body>
  <script>
    function fn1() {
      alert(1);
    }
    const btn1 = document.getElementById("btn1");
    btn1.onclick = fn1;
    console.log(btn1);

    let res = delete btn1.onclick;
    console.log(res);

    console.log(btn1.onclick);
  </script>
</html>

Mobile support

I only tried the image zoom and splitter demos, but neither of these work on mobile, and probably won't work on tablets.

The whole project likely needs testing and optimization for touch input?

In many cases, this isn't going to be simple or elegant and will likely increase the complexity of some of these demos substantially, which might be harmful to the learning process for some, so there is that to consider.

Mobile support in some cases could be an additional section, so those who don't need it can skip it - and in some other cases, mobile support isn't really possible or intended, so it might be a good idea for every demo to indicate clearly (perhaps with icons) which device types it intends to support.

Error installing dependencies

On a fresh clone of the project I'm running into the following errors.

$ git clone [email protected]:1milligram/html-dom.git
$ cd html-dom
$ npm install
npm ERR! code ERESOLVE
npm ERR! ERESOLVE could not resolve
npm ERR!
npm ERR! While resolving: @1milligram/[email protected]
npm ERR! Found: [email protected]
npm ERR! node_modules/next
npm ERR!   next@"^11.1.2" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer next@"^12.0.0" from @1milligram/[email protected]
npm ERR! node_modules/@1milligram/design
npm ERR!   @1milligram/design@"^0.4.0" from the root project
npm ERR!
npm ERR! Conflicting peer dependency: [email protected]
npm ERR! node_modules/next
npm ERR!   peer next@"^12.0.0" from @1milligram/[email protected]
npm ERR!   node_modules/@1milligram/design
npm ERR!     @1milligram/design@"^0.4.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/joemasilotti/.npm/eresolve-report.txt for a full report.

npm ERR! A complete log of this run can be found in:
npm ERR!     /Users/joemasilotti/.npm/_logs/2022-08-17T20_54_51_772Z-debug-0.log

Rmarkdown datatables

Is there a way of applying the drag&drop function to the tables that created via DT::datatable() function in html formatted Rmarkdown reports?
Thanks in advance..

Wouldn't a table header separate from the draggable rows produce a cleaner javascript code?

Your instructions are so clear and pedagogical. I am currently in the middle of trying out your instruction (applying them to my code) and haven't quite reached the end yet. Thus, I don't know if my idea would be valuable at all, but here goes anyway.

A restructured markup like the following would probably tidy up js code:

<table>
    <thead>
        <tr>
            <th> ... </th>
            ....
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> .... </td>
            ....
        </tr>
    </tbody>
</table>

Instead of referencing rows from the entire table and then excluding the first row, only rows from the tbody will be referenced.

Thus, the first line of js code can be:

table_body = document.querySelector('#table tbody');

and then rows can be referenced using

table_body.querySelectorAll('tr').forEach....

making the next few lines (those that ignore the first row) unnecessary.

Please let me know if this makes sense or if it will complicate succeeding llines of code.

Error in article: Load a JavaScript file dynamically

const waterfall = function (promises) {
    return promises.reduce(
        function (p, c) {
            // Waiting for `p` completed
            return p.then(function () {
                // and then `c`
                **return c().then(function (result) {**
                    return true;
                });
            });
        },
        // The initial value passed to the reduce method
        Promise.resolve([])
    );
};

line 61 trong bài posts/load-a-javascript-file-dynamically.md có vẻ đang sai anh ơi, c là 1 Promise nên mình .then luôn ạ, mình đang gọi c như 1 hàm nên code báo lỗi

Filter or sort by difficulty

I found the advanced tips really fun. Maybe it's useful to add a way to filter for how hard it is to do something, or instead a way to sort by difficulty. This way people can answer "what basic things can I do with Vanilla JS" at a glance, or satisfy the curiosity of people like me.

Help need help with drag & drop of columns into tables

Hi Phuoc, I am not an expert programmer, I am an amateur and for a personal project I need to make a small modification to this code https://htmldom.dev/drag-and-drop-table-column/

the code works very well, I just need that moving the table columns is not done through the text, but by dragging an icon inside the TH something like that. Header name .

In other words, only if I hover over the icon and drag the icon can the column move as it does now, but if the text or any other element within the TH is dragged, it will not trigger the drag event.
Could you help me?
thanks

Help needed Drag and drop table column

Hi, can you help me. please? I use your approach for drag&drop columns in me table, but I need that user don't have opportunity to change the order of first and second columns. use can move all columns excluded first and second.

Return search results when searching by methods

This is a really cool resource! Thanks for building it. 👏

I think it would be helpful, when searching/filtering for tasks, to return results for specific methods. eg: If I typed in fetch or map or filter, showing the tasks that have those methods in them.

A similar project, Code To Go, does this and is very useful.

Do you also have sticky table columns feature or script?

Hi,

imagine a scenario where you need to show 3 or 4 columns freeze while scrolling a big chunk of column data. You can have a sticky header or sticky columns and it can stick to left or right or both.

It would be nice to have such an HTML dom script in vanilla javascript. There are a few on jquery but many, including me, are big fans of using pure JavaScript.

Let me know if this is possible to include in your arsenal.

Thanks,
Raj

Short click by row sticks row with the cursor too

Hi there!

Initially, moving the line is accompanied by its sticking to the cursor, but this is if the click is not released. Moreover, if the line is moved to another position, it is enough to release the click. BUT I gonna use short click by table row without moving it for some functions, but it sticks with my mouse until I repeat the click and I've the error in console like that - http://joxi.ru/12MZVMPF0w1kgA. According this situation other JS stops...

Can I fix it somehow?

Have somebody same situation ?

Add: scroll while dragging

First, thank you for such a wonderful site! I'm in the middle of making a drag and drop library and have been splitting up the architecture as I go along and thought it might be nice to have an example of scrolling the viewport while dragging. I have a React example here that I wouldn't mind converting to vanilla if you think it would make for a good example. Please let me know, I'd be happy to start a PR 🙂

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.