GithubHelp home page GithubHelp logo

mdn / dom-examples Goto Github PK

View Code? Open in Web Editor NEW
3.2K 55.0 1.8K 132.61 MB

Code examples that accompany various MDN DOM and Web API documentation pages

Home Page: https://developer.mozilla.org/en-US/docs/Web/API

License: Creative Commons Zero v1.0 Universal

HTML 36.06% JavaScript 57.60% CSS 6.20% PHP 0.14%
matchmedia demo drag-drop dom-manipulation pointer-lock mdn-docs touch-events pointer-events channel-messaging javascript

dom-examples's Introduction

dom-examples

Code examples that accompany various MDN DOM and Web API documentation pages.

Note

You can include an example directly in MDN pages using {{EmbedLiveSample()}} macros or regular Markdown code blocks. These methods are simpler to maintain as the code lives beside the rest of the content. Only add examples to this repository if your example doesn't easily run on MDN pages for technical or security reasons.

Repository contents

Contribute to MDN Web Docs

You can contribute to MDN Web Docs and be a part of our community through content contributions, engineering, or translation work. The MDN Web Docs project welcomes contributions from everyone who shares our goals and wants to contribute constructively and respectfully within our community.

To find out how to get started, see the CONTRIBUTING.md document in this repository. By participating in and contributing to our projects and discussions, you acknowledge that you have read and agree to our Code of Conduct.

Get in touch

You can communicate with the MDN Web Docs team and community using the communication channels.

dom-examples's People

Contributors

a2sheppy avatar afbarstow avatar anhr avatar bsmth avatar captainbrosset avatar chrisdavidmills avatar clemens-tolboom avatar darpankumar avatar dimshik100 avatar dipikabh avatar duzun avatar elchi3 avatar greggman avatar juliandescottes avatar ksm2 avatar lordloh avatar mozilla-github-standards avatar mrbrain295 avatar mrxcray avatar onkarruikar avatar phewphewb avatar poshaughnessy avatar prajwalborkar avatar rumyra avatar simonsiefke avatar skbhardwaj avatar sole avatar teoli2003 avatar upsuper avatar wbamberg 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

dom-examples's Issues

[Web Crypto] Add links to functions.

See #39 (review) - in the descriptions for the Web Crypto examples, we should link to the individual function pages.

Tasks

Error not handled properly in offline video player example fetch call?

In this demo, the error is not handled properly whenever there is an error in the fetch call i.e 404 video is not available then also it says video ready to play PFA the screenshot in which the api return 404 but it says the video is ready to play. I know it is the default behaviour of fetch API it calls reject only if the service is not available but we need to handle this scenario in our code.
URl for the demo file
https://github.com/mdn/dom-examples/blob/master/abort-api/index.html

Screenshot 2020-03-07 at 3 26 37 PM

Restore commit log from mdn/web-speech-api and mdn/webgl-examples

It seems (never tried) possible to keep the commits according anwers in https://stackoverflow.com/questions/17371150/moving-git-repository-content-to-another-repository-preserving-history

It only required to prepare https://github.com/mdn/web-speech-api moving the tree into a subdirectory /web-speech-api beforehand.

Hope you can redo this.
@schalkneethling according to https://github.com/mdn/dom-examples/commits/master/web-speech-api

pixel-manipulation in bottom area

I was reading the tutorial assigned to pixel-manipulation/color-picker and it's not working as expected in Edge(100.0.1185.44) and Chrome(100.0.4896.88)

image

I found out that when you hover the mouse in the far top of the canvas, it shows y=33, but when you hover down to the bottom part, it shows y=259. This situation makes that the bottom part of the image can't be picked.

Notification not working on Windows 10 Action Center

In Windows 10, when the notification closes, it is pushed to Windows 10's action center. Clicking on the notification action center (after the notification at the bottom has closed) directs to the root URL, not the URL that dispatched the notification.

For example, the URL that dispatched the notification might be https://mdn.github.io/to-do-notifications/ . However, clicking on the notification that made it into the Action Center will direct to https://mdn.github.io (along with an error message).

image

CODE_OF_CONDUCT.md file missing

As of January 1 2019, Mozilla requires that all GitHub projects include this CODE_OF_CONDUCT.md file in the project root. The file has two parts:

  1. Required Text - All text under the headings Community Participation Guidelines and How to Report, are required, and should not be altered.
  2. Optional Text - The Project Specific Etiquette heading provides a space to speak more specifically about ways people can work effectively and inclusively together. Some examples of those can be found on the Firefox Debugger project, and Common Voice. (The optional part is commented out in the raw template file, and will not be visible until you modify and uncomment that part.)

If you have any questions about this file, or Code of Conduct policies and procedures, please see Mozilla-GitHub-Standards or email [email protected].

(Message COC001)

performance-apis - Using_the_Resource_Timing_API.html

https://github.com/mdn/dom-examples/blob/master/performance-apis/Using_the_Resource_Timing_API.html#L139

// Secure connection time
t = (resources[i].secureConnectionStart > 0) ? "0" : (resources[i].connectEnd - resources[i].secureConnectionStart);

shouldn't the if-else be the other way around?

t = (resources[i].secureConnectionStart > 0) ? (resources[i].connectEnd - resources[i].secureConnectionStart) : "0";

the last 3 t definitions in that function also need fixing.

Server Sent Events.

Hi,
when running the demo from server sent events I removed the while(1){ ... loop in the php file so it should only run once.

However the web page still returned data every few seconds.

Looking at the spec for event listener and looking at your code there doesn't seem to be any setting for only pushing a message every 10 seconds, or 30 seconds etc.

is it possible to adjust the frequency of the message being sent and if so how do you stop the message getting pushed / pulled from / to the client as it almost seems as though the client is making the request, not the server pushing the information. It's the only thing that makes sense to me to explain how the code continues to send messages if there is no while(1) loop in it.

SSE example does not work in Firefox.

I have set this example up on my localhost with nginx running (I have made the change from the Readme.md file) and it runs fine in Chromium but nothing happens in Firefox, no error messages just the button. I have tried it in v60 and the nightly build v62 with the same result.

Any ideas?

Tim

Is async required to make it work?

const` shareData = {
    title: 'MDN',
    text: 'Learn web development on MDN!',
    url: 'https://developer.mozilla.org'
  }

  const btn = document.querySelector('button');
  const resultPara = document.querySelector('.result');

  // Share must be triggered by "user activation"
  btn.addEventListener('click', async () => {
    try {
      await navigator.share(shareData)
      resultPara.textContent = 'MDN shared successfully'
    } catch(err) {
      resultPara.textContent = 'Error: ' + err
    }
  });

Is async function required?

Feature request: use of tags/additionalData in AES-GCM example.

In https://github.com/mdn/dom-examples/blob/master/web-crypto/encrypt-decrypt/aes-gcm.js it would be very nice to see examples of using the tags and additionalData parameters in encryption and decryption. In most GCM documentation I read, including MDN's there's ambiguity about how the authentication will be performed at an implementation level. I'm not perfectly sure yet what checks AES-GCM will perform in the Web Crypto implementation and what the calling code must do.

If maintainers are interested, I can maybe research further and submit a PR.

Chrome console error using default demo

Example: service-worker/simple-service-worker

I tried the demo and got the following error after couple of refreshes:

The service worker navigation preload request was cancelled before 'preloadResponse' settled. If you intend to use 'preloadResponse', use waitUntil() or respondWith() to wait for the promise to settle.

and as second error:

Uncaught (in promise) DOMException: The service worker navigation preload request was cancelled before 'preloadResponse' settled. If you intend to use 'preloadResponse', use waitUntil() or respondWith() to wait for the promise to settle.

after I watched the github demo I saw the same problem. How could this be resolved?

Improper Distance Calculation in Zoom Event

https://github.com/mdn/dom-examples/blob/master/pointerevents/Pinch_zoom_gestures.html

Line 79 of this script should be:
var curDiff = Math.sqrt(Math.pow(evCache[1].clientX - evCache[0].clientX, 2) + Math.pow(evCache[1].clientY - evCache[0].clientY, 2));

Currently line 79 is only calculating the difference between the X coordinates of the touches, but it should actually be measuring the distance between the two points. In the case of the difference of the X coordinates not changing or even decreasing, but the overall distance between the two touches is increasing then the current line 79 would not register a zoom out, but a zoom in. The line written above prevents such confusion.

MediaRecorder example not working on Download Audio

https://github.com/mdn/dom-examples/tree/master/media/web-dictaphone

Example here was not working when click download recorded audio.

My Browser : Chrome 103
OS: Mac OS 12.3.1

I guess the root cause is
https://github.com/mdn/dom-examples/blob/master/media/web-dictaphone/scripts/app.js#L80

it specific type to ogg but in fact it was webm format .

for prove that, i have download the file and rename the extension to webm from ogg manually . It would working perfectly

dom-examples/server-sent-events/sse.php is a mac alias file

Can you commit an actual text file please? It looks like you committed an alias by accident.

$ file sse.php
sse.php: MacOS Alias file
$ cat -vet sse.php
book^@^@^@^@mark^@^@^@^@8^@^@^@8^@^@^@M-X^B^@^@^@^@^D^P^@^@^@^@rs/cM-TEM-"M-uM-xNM-?A^@^@^@^@t/do^D^B^@^@^D^@^@^@^C^C^@^@^@^D^@^@^L^@^@^@^A^A^@^@Applications^D^@^@^@^A^A^@^@MAMP^F^@^@^@^A^A^@^@htdocs^@^@^R^@^@^@^A^A^@^@server-sent-events^@^@^G^@^@^@^A^A^@^@sse.php^@^T^@^@^@^A^F^@^@^P^@^@^@$^@^@^@0^@^@^@@^@^@^@\^@^@^@^H^@^@^@^D^C^@^@G^@^@^@^@^@^@^@^H^@^@^@^D^C^@^@[^MM-^R^@^@^@^@^@^H^@^@^@^D^C^@^@N)M-^R^@^@^@^@^@^H^@^@^@^D^C^@^@^Q^BM-^S^@^@^@^@^@^H^@^@^@^D^C^@^@^S^BM-^S^@^@^@^@^@^T^@^@^@^A^F^@^@M-^H^@^@^@M-^X^@^@^@M-(^@^@^@M-8^@^@^@M-H^@^@^@^H^@^@^@^@^D^@^@AM->M-IM-nM-"^@^@^@^X^@^@^@^A^B^@^@^A^@^@^@^@^@^@^@^_^B^@^@^@^@^@^@^_^B^@^@^@^@^@^@^@^@^@^@^A^E^@^@^H^@^@^@^A^I^@^@file:///^L^@^@^@^A^A^@^@Macintosh HD^H^@^@^@^D^C^@^@^@^@^@-t^@^@^@^H^@^@^@^@^D^@^@AM->&eM-}^@^@^@$^@^@^@^A^A^@^@DEA4743C-05AB-3BD2-8DE4-6F6C2AE614ED^X^@^@^@^A^B^@^@M-^A^@^@^@^A^@^@^@M-o^S^@^@^A^@^@^@M-o^S^@^@^A^@^@^@^A^@^@^@^A^A^@^@/^@^@^@3^@^@^@^A^B^@^@dnib^@^@^@^@^A^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^@^C^@^@^@^@^@^@^@php????^@^@^@^@^@^@^@^@^@M-L^@^@^@M-~M-^?M-^?M-^?^A^@^@^@^@^@^@^@^P^@^@^@^D^P^@^@l^@^@^@^@^@^@^@^E^P^@^@M-X^@^@^@^@^@^@^@^P^P^@^@^D^A^@^@^@^@^@^@@^P^@^@M-t^@^@^@^@^@^@^@^B ^@^@M-<^A^@^@^@^@^@^@^E ^@^@,^A^@^@^@^@^@^@^P ^@^@<^A^@^@^@^@^@^@^Q ^@^@p^A^@^@^@^@^@^@^R ^@^@P^A^@^@^@^@^@^@^S ^@^@`^A^@^@^@^@^@^@  ^@^@M-^\^A^@^@^@^@^@^@0 ^@^@$^A^@^@^@^@^@^@^AM-P^@^@$^A^@^@^@^@^@^@^PM-P^@^@^D^@^@^@^@^@^@^@^WM-p^@^@\^@^@^@^@^@^@^@"M-p^@^@M-H^A^@^@^@^@^@^@

Thanks!

Channel Messaging Examples are confusing at best.

I fail to see the point of channel-messaging-multimessage example...

Why is a new MessageChannel created every time, instead of simply passing the new messages in the MessagePort?
That makes the use of WindowObject.postMessage and MessagePort.postMessage really unclear: it sounds like either we can postMessage to only a single port, or that MessageChannel is a single-shot API, this later speculation being comforted by weird wording in MDN's Using channel messaging article:

Message channels on the other hand can provide a secure channel that a single data item can be sent down, from one browsing context to another, after which the channel is closed.

[emphasize mines]

That surely can be heard as channel messaging is "single-shot", and it actually have been at least by the asker of this question on stackoverflow.

So except if it is really a "single-shot" API and that I got it all wrong, (in this case all implementations would have got it wrong too) I think multimessage is actually a basic usage, that it should be rewritten to show a basic usage (i.e reusing the MessagePorts), and that what is currently called "basic" should be renamed single-message.

Rename main branch from master to main

This has been done on other MDN repositories, this one should also migrate. (note this could break some links on MDN, and would need some find and replace…)

indexeddb-examples/idbkeyrange: bad UX

The font sizes are huge. It is not easy to understand what's going on especially on smart phones:

simplescreenrecorder-2022-07-27_13.13.39.mp4

The radio buttons are smaller. In first glance it's not recognizable that we are supposed to select radio options and input ranges and hit the run square box.

Question - Is there a reason for not allowing a server to start from the root directory?

Is there a reason for having the project setup in such a way that starting a web server from the project root causes an error in registering the service worker? It seems like a simpler way would be to register the service worker at the root of the project. For example:

// app.js
navigator.serviceWorker.register('/sw-test/sw.js', { scope: '/sw-test/' })`

// could be changed to 
navigator.serviceWorker.register('/sw.js', { scope: '/' })

And then

// sw.js
return cache.addAll([
  '/sw-test/',
  '/sw-test/index.html',
  '/sw-test/style.css',
  '/sw-test/app.js',
  '/sw-test/image-list.js',
  '/sw-test/star-wars-logo.jpg',
  '/sw-test/gallery/bountyHunters.jpg',
  '/sw-test/gallery/myLittleVader.jpg',
  '/sw-test/gallery/snowTroopers.jpg'
]);

// could be changed to
return cache.addAll([
  '/',
  '/index.html',
  '/style.css',
  '/app.js',
  '/image-list.js',
  '/star-wars-logo.jpg',
  '/gallery/bountyHunters.jpg',
  '/gallery/myLittleVader.jpg',
  '/gallery/snowTroopers.jpg',
]);

With those changes I'm able to start a server from the project root directory and successfully register a service worker. But I don't know if maybe there's some implications to having it setup this way that I'm unaware of?

fetch-with-init-then-request sets Content-Type request header for GET

const myHeaders = new Headers();
myHeaders.append("Content-Type", "image/jpeg");
const myOptions = {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "default",
};
const myRequest = new Request("flowers.jpg");
fetch(myRequest, myOptions)

That example is setting a Content-Type request header for a GET request, which serves no real purpose since the request has no request body/payload.

I guess a simple fix would be to change the request header to an Accept header. But it seems like that wouldn’t be serving much real purpose either, since the request for flowers.jpg will without any Accept request header needed return that JPEG file as expected anyway.

A more real-world example would be a POST request with a JSON request payload/body and a Content-Type: application/json request header. But I don’t know if/how that would fit with how the set of examples here are served.

Regardless, I’m happy to help work on putting together another example that illustrates the same thing this one’s intended to illustrate.

But note also that whatever changes we make here, we will also need to update the example code at https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch#Example, which repeats the code from here.

Live Streaming?

Can this code be used for live streaming webrtc?

What changes would I need to make?

Thanks,

Ray

File-drag.html example not working

In fact it is not working every time. Sometimes the file are detected, and their name is printed, sometimes not. The drop event is always fired.

Here is an output, showing that it only worked once:

File(s) in drop zone
File-drag.html:32:7
File(s) dropped File-drag.html:39:7
Removing drag data File-drag.html:65:7
File(s) in drop zone
File-drag.html:32:7
File(s) dropped File-drag.html:39:7
Removing drag data File-drag.html:65:7
File(s) in drop zone
File-drag.html:32:7
File(s) dropped File-drag.html:39:7
Removing drag data File-drag.html:65:7
File(s) in drop zone
File-drag.html:32:7
File(s) dropped File-drag.html:39:7
... file[0].name = screen_fluoread.png File-drag.html:50:13
Removing drag data

Files from os to browser using firefox. Using chrome there is no issues

basic example returns "NetworkError when attempting to fetch resource."

I clone this projects and try run basic-fetch example, as my first test, Firefox returns "NetworkError when attempting to fetch resource." Similar error with Chromium : "Error: Failed to fetch"

I use Ubuntu 18.04 and firefox v97.0.2 and chromium v99

EDIT :
this example works fine (src (fr language) : https://www.digitalocean.com/community/tutorials/how-to-use-the-javascript-fetch-api-to-get-data-fr ):

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width">

    <title>Fetch basic example</title>

    <link rel="stylesheet" href="">
  </head>

  <body>
<h1>Authors</h1>
<ul id="authors"></ul>

  </body>
<script>
function createNode(element) {
    return document.createElement(element);
}

function append(parent, el) {
  return parent.appendChild(el);
}

const ul = document.getElementById('authors');
const url = 'https://randomuser.me/api/?results=10';

fetch(url)
.then((resp) => resp.json())
.then(function(data) {
  let authors = data.results;
  return authors.map(function(author) {
    let li = createNode('li');
    let img = createNode('img');
    let span = createNode('span');
    img.src = author.picture.medium;
    span.innerHTML = `${author.name.first} ${author.name.last}`;
    append(li, img);
    append(li, span);
    append(ul, li);
  })
})
.catch(function(error) {
  console.log(error);
});
</script>
</html>

Small grammar error on MediaDevicesInfo page

This is a definite nitpick, but I noticed it when I was on this page -- https://developer.mozilla.org/en-US/docs/Web/API/MediaDeviceInfo

There is a grammar error in the sentence : "Two devices have the same group identifier if they belong to the same physical device; for example a monitor with both a built-in camera and microphone."

After the semicolon, the is a sentence fragment. To fix this, you could make this semicolon a comma (or emdash, if you're feeling fancy!).

Hopefully this is helpful.
Thanks!
-jeff

Can't make dom-examples/screen-wake-lock-api work

Hi!
Thanks for providing this example.
https://github.com/mdn/dom-examples/tree/master/screen-wake-lock-api

Expected Behavior

Button 'turn wake lock on' is active.
Text in the box 'wake lock status' is 'Screen Wake Lock API supported 🎉'

Current Behavior

Button 'turn wake lock on' is inactive.
Text in the box 'wake lock status' is 'Wake lock is not supported by this browser.'

Possible Solution

Unknown to me

Steps to Reproduce

  1. Debian 9 server
  2. nginx/1.10.3
  3. add three files from repo to /var/www/html
  4. set up Nginx to serve index.html
  5. Chrome Version 91.0.4472.114 (Official Build) (x86_64)
  6. No https (might it be an issue?)

No errors shown, just button is inactive.
How can I make it work as it's working in your demo (https://mdn.github.io/dom-examples/screen-wake-lock-api/)?

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.