From 4ab365b110f2f1f2b736326b7059244a32115089 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:45:38 +0100 Subject: unslug de: move --- .../javascript/bausteine/ereignisse/index.html | 587 -------------------- files/de/learn/javascript/bausteine/index.html | 42 -- .../javascript/building_blocks/events/index.html | 587 ++++++++++++++++++++ .../de/learn/javascript/building_blocks/index.html | 42 ++ .../first_steps/a_first_splash/index.html | 597 +++++++++++++++++++++ .../javascript/first_steps/erster_blick/index.html | 597 --------------------- .../lustige_geschichten_generator/index.html | 139 ----- .../first_steps/silly_story_generator/index.html | 139 +++++ .../first_steps/was_ist_javascript/index.html | 339 ------------ .../first_steps/what_is_javascript/index.html | 339 ++++++++++++ 10 files changed, 1704 insertions(+), 1704 deletions(-) delete mode 100644 files/de/learn/javascript/bausteine/ereignisse/index.html delete mode 100644 files/de/learn/javascript/bausteine/index.html create mode 100644 files/de/learn/javascript/building_blocks/events/index.html create mode 100644 files/de/learn/javascript/building_blocks/index.html create mode 100644 files/de/learn/javascript/first_steps/a_first_splash/index.html delete mode 100644 files/de/learn/javascript/first_steps/erster_blick/index.html delete mode 100644 files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html create mode 100644 files/de/learn/javascript/first_steps/silly_story_generator/index.html delete mode 100644 files/de/learn/javascript/first_steps/was_ist_javascript/index.html create mode 100644 files/de/learn/javascript/first_steps/what_is_javascript/index.html (limited to 'files/de/learn/javascript') diff --git a/files/de/learn/javascript/bausteine/ereignisse/index.html b/files/de/learn/javascript/bausteine/ereignisse/index.html deleted file mode 100644 index c07922c124..0000000000 --- a/files/de/learn/javascript/bausteine/ereignisse/index.html +++ /dev/null @@ -1,587 +0,0 @@ ---- -title: Einleitung der Ereignissen -slug: Learn/JavaScript/Bausteine/Ereignisse -translation_of: Learn/JavaScript/Building_blocks/Events ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
- -

Events oder auch Ereignisse sind Vorfälle die im System ausgelöst werden können. Auf diese Events wird vom System aufmerksam gemacht und es ust  möglich, in irgendeiner Art und Weise darauf zu reagieren.
- Ein Beispiel: Ein Benutzer klickt einen Knopf auf der Website, woraufhin eine Box mit Infromationen eingeblendet wird.
- In diesem Artikel besprechen wir einige wichtige Konzepte rund um  die Events und deren Funktionsweise im Browser. Wir werden hierbei nicht auf jedes Detail eingehen und nur das bis zum jetzigen Wissensstandpunkt nötigste abdecken.

- - - - - - - - - - - - -
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps.
Objective:To understand the fundamental theory of events, how they work in browsers, and how events may differ in different programming environments.
- -

A series of fortunate events

- -

As mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and also provides a mechanism by which some kind of action can be automatically taken (that is, some code running) when the event occurs. For example in an airport when the runway is clear for a plane to take off, a signal is communicated to the pilot, and as a result, they commence piloting the plane.

- -

- -

In the case of the Web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the HTML document loaded in the current tab, or the entire browser window. There are a lot of different types of events that can occur, for example:

- - - -

You can gather from this (and from glancing at the MDN Event reference) that there are a lot of events that can be responded to.

- -

Each available event has an event handler, which is a block of code (usually a JavaScript function that you as a programmer create) that will be run when the event fires. When such a block of code is defined to be run in response to an event firing, we say we are registering an event handler. Note that event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.

- -
-

Note: Web events are not part of the core JavaScript language — they are defined as part of the APIs built into the browser.

-
- -

A simple example

- -

Let's look at a simple example to explain what we mean here. You've already seen events and event handlers used in many of the examples in this course already, but let's recap just to cement our knowledge. In the following example, we have a single {{htmlelement("button")}}, which when pressed, makes the background change to a random color:

- -
<button>Change color</button>
- - - -

The JavaScript looks like so:

- -
const btn = document.querySelector('button');
-
-function random(number) {
-  return Math.floor(Math.random() * (number+1));
-}
-
-btn.onclick = function() {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
- -

In this code, we store a reference to the button inside a constant called btn, using the {{domxref("Document.querySelector()")}} function. We also define a function that returns a random number. The third part of the code is the event handler. The btn constant points to a <button> element, and this type of object has a number of events that can fire on it, and therefore, event handlers available. We are listening for the click event firing, by setting the onclick event handler property to equal an anonymous function containing code that generates a random RGB color and sets the <body> background-color equal to it.

- -

This code is run whenever the click event fires on the <button> element, that is, whenever a user clicks on it.

- -

The example output is as follows:

- -

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

- -

It's not just web pages

- -

Another thing worth mentioning at this point is that events are not unique to JavaScript — most programming languages have some kind of event model, and the way the model works often differs from JavaScript's way. In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments.

- -

For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically — it doesn't sound that different, but the code is quite different, making use of functions like on() to register an event listener, and once() to register an event listener that unregisters after it has run once. The HTTP connect event docs provide a good example of use.

- -

As another example, you can also use JavaScript to build cross-browser add-ons — browser functionality enhancements — using a technology called WebExtensions. The event model is similar to the web events model, but a bit different — event listeners properties are camel-cased (such as onMessage rather than onmessage), and need to be combined with the addListener function. See the runtime.onMessage page for an example.

- -

You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments.

- -

Ways of using web events

- -

There are a number of ways in which you can add event listener code to web pages so that it will be run when the associated event fires. In this section, we review the various mechanisms and discuss which ones you should use.

- -

Event handler properties

- -

These are the properties that exist to contain event handler code that we have seen most frequently during the course. Returning to the above example:

- -
const btn = document.querySelector('button');
-
-btn.onclick = function() {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
- -

The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special type — when you set it to be equal to some code, that code is run when the event fires on the button.

- -

You could also set the handler property to be equal to a named function name (like we saw in Build your own function). The following would work just the same:

- -
const btn = document.querySelector('button');
-
-function bgChange() {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
-
-btn.onclick = bgChange;
- -

There are many different event handler properties available. Let's do an experiment.

- -

First of all, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing btn.onclick to the following different values in turn, and observing the results in the example:

- - - -

Some events are very general and available nearly anywhere (for example an onclick handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use onplay only on specific elements, such as {{htmlelement("video")}}).

- -

Inline event handlers — don't use these

- -

You might also see a pattern like this in your code:

- -
<button onclick="bgChange()">Press me</button>
-
- -
function bgChange() {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
- -
-

Note: You can find the full source code for this example on GitHub (also see it running live).

-
- -

The earliest method of registering event handlers found on the Web involved event handler HTML attributes (or inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

- -
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
- -

You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

- -

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.

- -

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

- -
const buttons = document.querySelectorAll('button');
-
-for (let i = 0; i < buttons.length; i++) {
-  buttons[i].onclick = bgChange;
-}
- -

Note that another option here would be to use the forEach() built-in method available on NodeList objects:

- -
buttons.forEach(function(button) {
-  button.onclick = bgChange;
-});
- -
-

Note: Separating your programming logic from your content also makes your site more friendly to search engines.

-
- -

addEventListener() and removeEventListener()

- -

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

- -
const btn = document.querySelector('button');
-
-function bgChange() {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-}
-
-btn.addEventListener('click', bgChange);
- -
-

Note: You can find the full source code for this example on GitHub (also see it running live).

-
- -

Inside the addEventListener() function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

- -
btn.addEventListener('click', function() {
-  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  document.body.style.backgroundColor = rndCol;
-});
- -

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

- -
btn.removeEventListener('click', bgChange);
- -

This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you have to do is add or remove event handlers as appropriate.

- -

Second, you can also register multiple handlers for the same listener. The following two handlers wouldn't both be applied:

- -
myElement.onclick = functionA;
-myElement.onclick = functionB;
- -

The second line overwrites the value of onclick set by the first line. This would work, however:

- -
myElement.addEventListener('click', functionA);
-myElement.addEventListener('click', functionB);
- -

Both functions would now run when the element is clicked.

- -

In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the addEventListener() and removeEventListener() reference pages.

- -

What mechanism should I use?

- -

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

- -

The other two are relatively interchangeable, at least for simple uses:

- - - -

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required. For example, you can call addEventListener('click', function() { ... }) on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:

- -
element.onclick = function1;
-element.onclick = function2;
-etc.
- -
-

Note: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example jQuery) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.

-
- -

Other event concepts

- -

In this section, we briefly cover some advanced concepts that are relevant to events. It is not important to understand these concepts fully at this point, but they might serve to explain some code patterns you'll likely come across from time to time.

- -

Event objects

- -

Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

- -
function bgChange(e) {
-  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
-  e.target.style.backgroundColor = rndCol;
-  console.log(e);
-}
-
-btn.addEventListener('click', bgChange);
- -
-

Note: You can find the full source code for this example on GitHub (also see it running live).

-
- -

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.

- -
-

Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to be consistent — with yourself, and with others if possible.

-
- -

e.target is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. In the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked:

- -
const divs = document.querySelectorAll('div');
-
-for (let i = 0; i < divs.length; i++) {
-  divs[i].onclick = function(e) {
-    e.target.style.backgroundColor = bgChange();
-  }
-}
- -

The output is as follows (try clicking around on it — have fun):

- - - -

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

- -

Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object; see the {{domxref("Event")}} object reference for a full list. Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The Media Recorder API, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding ondataavailable handler's event object has a data property available containing the recorded audio or video data to allow you to access it and do something with it.

- -

Preventing default behavior

- -

Sometimes, you'll come across a situation where you want to prevent an event from doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)

- -

The trouble comes when the user has not submitted the data correctly — as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.

- -

First, a simple HTML form that requires you to enter your first and last name:

- -
<form>
-  <div>
-    <label for="fname">First name: </label>
-    <input id="fname" type="text">
-  </div>
-  <div>
-    <label for="lname">Last name: </label>
-    <input id="lname" type="text">
-  </div>
-  <div>
-     <input id="submit" type="submit">
-  </div>
-</form>
-<p></p>
- - - -

Now some JavaScript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the preventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

- -
const form = document.querySelector('form');
-const fname = document.getElementById('fname');
-const lname = document.getElementById('lname');
-const para = document.querySelector('p');
-
-form.onsubmit = function(e) {
-  if (fname.value === '' || lname.value === '') {
-    e.preventDefault();
-    para.textContent = 'You need to fill in both names!';
-  }
-}
- -

Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is OK for example purposes. The output is as follows:

- -

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

- -
-

Note: for the full source code, see preventdefault-validation.html (also see it running live here.)

-
- -

Event bubbling and capture

- -

The final subject to cover here is something that you won't come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

- - - -

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

- -

This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:

- -
<button>Display video</button>
-
-<div class="hidden">
-  <video>
-    <source src="rabbit320.mp4" type="video/mp4">
-    <source src="rabbit320.webm" type="video/webm">
-    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
-  </video>
-</div>
- -

When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <div> from hidden to showing (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):

- -
btn.onclick = function() {
-  videoBox.setAttribute('class', 'showing');
-}
- -

We then add a couple more onclick event handlers — the first one to the <div> and the second one to the <video>. The idea is that when the area of the <div> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.

- -
videoBox.onclick = function() {
-  videoBox.setAttribute('class', 'hidden');
-};
-
-video.onclick = function() {
-  video.play();
-};
- -

But there's a problem — currently, when you click the video it starts to play, but it causes the <div> to also be hidden at the same time. This is because the video is inside the <div> — it is part of it — so clicking on the video actually runs both the above event handlers.

- -

Bubbling and capturing explained

- -

When an event is fired on an element that has parent elements (in this case, the {{htmlelement("video")}} has the {{htmlelement("div")}} as a parent), modern browsers run two different phases — the capturing phase and the bubbling phase.

- -

In the capturing phase:

- - - -

In the bubbling phase, the exact opposite occurs:

- - - -

- -

(Click on image for bigger diagram)

- -

In modern browsers, by default, all event handlers are registered for the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <video> element outwards to the <html> element. Along the way:

- - - -
-

Note: In cases where both types of event handlers are present, bubbling and capturing, the capturing phase will run first, followed by the bubbling phase.

-
- -

Fixing the problem with stopPropagation()

- -

This is annoying behavior, but there is a way to fix it! The standard Event object has a function available on it called stopPropagation() which, when invoked on a handler's event object, makes it so that first handler is run but the event doesn't bubble any further up the chain, so no more handlers will be run.

- -

We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:

- -
video.onclick = function(e) {
-  e.stopPropagation();
-  video.play();
-};
- -

You can try making a local copy of the show-video-box.html source code and fixing it yourself, or looking at the fixed result in show-video-box-fixed.html (also see the source code here).

- -
-

Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.

-
- -
-

Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true.

-
- -

Event delegation

- -

Bubbling also allows us to take advantage of event delegation — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember earlier that we said bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc.?

- -

A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>.

- -

This concept is explained further on David Walsh's blog, with multiple examples — see How JavaScript Event Delegation Works.

- -

Test your skills!

- -

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Events.

- -

Conclusion

- -

You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.

- -

Also, it is important to understand that the different contexts in which JavaScript is used have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.

- -

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

- -

See also

- - - -

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

- -

In this module

- - diff --git a/files/de/learn/javascript/bausteine/index.html b/files/de/learn/javascript/bausteine/index.html deleted file mode 100644 index 1c6fb8fc46..0000000000 --- a/files/de/learn/javascript/bausteine/index.html +++ /dev/null @@ -1,42 +0,0 @@ ---- -title: JavaScript Bausteine -slug: Learn/JavaScript/Bausteine -translation_of: Learn/JavaScript/Building_blocks ---- -
{{LearnSidebar}}
- -

In diesem Modul betrachten wir weiterhin JavaScripts Kernfunktionen. Wir betrachten verschiedene, häufig vorkommende Arten von Code Blöcken, wie zum Beispiel Fallunterscheidungen, Schleifen, Funktionen und Events. Diese hast du bereits im Laufe des Kurses gesehen, allerdings nur "nebenbei" -  jetzt behandeln wir sie explizit.

- -

Vorraussetzungen

- -

Bevor du mit diesem Modul anfängst, solltest du mit den Grundlagen von HTML und CSS vertraut sein und das vorherige Modul, Erste Schritte mit JavaScript, abgeschlossen haben.

- -
-

Hinweis: Falls du auf einem Computer/Tablet/anderem Gerät arbeitest, auf dem du keine Dateien erstellen kannst, kannst du die (meisten) Code Beispiele online, zum Beispiel mit JSBin oder Thimble, ausprobieren.

-
- -

Anleitungen

- -
-
Entscheidungen treffen --- Fallunterscheidungen
-
In allen Programmiersprachen muss Code Entscheidungen treffen und bei unterschiedlichen Eingaben entsprechend handeln. Falls zum Beispiel in einem Spiel der Spieler keine Leben mehr übrig hat, so hat er das Spiel verloren. In einer Wetter-App soll beispielsweise morgens ein Sonnenaufgang als Hintergrund gezeigt werden, nachts jedoch Mond und Sterne. In diesem Artikel betrachten wir Fallunterscheidungen und wie diese in JavaScript funktionieren.
-
Code wiederholen
-
Manchmal soll eine Aufgabe mehr als einmal ausgeführt werden, zum Beispiel wenn eine Liste an Namen durchsucht wird. Um solche Aufgaben zu erledigen, sind Schleifen eine gute Lösung. Im folgenden Artikel werden wir Schleifen in JavaScript genauer betrachten.
-
Funktionen -- Wiederverwendbare Codeblöcke
-
Ein essentielles Konzept in der Programmierung sind Funktionen. Funktionen erlauben es, Code, der eine bestimmte Aufgabe erfüllt, in einem eigenen Block zu definieren. Anschließend kann dieser Code über ein einzelnes, kurzes Kommando aufgerufen werden, anstatt den ganzen Code mehrere Male tippen zu müssen. In diesem Artikel erkunden wir die Konzepte hinter Funktionen wie die grundlegende Syntax oder wie diese aufgerufen werden und definieren die Begriffe Funktion, Sichtbereich (Scope) und Parameter.
-
Baue deine eigene Funktion
-
Nach dem der Großteil der grundlegenden Theorie im vorherigen Artikel thematisiert wurde, bietet dieser Artikel eine praktische Erfahrung. Hier bekommst du etwas Übung im Erstellen deiner eigenen Funktion. Außerdem werden wir einige weitere nützliche Details für das Arbeiten mit Funktionen behandeln. 
-
Rückgabewerte von Funktionen
-
Es gibt ein weiteres essentielles Konzept, dass wir in diesem Kurs behandeln werden, um unsere Betrachtung von Funktionne abzuschließen --- Rückgabewerte. Manche Funktionen geben keinen "sinnvollen" Wert zurück, andere schon. Es ist wichtig zu verstehen, was diese Werte sind, wie sie benutzt werden und wie du Funktionen schreibst, die sinnvolle Werte zurückgeben.
-
Einführung in Events
-
Events sind Aktionen oder Ereignisse die in dem System, in dem du programmierts, passieren. Das System weist dich auf diese hin, so dass du gegebenenfalls entsprechend reagieren kannst. Klickt ein Nutzer beispielsweise auf einen Button auf einer Webseite, so möchtest du vermutlich darauf reagieren, in dem du eine Aktion ausführst. In diesem Artikel behandeln wir einige wichtige Konzepte bezüglich Events und betrachten deren Funktionsweise in Browsern.
-
- -

Prüfungen

- -

Die folgenden Aufgaben werden dein Verständnis der in diesen Artikeln behandelten JavaScript Grundlagen prüfen. 

- -
-
Bildergalerie
-
Jetzt wo wir die grundlegenden Bausteine JavaScripts betrachtet haben, werden wir dein Wissen über Schleifen, Funktionen, Fallunterscheidungen und Events testen, indem wir eine JavaScript-basierte Bildergalerie entwickeln.
-
diff --git a/files/de/learn/javascript/building_blocks/events/index.html b/files/de/learn/javascript/building_blocks/events/index.html new file mode 100644 index 0000000000..c07922c124 --- /dev/null +++ b/files/de/learn/javascript/building_blocks/events/index.html @@ -0,0 +1,587 @@ +--- +title: Einleitung der Ereignissen +slug: Learn/JavaScript/Bausteine/Ereignisse +translation_of: Learn/JavaScript/Building_blocks/Events +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}
+ +

Events oder auch Ereignisse sind Vorfälle die im System ausgelöst werden können. Auf diese Events wird vom System aufmerksam gemacht und es ust  möglich, in irgendeiner Art und Weise darauf zu reagieren.
+ Ein Beispiel: Ein Benutzer klickt einen Knopf auf der Website, woraufhin eine Box mit Infromationen eingeblendet wird.
+ In diesem Artikel besprechen wir einige wichtige Konzepte rund um  die Events und deren Funktionsweise im Browser. Wir werden hierbei nicht auf jedes Detail eingehen und nur das bis zum jetzigen Wissensstandpunkt nötigste abdecken.

+ + + + + + + + + + + + +
Prerequisites:Basic computer literacy, a basic understanding of HTML and CSS, JavaScript first steps.
Objective:To understand the fundamental theory of events, how they work in browsers, and how events may differ in different programming environments.
+ +

A series of fortunate events

+ +

As mentioned above, events are actions or occurrences that happen in the system you are programming — the system produces (or "fires") a signal of some kind when an event occurs, and also provides a mechanism by which some kind of action can be automatically taken (that is, some code running) when the event occurs. For example in an airport when the runway is clear for a plane to take off, a signal is communicated to the pilot, and as a result, they commence piloting the plane.

+ +

+ +

In the case of the Web, events are fired inside the browser window, and tend to be attached to a specific item that resides in it — this might be a single element, set of elements, the HTML document loaded in the current tab, or the entire browser window. There are a lot of different types of events that can occur, for example:

+ + + +

You can gather from this (and from glancing at the MDN Event reference) that there are a lot of events that can be responded to.

+ +

Each available event has an event handler, which is a block of code (usually a JavaScript function that you as a programmer create) that will be run when the event fires. When such a block of code is defined to be run in response to an event firing, we say we are registering an event handler. Note that event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.

+ +
+

Note: Web events are not part of the core JavaScript language — they are defined as part of the APIs built into the browser.

+
+ +

A simple example

+ +

Let's look at a simple example to explain what we mean here. You've already seen events and event handlers used in many of the examples in this course already, but let's recap just to cement our knowledge. In the following example, we have a single {{htmlelement("button")}}, which when pressed, makes the background change to a random color:

+ +
<button>Change color</button>
+ + + +

The JavaScript looks like so:

+ +
const btn = document.querySelector('button');
+
+function random(number) {
+  return Math.floor(Math.random() * (number+1));
+}
+
+btn.onclick = function() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

In this code, we store a reference to the button inside a constant called btn, using the {{domxref("Document.querySelector()")}} function. We also define a function that returns a random number. The third part of the code is the event handler. The btn constant points to a <button> element, and this type of object has a number of events that can fire on it, and therefore, event handlers available. We are listening for the click event firing, by setting the onclick event handler property to equal an anonymous function containing code that generates a random RGB color and sets the <body> background-color equal to it.

+ +

This code is run whenever the click event fires on the <button> element, that is, whenever a user clicks on it.

+ +

The example output is as follows:

+ +

{{ EmbedLiveSample('A_simple_example', '100%', 200, "", "", "hide-codepen-jsfiddle") }}

+ +

It's not just web pages

+ +

Another thing worth mentioning at this point is that events are not unique to JavaScript — most programming languages have some kind of event model, and the way the model works often differs from JavaScript's way. In fact, the event model in JavaScript for web pages differs from the event model for JavaScript as it is used in other environments.

+ +

For example, Node.js is a very popular JavaScript runtime that enables developers to use JavaScript to build network and server-side applications. The Node.js event model relies on listeners to listen for events and emitters to emit events periodically — it doesn't sound that different, but the code is quite different, making use of functions like on() to register an event listener, and once() to register an event listener that unregisters after it has run once. The HTTP connect event docs provide a good example of use.

+ +

As another example, you can also use JavaScript to build cross-browser add-ons — browser functionality enhancements — using a technology called WebExtensions. The event model is similar to the web events model, but a bit different — event listeners properties are camel-cased (such as onMessage rather than onmessage), and need to be combined with the addListener function. See the runtime.onMessage page for an example.

+ +

You don't need to understand anything about other such environments at this stage in your learning; we just wanted to make it clear that events can differ in different programming environments.

+ +

Ways of using web events

+ +

There are a number of ways in which you can add event listener code to web pages so that it will be run when the associated event fires. In this section, we review the various mechanisms and discuss which ones you should use.

+ +

Event handler properties

+ +

These are the properties that exist to contain event handler code that we have seen most frequently during the course. Returning to the above example:

+ +
const btn = document.querySelector('button');
+
+btn.onclick = function() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +

The onclick property is the event handler property being used in this situation. It is essentially a property like any other available on the button (e.g. btn.textContent, or btn.style), but it is a special type — when you set it to be equal to some code, that code is run when the event fires on the button.

+ +

You could also set the handler property to be equal to a named function name (like we saw in Build your own function). The following would work just the same:

+ +
const btn = document.querySelector('button');
+
+function bgChange() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.onclick = bgChange;
+ +

There are many different event handler properties available. Let's do an experiment.

+ +

First of all, make a local copy of random-color-eventhandlerproperty.html, and open it in your browser. It's just a copy of the simple random color example we've been playing with already in this article. Now try changing btn.onclick to the following different values in turn, and observing the results in the example:

+ + + +

Some events are very general and available nearly anywhere (for example an onclick handler can be registered on nearly any element), whereas some are more specific and only useful in certain situations (for example it makes sense to use onplay only on specific elements, such as {{htmlelement("video")}}).

+ +

Inline event handlers — don't use these

+ +

You might also see a pattern like this in your code:

+ +
<button onclick="bgChange()">Press me</button>
+
+ +
function bgChange() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

The earliest method of registering event handlers found on the Web involved event handler HTML attributes (or inline event handlers) like the one shown above — the attribute value is literally the JavaScript code you want to run when the event occurs. The above example invokes a function defined inside a {{htmlelement("script")}} element on the same page, but you could also insert JavaScript directly inside the attribute, for example:

+ +
<button onclick="alert('Hello, this is my old-fashioned event handler!');">Press me</button>
+ +

You can find HTML attribute equivalents for many of the event handler properties; however, you shouldn't use these — they are considered bad practice. It might seem easy to use an event handler attribute if you are just doing something really quick, but they very quickly become unmanageable and inefficient.

+ +

For a start, it is not a good idea to mix up your HTML and your JavaScript, as it becomes hard to parse — keeping your JavaScript all in one place is better; if it is in a separate file you can apply it to multiple HTML documents.

+ +

Even in a single file, inline event handlers are not a good idea. One button is OK, but what if you had 100 buttons? You'd have to add 100 attributes to the file; it would very quickly turn into a maintenance nightmare. With JavaScript, you could easily add an event handler function to all the buttons on the page no matter how many there were, using something like this:

+ +
const buttons = document.querySelectorAll('button');
+
+for (let i = 0; i < buttons.length; i++) {
+  buttons[i].onclick = bgChange;
+}
+ +

Note that another option here would be to use the forEach() built-in method available on NodeList objects:

+ +
buttons.forEach(function(button) {
+  button.onclick = bgChange;
+});
+ +
+

Note: Separating your programming logic from your content also makes your site more friendly to search engines.

+
+ +

addEventListener() and removeEventListener()

+ +

The newest type of event mechanism is defined in the Document Object Model (DOM) Level 2 Events Specification, which provides browsers with a new function — addEventListener(). This functions in a similar way to the event handler properties, but the syntax is obviously different. We could rewrite our random color example to look like this:

+ +
const btn = document.querySelector('button');
+
+function bgChange() {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Inside the addEventListener() function, we specify two parameters — the name of the event we want to register this handler for, and the code that comprises the handler function we want to run in response to it. Note that it is perfectly appropriate to put all the code inside the addEventListener() function, in an anonymous function, like this:

+ +
btn.addEventListener('click', function() {
+  var rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  document.body.style.backgroundColor = rndCol;
+});
+ +

This mechanism has some advantages over the older mechanisms discussed earlier. For a start, there is a counterpart function, removeEventListener(), which removes a previously added listener. For example, this would remove the listener set in the first code block in this section:

+ +
btn.removeEventListener('click', bgChange);
+ +

This isn't significant for simple, small programs, but for larger, more complex programs it can improve efficiency to clean up old unused event handlers. Plus, for example, this allows you to have the same button performing different actions in different circumstances — all you have to do is add or remove event handlers as appropriate.

+ +

Second, you can also register multiple handlers for the same listener. The following two handlers wouldn't both be applied:

+ +
myElement.onclick = functionA;
+myElement.onclick = functionB;
+ +

The second line overwrites the value of onclick set by the first line. This would work, however:

+ +
myElement.addEventListener('click', functionA);
+myElement.addEventListener('click', functionB);
+ +

Both functions would now run when the element is clicked.

+ +

In addition, there are a number of other powerful features and options available with this event mechanism. These are a little out of scope for this article, but if you want to read up on them, have a look at the addEventListener() and removeEventListener() reference pages.

+ +

What mechanism should I use?

+ +

Of the three mechanisms, you definitely shouldn't use the HTML event handler attributes — these are outdated, and bad practice, as mentioned above.

+ +

The other two are relatively interchangeable, at least for simple uses:

+ + + +

The main advantages of the third mechanism are that you can remove event handler code if needed, using removeEventListener(), and you can add multiple listeners of the same type to elements if required. For example, you can call addEventListener('click', function() { ... }) on an element multiple times, with different functions specified in the second argument. This is impossible with event handler properties because any subsequent attempts to set a property will overwrite earlier ones, e.g.:

+ +
element.onclick = function1;
+element.onclick = function2;
+etc.
+ +
+

Note: If you are called upon to support browsers older than Internet Explorer 8 in your work, you may run into difficulties, as such ancient browsers use different event models from newer browsers. But never fear, most JavaScript libraries (for example jQuery) have built-in functions that abstract away cross-browser differences. Don't worry about this too much at this stage in your learning journey.

+
+ +

Other event concepts

+ +

In this section, we briefly cover some advanced concepts that are relevant to events. It is not important to understand these concepts fully at this point, but they might serve to explain some code patterns you'll likely come across from time to time.

+ +

Event objects

+ +

Sometimes inside an event handler function, you might see a parameter specified with a name such as event, evt, or simply e. This is called the event object, and it is automatically passed to event handlers to provide extra features and information. For example, let's rewrite our random color example again slightly:

+ +
function bgChange(e) {
+  const rndCol = 'rgb(' + random(255) + ',' + random(255) + ',' + random(255) + ')';
+  e.target.style.backgroundColor = rndCol;
+  console.log(e);
+}
+
+btn.addEventListener('click', bgChange);
+ +
+

Note: You can find the full source code for this example on GitHub (also see it running live).

+
+ +

Here you can see that we are including an event object, e, in the function, and in the function setting a background color style on e.target — which is the button itself. The target property of the event object is always a reference to the element that the event has just occurred upon. So in this example, we are setting a random background color on the button, not the page.

+ +
+

Note: You can use any name you like for the event object — you just need to choose a name that you can then use to reference it inside the event handler function. e/evt/event are most commonly used by developers because they are short and easy to remember. It's always good to be consistent — with yourself, and with others if possible.

+
+ +

e.target is incredibly useful when you want to set the same event handler on multiple elements and do something to all of them when an event occurs on them. You might, for example, have a set of 16 tiles that disappear when they are clicked on. It is useful to always be able to just set the thing to disappear as e.target, rather than having to select it in some more difficult way. In the following example (see useful-eventtarget.html for the full source code; also see it running live here), we create 16 {{htmlelement("div")}} elements using JavaScript. We then select all of them using {{domxref("document.querySelectorAll()")}}, then loop through each one, adding an onclick handler to each that makes it so that a random color is applied to each one when clicked:

+ +
const divs = document.querySelectorAll('div');
+
+for (let i = 0; i < divs.length; i++) {
+  divs[i].onclick = function(e) {
+    e.target.style.backgroundColor = bgChange();
+  }
+}
+ +

The output is as follows (try clicking around on it — have fun):

+ + + +

{{ EmbedLiveSample('Hidden_example', '100%', 400, "", "", "hide-codepen-jsfiddle") }}

+ +

Most event handlers you'll encounter just have a standard set of properties and functions (methods) available on the event object; see the {{domxref("Event")}} object reference for a full list. Some more advanced handlers, however, add specialist properties containing extra data that they need to function. The Media Recorder API, for example, has a dataavailable event, which fires when some audio or video has been recorded and is available for doing something with (for example saving it, or playing it back). The corresponding ondataavailable handler's event object has a data property available containing the recorded audio or video data to allow you to access it and do something with it.

+ +

Preventing default behavior

+ +

Sometimes, you'll come across a situation where you want to prevent an event from doing what it does by default. The most common example is that of a web form, for example, a custom registration form. When you fill in the details and press the submit button, the natural behavior is for the data to be submitted to a specified page on the server for processing, and the browser to be redirected to a "success message" page of some kind (or the same page, if another is not specified.)

+ +

The trouble comes when the user has not submitted the data correctly — as a developer, you want to prevent the submission to the server and give an error message saying what's wrong and what needs to be done to put things right. Some browsers support automatic form data validation features, but since many don't, you are advised to not rely on those and implement your own validation checks. Let's look at a simple example.

+ +

First, a simple HTML form that requires you to enter your first and last name:

+ +
<form>
+  <div>
+    <label for="fname">First name: </label>
+    <input id="fname" type="text">
+  </div>
+  <div>
+    <label for="lname">Last name: </label>
+    <input id="lname" type="text">
+  </div>
+  <div>
+     <input id="submit" type="submit">
+  </div>
+</form>
+<p></p>
+ + + +

Now some JavaScript — here we implement a very simple check inside an onsubmit event handler (the submit event is fired on a form when it is submitted) that tests whether the text fields are empty. If they are, we call the preventDefault() function on the event object — which stops the form submission — and then display an error message in the paragraph below our form to tell the user what's wrong:

+ +
const form = document.querySelector('form');
+const fname = document.getElementById('fname');
+const lname = document.getElementById('lname');
+const para = document.querySelector('p');
+
+form.onsubmit = function(e) {
+  if (fname.value === '' || lname.value === '') {
+    e.preventDefault();
+    para.textContent = 'You need to fill in both names!';
+  }
+}
+ +

Obviously, this is pretty weak form validation — it wouldn't stop the user validating the form with spaces or numbers entered into the fields, for example — but it is OK for example purposes. The output is as follows:

+ +

{{ EmbedLiveSample('Preventing_default_behavior', '100%', 140, "", "", "hide-codepen-jsfiddle") }}

+ +
+

Note: for the full source code, see preventdefault-validation.html (also see it running live here.)

+
+ +

Event bubbling and capture

+ +

The final subject to cover here is something that you won't come across often, but it can be a real pain if you don't understand it. Event bubbling and capture are two mechanisms that describe what happens when two handlers of the same event type are activated on one element. Let's look at an example to make this easier — open up the show-video-box.html example in a new tab (and the source code in another tab.) It is also available live below:

+ + + +

{{ EmbedLiveSample('Hidden_video_example', '100%', 500, "", "", "hide-codepen-jsfiddle") }}

+ +

This is a pretty simple example that shows and hides a {{htmlelement("div")}} with a {{htmlelement("video")}} element inside it:

+ +
<button>Display video</button>
+
+<div class="hidden">
+  <video>
+    <source src="rabbit320.mp4" type="video/mp4">
+    <source src="rabbit320.webm" type="video/webm">
+    <p>Your browser doesn't support HTML5 video. Here is a <a href="rabbit320.mp4">link to the video</a> instead.</p>
+  </video>
+</div>
+ +

When the {{htmlelement("button")}} is clicked, the video is displayed, by changing the class attribute on the <div> from hidden to showing (the example's CSS contains these two classes, which position the box off the screen and on the screen, respectively):

+ +
btn.onclick = function() {
+  videoBox.setAttribute('class', 'showing');
+}
+ +

We then add a couple more onclick event handlers — the first one to the <div> and the second one to the <video>. The idea is that when the area of the <div> outside the video is clicked, the box should be hidden again; when the video itself is clicked, the video should start to play.

+ +
videoBox.onclick = function() {
+  videoBox.setAttribute('class', 'hidden');
+};
+
+video.onclick = function() {
+  video.play();
+};
+ +

But there's a problem — currently, when you click the video it starts to play, but it causes the <div> to also be hidden at the same time. This is because the video is inside the <div> — it is part of it — so clicking on the video actually runs both the above event handlers.

+ +

Bubbling and capturing explained

+ +

When an event is fired on an element that has parent elements (in this case, the {{htmlelement("video")}} has the {{htmlelement("div")}} as a parent), modern browsers run two different phases — the capturing phase and the bubbling phase.

+ +

In the capturing phase:

+ + + +

In the bubbling phase, the exact opposite occurs:

+ + + +

+ +

(Click on image for bigger diagram)

+ +

In modern browsers, by default, all event handlers are registered for the bubbling phase. So in our current example, when you click the video, the click event bubbles from the <video> element outwards to the <html> element. Along the way:

+ + + +
+

Note: In cases where both types of event handlers are present, bubbling and capturing, the capturing phase will run first, followed by the bubbling phase.

+
+ +

Fixing the problem with stopPropagation()

+ +

This is annoying behavior, but there is a way to fix it! The standard Event object has a function available on it called stopPropagation() which, when invoked on a handler's event object, makes it so that first handler is run but the event doesn't bubble any further up the chain, so no more handlers will be run.

+ +

We can, therefore, fix our current problem by changing the second handler function in the previous code block to this:

+ +
video.onclick = function(e) {
+  e.stopPropagation();
+  video.play();
+};
+ +

You can try making a local copy of the show-video-box.html source code and fixing it yourself, or looking at the fixed result in show-video-box-fixed.html (also see the source code here).

+ +
+

Note: Why bother with both capturing and bubbling? Well, in the bad old days when browsers were much less cross-compatible than they are now, Netscape only used event capturing, and Internet Explorer used only event bubbling. When the W3C decided to try to standardize the behavior and reach a consensus, they ended up with this system that included both, which is the one modern browsers implemented.

+
+ +
+

Note: As mentioned above, by default all event handlers are registered in the bubbling phase, and this makes more sense most of the time. If you really want to register an event in the capturing phase instead, you can do so by registering your handler using addEventListener(), and setting the optional third property to true.

+
+ +

Event delegation

+ +

Bubbling also allows us to take advantage of event delegation — this concept relies on the fact that if you want some code to run when you click on any one of a large number of child elements, you can set the event listener on their parent and have events that happen on them bubble up to their parent rather than having to set the event listener on every child individually. Remember earlier that we said bubbling involves checking the element the event is fired on for an event handler first, then moving up to the element's parent, etc.?

+ +

A good example is a series of list items — if you want each one of them to pop up a message when clicked, you can set the click event listener on the parent <ul>, and events will bubble from the list items to the <ul>.

+ +

This concept is explained further on David Walsh's blog, with multiple examples — see How JavaScript Event Delegation Works.

+ +

Test your skills!

+ +

You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on — see Test your skills: Events.

+ +

Conclusion

+ +

You should now know all you need to know about web events at this early stage. As mentioned above, events are not really part of the core JavaScript — they are defined in browser Web APIs.

+ +

Also, it is important to understand that the different contexts in which JavaScript is used have different event models — from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development.

+ +

If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help.

+ +

See also

+ + + +

{{PreviousMenuNext("Learn/JavaScript/Building_blocks/Return_values","Learn/JavaScript/Building_blocks/Image_gallery", "Learn/JavaScript/Building_blocks")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/building_blocks/index.html b/files/de/learn/javascript/building_blocks/index.html new file mode 100644 index 0000000000..1c6fb8fc46 --- /dev/null +++ b/files/de/learn/javascript/building_blocks/index.html @@ -0,0 +1,42 @@ +--- +title: JavaScript Bausteine +slug: Learn/JavaScript/Bausteine +translation_of: Learn/JavaScript/Building_blocks +--- +
{{LearnSidebar}}
+ +

In diesem Modul betrachten wir weiterhin JavaScripts Kernfunktionen. Wir betrachten verschiedene, häufig vorkommende Arten von Code Blöcken, wie zum Beispiel Fallunterscheidungen, Schleifen, Funktionen und Events. Diese hast du bereits im Laufe des Kurses gesehen, allerdings nur "nebenbei" -  jetzt behandeln wir sie explizit.

+ +

Vorraussetzungen

+ +

Bevor du mit diesem Modul anfängst, solltest du mit den Grundlagen von HTML und CSS vertraut sein und das vorherige Modul, Erste Schritte mit JavaScript, abgeschlossen haben.

+ +
+

Hinweis: Falls du auf einem Computer/Tablet/anderem Gerät arbeitest, auf dem du keine Dateien erstellen kannst, kannst du die (meisten) Code Beispiele online, zum Beispiel mit JSBin oder Thimble, ausprobieren.

+
+ +

Anleitungen

+ +
+
Entscheidungen treffen --- Fallunterscheidungen
+
In allen Programmiersprachen muss Code Entscheidungen treffen und bei unterschiedlichen Eingaben entsprechend handeln. Falls zum Beispiel in einem Spiel der Spieler keine Leben mehr übrig hat, so hat er das Spiel verloren. In einer Wetter-App soll beispielsweise morgens ein Sonnenaufgang als Hintergrund gezeigt werden, nachts jedoch Mond und Sterne. In diesem Artikel betrachten wir Fallunterscheidungen und wie diese in JavaScript funktionieren.
+
Code wiederholen
+
Manchmal soll eine Aufgabe mehr als einmal ausgeführt werden, zum Beispiel wenn eine Liste an Namen durchsucht wird. Um solche Aufgaben zu erledigen, sind Schleifen eine gute Lösung. Im folgenden Artikel werden wir Schleifen in JavaScript genauer betrachten.
+
Funktionen -- Wiederverwendbare Codeblöcke
+
Ein essentielles Konzept in der Programmierung sind Funktionen. Funktionen erlauben es, Code, der eine bestimmte Aufgabe erfüllt, in einem eigenen Block zu definieren. Anschließend kann dieser Code über ein einzelnes, kurzes Kommando aufgerufen werden, anstatt den ganzen Code mehrere Male tippen zu müssen. In diesem Artikel erkunden wir die Konzepte hinter Funktionen wie die grundlegende Syntax oder wie diese aufgerufen werden und definieren die Begriffe Funktion, Sichtbereich (Scope) und Parameter.
+
Baue deine eigene Funktion
+
Nach dem der Großteil der grundlegenden Theorie im vorherigen Artikel thematisiert wurde, bietet dieser Artikel eine praktische Erfahrung. Hier bekommst du etwas Übung im Erstellen deiner eigenen Funktion. Außerdem werden wir einige weitere nützliche Details für das Arbeiten mit Funktionen behandeln. 
+
Rückgabewerte von Funktionen
+
Es gibt ein weiteres essentielles Konzept, dass wir in diesem Kurs behandeln werden, um unsere Betrachtung von Funktionne abzuschließen --- Rückgabewerte. Manche Funktionen geben keinen "sinnvollen" Wert zurück, andere schon. Es ist wichtig zu verstehen, was diese Werte sind, wie sie benutzt werden und wie du Funktionen schreibst, die sinnvolle Werte zurückgeben.
+
Einführung in Events
+
Events sind Aktionen oder Ereignisse die in dem System, in dem du programmierts, passieren. Das System weist dich auf diese hin, so dass du gegebenenfalls entsprechend reagieren kannst. Klickt ein Nutzer beispielsweise auf einen Button auf einer Webseite, so möchtest du vermutlich darauf reagieren, in dem du eine Aktion ausführst. In diesem Artikel behandeln wir einige wichtige Konzepte bezüglich Events und betrachten deren Funktionsweise in Browsern.
+
+ +

Prüfungen

+ +

Die folgenden Aufgaben werden dein Verständnis der in diesen Artikeln behandelten JavaScript Grundlagen prüfen. 

+ +
+
Bildergalerie
+
Jetzt wo wir die grundlegenden Bausteine JavaScripts betrachtet haben, werden wir dein Wissen über Schleifen, Funktionen, Fallunterscheidungen und Events testen, indem wir eine JavaScript-basierte Bildergalerie entwickeln.
+
diff --git a/files/de/learn/javascript/first_steps/a_first_splash/index.html b/files/de/learn/javascript/first_steps/a_first_splash/index.html new file mode 100644 index 0000000000..e772147cae --- /dev/null +++ b/files/de/learn/javascript/first_steps/a_first_splash/index.html @@ -0,0 +1,597 @@ +--- +title: Ein erster Eindruck von JavaScript +slug: Learn/JavaScript/First_steps/Erster_Blick +translation_of: Learn/JavaScript/First_steps/A_first_splash +--- +
{{LearnSidebar}}
+ +
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}
+ +

Nachdem Sie etwas über die Theorie von JavaScript gelernt haben und was Sie damit machen können, werden wir Ihnen in einem komplett praktischen Tutorial einen Crashkurs in den Grundfunktionen von JavaScript anbieten. Wir werden hier Schritt für Schritt ein einfaches Zahlenraten Spiel programmieren.

+ + + + + + + + + + + + +
Voraussetzungen:Grundlegende Computerkenntnisse, einfache Grundkentnisse von HTML und CSS, sowie eine Vorstellung, was JavaScript ist.
Ziel:Erste Erfahrung beim Schreiben von JavaScript zu bekommen und zumindest ein grundlegendes Verständnis dafür zu erlangen, was das Schreiben eines JavaScript-Programms beinhaltet.
+ +

Es ist nicht nötig, dass Sie den gesamten Code sofort im Detail verstehen - wir wollen Ihnen nur grob die Konzepte vorab vorstellen und Ihnen eine Vorstellung davon vermitteln, wie JavaScript (und andere Programmiersprachen) funktionieren. In den folgenden Artikeln werden wir alle diese Funktionen noch einmal im Detail besprechen!

+ +
+

Hinweis: Viele der Befehle und Konstrukte, die Sie in JavaScript sehen werden, sind die gleichen wie in anderen Programmiersprachen - Funktionen, Schleifen, etc. Die Syntax sieht anders aus, aber die Konzepte sind immer noch weitgehend die gleichen.

+
+ +

Denken wie ein Programmierer

+ +

Eines der schwierigsten Dinge, die man bei der Programmierung lernen muss, sind nicht die Befehle, sondern wie man sie zur Lösung der Aufgabe anwendet. Sie müssen anfangen, wie ein Programmierer zu denken - Sie müssen sich im klaren sein was  Ihr Programm tun soll, um dann herauszuarbeiten welche Funktionen und Befehle Sie dafür benötigen.

+ +

Dies erfordert eine Mischung aus harter Arbeit, Erfahrung mit der Programmiersprache und Praxis - und ein wenig Kreativität. Je mehr Sie kodieren, desto besser werden Sie werden. Wir können nicht versprechen, dass Sie in fünf Minuten ein "Programmierer-Gehirn" entwickeln werden, aber wir werden Ihnen viel Gelegenheit geben, während des gesamten Kurses das Denken wie ein Programmierer zu üben.

+ +

In diesem Sinne betrachten Sie das Beispiel, das wir in diesem Artikel erstellen werden und üben damit den Prozess der Zerlegung in konkrete Einzelschritte.

+ +

Beispiel — Rate die Zahl

+ +

In diesem Artikel zeigen wir Ihnen, wie Sie das Ratespiel aufbauen können, das Sie hier sehen können.:

+ + + +

{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}

+ +

Machen Sie sich mit der Funktionsweise des Spiels vertraut, bevor Sie weitermachen.

+ +

Stellen wir uns vor, Ihr Chef hat Ihnen den folgenden Auftrag für die Erstellung dieses Spiels gegeben:

+ +
+

Schreiben Sie ein Programm das ein Zahlenratespiel implementiert. Es sollte eine Zufallszahl zwischen 1 und 100 wählen und den Spieler auffordern, die Zahl nach spätestens 10 Runden zu erraten. Nach jedem Zug sollte dem Spieler mitgeteilt werden, ob er richtig geraten hat oder nicht - und, wenn er Unrecht hat, ob die Zahl zu niedrig oder zu hoch war. Außerdem sollen dem Spieler alle vorher geratenen Zahlen angezeigt werden. Das Spiel endet, wenn der Spieler richtig rät oder wenn er 10-mal falsch geraten hat. Wenn das Spiel endet, sollte dem Spieler die Möglichkeit gegeben werden, erneut zu spielen.

+
+ +

Wenn wir uns diesen Anweisungen ansehen, können wir zunächst damit beginnen, ihn in einfache, umsetzbare Aufgaben aufzuteilen, und zwar aus der Sicht eines Programmierers:

+ +
    +
  1. Generiere eine zufällige Zahl zwischen 1 und 100.
  2. +
  3. Speichere die Anzahl der getätigten Rateversuche, setze den Wert anfangs auf 1.
  4. +
  5. Ermögliche dem Spieler, einen Tipp abzugeben.
  6. +
  7. Sobald ein Tip abgegeben wurde, speichere sie damit der Spieler seine vorherigen Eingaben sehen kann.
  8. +
  9. Als Nächstes überprüfe, ob es sich um die richtige Zahl handelt.
  10. +
  11. Wenn sie richtig ist: +
      +
    1. Zeige Glückwunsch Nachricht.
    2. +
    3. Verhindere weiter Eingaben, da das Spiel zu Ende ist.
    4. +
    5. Biete eine Möglichkeit, das Spiel neu zu starten.
    6. +
    +
  12. +
  13. Wenn sie falsch ist und noch Versuche übrig sind: +
      +
    1. Dem Spieler mitteilen, dass die Zahl noch nicht erraten ist.
    2. +
    3. Die Eingabe einer weiteren Zahl ermöglichen.
    4. +
    5. Die Anzahl der Rateversuche um 1 erhöhen.
    6. +
    +
  14. +
  15. Wenn die Zahl falsch ist und keine Versuche mehr übrig sind: +
      +
    1. Dem Spieler mitteilen, dass das Spiel zu Ende ist.
    2. +
    3. Keine weiteren Eingaben mehr zulassen.
    4. +
    5. Ein Steuerelement zum Neustart des Spiels anzeigen.
    6. +
    +
  16. +
  17. Wenn das Spiel neu startet, sicherstellen dass Logik und Benutzeroberfläche zurückgesetzt werden. Danach zurück zum 1. Schritt.
  18. +
+ +

Lassen Sie uns nun fortfahren und schauen, wie wir diese Punkte in Code umwandeln können, das Beispiel aufbauen und die JavaScript-Funktionen während der Arbeit erforschen.

+ +

Vorbereitungen

+ +

Um dieses Tutorial zu beginnen, möchten wir Sie bitten, eine lokale Kopie der Datei number-guessing-game-start.html (see it live here) zu erstellen. Öffnen Sie es sowohl in Ihrem Texteditor als auch in Ihrem Webbrowser. Im Moment sehen Sie eine einfache Überschrift, einen Absatz mit Anweisungen und ein Formular zur Eingabe einer Schätzung, aber das Formular wird derzeit nichts tun.

+ +

Unseren gesamten Code werden wir innerhalb des {{htmlelement("script")}} Elements am Ende der HTML-Datei einfügen:

+ +
<script>
+
+  // Ihr Programm steht hier
+
+</script>
+
+ +

Variablen hinzufügen um Daten zu speichern

+ +

Lassen Sie uns anfangen. Fügen Sie zunächst die folgenden Zeilen nach dem {{htmlelement("script")}} Element ein:

+ +
let randomNumber = Math.floor(Math.random() * 100) + 1;
+
+const guesses = document.querySelector('.guesses');
+const lastResult = document.querySelector('.lastResult');
+const lowOrHi = document.querySelector('.lowOrHi');
+
+const guessSubmit = document.querySelector('.guessSubmit');
+const guessField = document.querySelector('.guessField');
+
+let guessCount = 1;
+let resetButton;
+ +

Obiger Code richtet die Variablen und Konstanten ein, die wir benötigen, um die Daten zu speichern, die unser Programm verwenden wird. Variablen sind im Grunde genommen Container für Werte (z.B. Zahlen oder Text). Sie erstellen eine Variable mit dem Schlüsselwort let (oder var) gefolgt von einem Namen für Ihre Variable (Sie werden mehr über den Unterschied zwischen den beiden Schlüsselwörtern in einem zukünftigen Artikel lesen). Konstanten werden verwendet, um Werte zu speichern, die Sie nicht ändern möchten, und werden mit dem Schlüsselwort const erstellt. In diesem Fall verwenden wir Konstanten, um Referenzen auf Teile unserer Benutzeroberfläche zu speichern; der Text in einigen von ihnen kann sich ändern, aber die referenzierten HTML-Elemente bleiben unverändert.

+ +

Sie können Ihrer Variablen oder Konstanten einen Wert mit einem Gleichheitszeichen (=) zuweisen, gefolgt von dem Wert, den Sie ihr geben möchten.

+ +

In unser Beispiel:

+ + + +
+

Note: You'll learn a lot more about variables/constants later on in the course, starting with the next article.

+
+ +

Functions

+ +

Next, add the following below your previous JavaScript:

+ +
function checkGuess() {
+  alert('I am a placeholder');
+}
+ +

Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it. After that we put two curly braces ({ }). Inside the curly braces goes all the code that we want to run whenever we call the function.

+ +

When we want to run the code, we type the name of the function followed by the parentheses.

+ +

Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:

+ +
checkGuess();
+ +

After pressing Return/Enter, you should see an alert come up that says "I am a placeholder"; we have defined a function in our code that creates an alert whenever we call it.

+ +
+

Note: You'll learn a lot more about functions later in the course.

+
+ +

Operators

+ +

JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.

+ +

If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below — type in each one from the "Example" columns exactly as shown, pressing Return/Enter after each one, and see what results they return.

+ +

First let's look at arithmetic operators, for example:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExample
+Addition6 + 9
-Subtraction20 - 15
*Multiplication3 * 7
/Division10 / 5
+ +

You can also use the + operator to join text strings together (in programming, this is called concatenation). Try entering the following lines, one at a time:

+ +
let name = 'Bingo';
+name;
+let hello = ' says hello!';
+hello;
+let greeting = name + hello;
+greeting;
+ +

There are also some shortcut operators available, called augmented assignment operators. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:

+ +
name += ' says hello!';
+ +

This is equivalent to

+ +
name = name + ' says hello!';
+ +

When we are running true/false tests (for example inside conditionals — see {{anch("Conditionals", "below")}}) we use comparison operators. For example:

+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
OperatorNameExample
===Strict equality (is it exactly the same?) +
+5 === 2 + 4 // false
+'Chris' === 'Bob' // false
+5 === 2 + 3 // true
+2 === '2' // false; number versus string
+
+
!==Non-equality (is it not the same?) +
+5 !== 2 + 4 // true
+'Chris' !== 'Bob' // true
+5 !== 2 + 3 // false
+2 !== '2' // true; number versus string
+
+
<Less than +
+6 < 10 // true
+20 < 10 // false
+
>Greater than +
+6 > 10 // false
+20 > 10  // true
+
+ +

Conditionals

+ +

Returning to our checkGuess() function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.

+ +

At this point, replace your current checkGuess() function with this version instead:

+ +
function checkGuess() {
+  let userGuess = Number(guessField.value);
+  if (guessCount === 1) {
+    guesses.textContent = 'Previous guesses: ';
+  }
+  guesses.textContent += userGuess + ' ';
+
+  if (userGuess === randomNumber) {
+    lastResult.textContent = 'Congratulations! You got it right!';
+    lastResult.style.backgroundColor = 'green';
+    lowOrHi.textContent = '';
+    setGameOver();
+  } else if (guessCount === 10) {
+    lastResult.textContent = '!!!GAME OVER!!!';
+    setGameOver();
+  } else {
+    lastResult.textContent = 'Wrong!';
+    lastResult.style.backgroundColor = 'red';
+    if(userGuess < randomNumber) {
+      lowOrHi.textContent = 'Last guess was too low!';
+    } else if(userGuess > randomNumber) {
+      lowOrHi.textContent = 'Last guess was too high!';
+    }
+  }
+
+  guessCount++;
+  guessField.value = '';
+  guessField.focus();
+}
+ +

This is a lot of code — phew! Let's go through each section and explain what it does.

+ + + +

Events

+ +

At this point we have a nicely implemented checkGuess() function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers.

+ +

Add the following line below your checkGuess() function:

+ +
guessSubmit.addEventListener('click', checkGuess);
+ +

Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside {{domxref("EventTarget.addEventListener", "addEventListener()")}}.

+ +

Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.

+ +

Finishing the game functionality

+ +

Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:

+ +
function setGameOver() {
+  guessField.disabled = true;
+  guessSubmit.disabled = true;
+  resetButton = document.createElement('button');
+  resetButton.textContent = 'Start new game';
+  document.body.appendChild(resetButton);
+  resetButton.addEventListener('click', resetGame);
+}
+ + + +

Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:

+ +
function resetGame() {
+  guessCount = 1;
+
+  const resetParas = document.querySelectorAll('.resultParas p');
+  for (let i = 0 ; i < resetParas.length ; i++) {
+    resetParas[i].textContent = '';
+  }
+
+  resetButton.parentNode.removeChild(resetButton);
+
+  guessField.disabled = false;
+  guessSubmit.disabled = false;
+  guessField.value = '';
+  guessField.focus();
+
+  lastResult.style.backgroundColor = 'white';
+
+  randomNumber = Math.floor(Math.random() * 100) + 1;
+}
+ +

This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:

+ + + +

At this point you should have a fully working (simple) game — congratulations!

+ +

All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.

+ +

Loops

+ +

One part of the above code that we need to take a more detailed look at is the for loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.

+ +

To start with, go to your browser developer tools JavaScript console again, and enter the following:

+ +
for (let i = 1 ; i < 21 ; i++) { console.log(i) }
+ +

What happened? The numbers 1 to 20 were printed out in your console. This is because of the loop. A for loop takes three input values (arguments):

+ +
    +
  1. A starting value: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter i with any name you like too, but i is used as a convention because it's short and easy to remember.
  2. +
  3. An exit condition: Here we have specified i < 21 — the loop will keep going until i is no longer less than 21. When i reaches 21, the loop will no longer run.
  4. +
  5. An incrementor: We have specified i++, which means "add 1 to i". The loop will run once for every value of i, until i reaches a value of 21 (as discussed above). In this case, we are simply printing the value of i out to the console on every iteration using {{domxref("Console.log", "console.log()")}}.
  6. +
+ +

Now let's look at the loop in our number guessing game — the following can be found inside the resetGame() function:

+ +
let resetParas = document.querySelectorAll('.resultParas p');
+for (let i = 0 ; i < resetParas.length ; i++) {
+  resetParas[i].textContent = '';
+}
+ +

This code creates a variable containing a list of all the paragraphs inside <div class="resultParas"> using the {{domxref("Document.querySelectorAll", "querySelectorAll()")}} method, then it loops through each one, removing the text content of each.

+ +

A small discussion on objects

+ +

Let's add one more final improvement before we get to this discussion. Add the following line just below the let resetButton; line near the top of your JavaScript, then save your file:

+ +
guessField.focus();
+ +

This line uses the {{domxref("HTMLElement.focus", "focus()")}} method to automatically put the text cursor into the {{htmlelement("input")}} text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.

+ +

Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.

+ +

In this particular case, we first created a guessField constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:

+ +
const guessField = document.querySelector('.guessField');
+ +

To get this reference, we used the {{domxref("document.querySelector", "querySelector()")}} method of the {{domxref("document")}} object. querySelector() takes one piece of information — a CSS selector that selects the element you want a reference to.

+ +

Because guessField now contains a reference to an {{htmlelement("input")}} element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is focus(), so we can now use this line to focus the text input:

+ +
guessField.focus();
+ +

Variables that don't contain references to form elements won't have focus() available to them. For example, the guesses constant contains a reference to a {{htmlelement("p")}} element, and the guessCount variable contains a number.

+ +

Playing with browser objects

+ +

Let's play with some browser objects a bit.

+ +
    +
  1. First of all, open up your program in a browser.
  2. +
  3. Next, open your browser developer tools, and make sure the JavaScript console tab is open.
  4. +
  5. Type in guessField and the console will show you that the variable contains an {{htmlelement("input")}} element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!
  6. +
  7. Now type in the following: +
    guessField.value = 'Hello';
    + The value property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!
  8. +
  9. Now try typing in guesses and pressing return. The console will show you that the variable contains a {{htmlelement("p")}} element.
  10. +
  11. Now try entering the following line: +
    guesses.value
    + The browser will return undefined, because paragraphs don't have the value property.
  12. +
  13. To change the text inside a paragraph, you need the {{domxref("Node.textContent", "textContent")}} property instead. Try this: +
    guesses.textContent = 'Where is my paragraph?';
    +
  14. +
  15. Now for some fun stuff. Try entering the below lines, one by one: +
    guesses.style.backgroundColor = 'yellow';
    +guesses.style.fontSize = '200%';
    +guesses.style.padding = '10px';
    +guesses.style.boxShadow = '3px 3px 6px black';
    + Every element on a page has a style property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.
  16. +
+ +

Finished for now...

+ +

So that's it for building the example. You got to the end — well done! Try your final code out, or play with our finished version here. If you can't get the example to work, check it against the source code.

+ +

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/first_steps/erster_blick/index.html b/files/de/learn/javascript/first_steps/erster_blick/index.html deleted file mode 100644 index e772147cae..0000000000 --- a/files/de/learn/javascript/first_steps/erster_blick/index.html +++ /dev/null @@ -1,597 +0,0 @@ ---- -title: Ein erster Eindruck von JavaScript -slug: Learn/JavaScript/First_steps/Erster_Blick -translation_of: Learn/JavaScript/First_steps/A_first_splash ---- -
{{LearnSidebar}}
- -
{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}
- -

Nachdem Sie etwas über die Theorie von JavaScript gelernt haben und was Sie damit machen können, werden wir Ihnen in einem komplett praktischen Tutorial einen Crashkurs in den Grundfunktionen von JavaScript anbieten. Wir werden hier Schritt für Schritt ein einfaches Zahlenraten Spiel programmieren.

- - - - - - - - - - - - -
Voraussetzungen:Grundlegende Computerkenntnisse, einfache Grundkentnisse von HTML und CSS, sowie eine Vorstellung, was JavaScript ist.
Ziel:Erste Erfahrung beim Schreiben von JavaScript zu bekommen und zumindest ein grundlegendes Verständnis dafür zu erlangen, was das Schreiben eines JavaScript-Programms beinhaltet.
- -

Es ist nicht nötig, dass Sie den gesamten Code sofort im Detail verstehen - wir wollen Ihnen nur grob die Konzepte vorab vorstellen und Ihnen eine Vorstellung davon vermitteln, wie JavaScript (und andere Programmiersprachen) funktionieren. In den folgenden Artikeln werden wir alle diese Funktionen noch einmal im Detail besprechen!

- -
-

Hinweis: Viele der Befehle und Konstrukte, die Sie in JavaScript sehen werden, sind die gleichen wie in anderen Programmiersprachen - Funktionen, Schleifen, etc. Die Syntax sieht anders aus, aber die Konzepte sind immer noch weitgehend die gleichen.

-
- -

Denken wie ein Programmierer

- -

Eines der schwierigsten Dinge, die man bei der Programmierung lernen muss, sind nicht die Befehle, sondern wie man sie zur Lösung der Aufgabe anwendet. Sie müssen anfangen, wie ein Programmierer zu denken - Sie müssen sich im klaren sein was  Ihr Programm tun soll, um dann herauszuarbeiten welche Funktionen und Befehle Sie dafür benötigen.

- -

Dies erfordert eine Mischung aus harter Arbeit, Erfahrung mit der Programmiersprache und Praxis - und ein wenig Kreativität. Je mehr Sie kodieren, desto besser werden Sie werden. Wir können nicht versprechen, dass Sie in fünf Minuten ein "Programmierer-Gehirn" entwickeln werden, aber wir werden Ihnen viel Gelegenheit geben, während des gesamten Kurses das Denken wie ein Programmierer zu üben.

- -

In diesem Sinne betrachten Sie das Beispiel, das wir in diesem Artikel erstellen werden und üben damit den Prozess der Zerlegung in konkrete Einzelschritte.

- -

Beispiel — Rate die Zahl

- -

In diesem Artikel zeigen wir Ihnen, wie Sie das Ratespiel aufbauen können, das Sie hier sehen können.:

- - - -

{{ EmbedLiveSample('Top_hidden_code', '100%', 320, "", "", "hide-codepen-jsfiddle") }}

- -

Machen Sie sich mit der Funktionsweise des Spiels vertraut, bevor Sie weitermachen.

- -

Stellen wir uns vor, Ihr Chef hat Ihnen den folgenden Auftrag für die Erstellung dieses Spiels gegeben:

- -
-

Schreiben Sie ein Programm das ein Zahlenratespiel implementiert. Es sollte eine Zufallszahl zwischen 1 und 100 wählen und den Spieler auffordern, die Zahl nach spätestens 10 Runden zu erraten. Nach jedem Zug sollte dem Spieler mitgeteilt werden, ob er richtig geraten hat oder nicht - und, wenn er Unrecht hat, ob die Zahl zu niedrig oder zu hoch war. Außerdem sollen dem Spieler alle vorher geratenen Zahlen angezeigt werden. Das Spiel endet, wenn der Spieler richtig rät oder wenn er 10-mal falsch geraten hat. Wenn das Spiel endet, sollte dem Spieler die Möglichkeit gegeben werden, erneut zu spielen.

-
- -

Wenn wir uns diesen Anweisungen ansehen, können wir zunächst damit beginnen, ihn in einfache, umsetzbare Aufgaben aufzuteilen, und zwar aus der Sicht eines Programmierers:

- -
    -
  1. Generiere eine zufällige Zahl zwischen 1 und 100.
  2. -
  3. Speichere die Anzahl der getätigten Rateversuche, setze den Wert anfangs auf 1.
  4. -
  5. Ermögliche dem Spieler, einen Tipp abzugeben.
  6. -
  7. Sobald ein Tip abgegeben wurde, speichere sie damit der Spieler seine vorherigen Eingaben sehen kann.
  8. -
  9. Als Nächstes überprüfe, ob es sich um die richtige Zahl handelt.
  10. -
  11. Wenn sie richtig ist: -
      -
    1. Zeige Glückwunsch Nachricht.
    2. -
    3. Verhindere weiter Eingaben, da das Spiel zu Ende ist.
    4. -
    5. Biete eine Möglichkeit, das Spiel neu zu starten.
    6. -
    -
  12. -
  13. Wenn sie falsch ist und noch Versuche übrig sind: -
      -
    1. Dem Spieler mitteilen, dass die Zahl noch nicht erraten ist.
    2. -
    3. Die Eingabe einer weiteren Zahl ermöglichen.
    4. -
    5. Die Anzahl der Rateversuche um 1 erhöhen.
    6. -
    -
  14. -
  15. Wenn die Zahl falsch ist und keine Versuche mehr übrig sind: -
      -
    1. Dem Spieler mitteilen, dass das Spiel zu Ende ist.
    2. -
    3. Keine weiteren Eingaben mehr zulassen.
    4. -
    5. Ein Steuerelement zum Neustart des Spiels anzeigen.
    6. -
    -
  16. -
  17. Wenn das Spiel neu startet, sicherstellen dass Logik und Benutzeroberfläche zurückgesetzt werden. Danach zurück zum 1. Schritt.
  18. -
- -

Lassen Sie uns nun fortfahren und schauen, wie wir diese Punkte in Code umwandeln können, das Beispiel aufbauen und die JavaScript-Funktionen während der Arbeit erforschen.

- -

Vorbereitungen

- -

Um dieses Tutorial zu beginnen, möchten wir Sie bitten, eine lokale Kopie der Datei number-guessing-game-start.html (see it live here) zu erstellen. Öffnen Sie es sowohl in Ihrem Texteditor als auch in Ihrem Webbrowser. Im Moment sehen Sie eine einfache Überschrift, einen Absatz mit Anweisungen und ein Formular zur Eingabe einer Schätzung, aber das Formular wird derzeit nichts tun.

- -

Unseren gesamten Code werden wir innerhalb des {{htmlelement("script")}} Elements am Ende der HTML-Datei einfügen:

- -
<script>
-
-  // Ihr Programm steht hier
-
-</script>
-
- -

Variablen hinzufügen um Daten zu speichern

- -

Lassen Sie uns anfangen. Fügen Sie zunächst die folgenden Zeilen nach dem {{htmlelement("script")}} Element ein:

- -
let randomNumber = Math.floor(Math.random() * 100) + 1;
-
-const guesses = document.querySelector('.guesses');
-const lastResult = document.querySelector('.lastResult');
-const lowOrHi = document.querySelector('.lowOrHi');
-
-const guessSubmit = document.querySelector('.guessSubmit');
-const guessField = document.querySelector('.guessField');
-
-let guessCount = 1;
-let resetButton;
- -

Obiger Code richtet die Variablen und Konstanten ein, die wir benötigen, um die Daten zu speichern, die unser Programm verwenden wird. Variablen sind im Grunde genommen Container für Werte (z.B. Zahlen oder Text). Sie erstellen eine Variable mit dem Schlüsselwort let (oder var) gefolgt von einem Namen für Ihre Variable (Sie werden mehr über den Unterschied zwischen den beiden Schlüsselwörtern in einem zukünftigen Artikel lesen). Konstanten werden verwendet, um Werte zu speichern, die Sie nicht ändern möchten, und werden mit dem Schlüsselwort const erstellt. In diesem Fall verwenden wir Konstanten, um Referenzen auf Teile unserer Benutzeroberfläche zu speichern; der Text in einigen von ihnen kann sich ändern, aber die referenzierten HTML-Elemente bleiben unverändert.

- -

Sie können Ihrer Variablen oder Konstanten einen Wert mit einem Gleichheitszeichen (=) zuweisen, gefolgt von dem Wert, den Sie ihr geben möchten.

- -

In unser Beispiel:

- - - -
-

Note: You'll learn a lot more about variables/constants later on in the course, starting with the next article.

-
- -

Functions

- -

Next, add the following below your previous JavaScript:

- -
function checkGuess() {
-  alert('I am a placeholder');
-}
- -

Functions are reusable blocks of code that you can write once and run again and again, saving the need to keep repeating code all the time. This is really useful. There are a number of ways to define functions, but for now we'll concentrate on one simple type. Here we have defined a function by using the keyword function, followed by a name, with parentheses put after it. After that we put two curly braces ({ }). Inside the curly braces goes all the code that we want to run whenever we call the function.

- -

When we want to run the code, we type the name of the function followed by the parentheses.

- -

Let's try that now. Save your code and refresh the page in your browser. Then go into the developer tools JavaScript console, and enter the following line:

- -
checkGuess();
- -

After pressing Return/Enter, you should see an alert come up that says "I am a placeholder"; we have defined a function in our code that creates an alert whenever we call it.

- -
-

Note: You'll learn a lot more about functions later in the course.

-
- -

Operators

- -

JavaScript operators allow us to perform tests, do maths, join strings together, and other such things.

- -

If you haven't already done so, save your code, refresh the page in your browser, and open the developer tools JavaScript console. Then we can try typing in the examples shown below — type in each one from the "Example" columns exactly as shown, pressing Return/Enter after each one, and see what results they return.

- -

First let's look at arithmetic operators, for example:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperatorNameExample
+Addition6 + 9
-Subtraction20 - 15
*Multiplication3 * 7
/Division10 / 5
- -

You can also use the + operator to join text strings together (in programming, this is called concatenation). Try entering the following lines, one at a time:

- -
let name = 'Bingo';
-name;
-let hello = ' says hello!';
-hello;
-let greeting = name + hello;
-greeting;
- -

There are also some shortcut operators available, called augmented assignment operators. For example, if you want to simply add a new text string to an existing one and return the result, you could do this:

- -
name += ' says hello!';
- -

This is equivalent to

- -
name = name + ' says hello!';
- -

When we are running true/false tests (for example inside conditionals — see {{anch("Conditionals", "below")}}) we use comparison operators. For example:

- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
OperatorNameExample
===Strict equality (is it exactly the same?) -
-5 === 2 + 4 // false
-'Chris' === 'Bob' // false
-5 === 2 + 3 // true
-2 === '2' // false; number versus string
-
-
!==Non-equality (is it not the same?) -
-5 !== 2 + 4 // true
-'Chris' !== 'Bob' // true
-5 !== 2 + 3 // false
-2 !== '2' // true; number versus string
-
-
<Less than -
-6 < 10 // true
-20 < 10 // false
-
>Greater than -
-6 > 10 // false
-20 > 10  // true
-
- -

Conditionals

- -

Returning to our checkGuess() function, I think it's safe to say that we don't want it to just spit out a placeholder message. We want it to check whether a player's guess is correct or not, and respond appropriately.

- -

At this point, replace your current checkGuess() function with this version instead:

- -
function checkGuess() {
-  let userGuess = Number(guessField.value);
-  if (guessCount === 1) {
-    guesses.textContent = 'Previous guesses: ';
-  }
-  guesses.textContent += userGuess + ' ';
-
-  if (userGuess === randomNumber) {
-    lastResult.textContent = 'Congratulations! You got it right!';
-    lastResult.style.backgroundColor = 'green';
-    lowOrHi.textContent = '';
-    setGameOver();
-  } else if (guessCount === 10) {
-    lastResult.textContent = '!!!GAME OVER!!!';
-    setGameOver();
-  } else {
-    lastResult.textContent = 'Wrong!';
-    lastResult.style.backgroundColor = 'red';
-    if(userGuess < randomNumber) {
-      lowOrHi.textContent = 'Last guess was too low!';
-    } else if(userGuess > randomNumber) {
-      lowOrHi.textContent = 'Last guess was too high!';
-    }
-  }
-
-  guessCount++;
-  guessField.value = '';
-  guessField.focus();
-}
- -

This is a lot of code — phew! Let's go through each section and explain what it does.

- - - -

Events

- -

At this point we have a nicely implemented checkGuess() function, but it won't do anything because we haven't called it yet. Ideally we want to call it when the "Submit guess" button is pressed, and to do this we need to use an event. Events are things that happen in the browser — a button being clicked, a page loading, a video playing, etc. — in response to which we can run blocks of code. The constructs that listen out for the event happening are called event listeners, and the blocks of code that run in response to the event firing are called event handlers.

- -

Add the following line below your checkGuess() function:

- -
guessSubmit.addEventListener('click', checkGuess);
- -

Here we are adding an event listener to the guessSubmit button. This is a method that takes two input values (called arguments) — the type of event we are listening out for (in this case click) as a string, and the code we want to run when the event occurs (in this case the checkGuess() function). Note that we don't need to specify the parentheses when writing it inside {{domxref("EventTarget.addEventListener", "addEventListener()")}}.

- -

Try saving and refreshing your code now, and your example should work — to a point. The only problem now is that if you guess the correct answer or run out of guesses, the game will break because we've not yet defined the setGameOver() function that is supposed to be run once the game is over. Let's add our missing code now and complete the example functionality.

- -

Finishing the game functionality

- -

Let's add that setGameOver() function to the bottom of our code and then walk through it. Add this now, below the rest of your JavaScript:

- -
function setGameOver() {
-  guessField.disabled = true;
-  guessSubmit.disabled = true;
-  resetButton = document.createElement('button');
-  resetButton.textContent = 'Start new game';
-  document.body.appendChild(resetButton);
-  resetButton.addEventListener('click', resetGame);
-}
- - - -

Now we need to define this function too! Add the following code, again to the bottom of your JavaScript:

- -
function resetGame() {
-  guessCount = 1;
-
-  const resetParas = document.querySelectorAll('.resultParas p');
-  for (let i = 0 ; i < resetParas.length ; i++) {
-    resetParas[i].textContent = '';
-  }
-
-  resetButton.parentNode.removeChild(resetButton);
-
-  guessField.disabled = false;
-  guessSubmit.disabled = false;
-  guessField.value = '';
-  guessField.focus();
-
-  lastResult.style.backgroundColor = 'white';
-
-  randomNumber = Math.floor(Math.random() * 100) + 1;
-}
- -

This rather long block of code completely resets everything to how it was at the start of the game, so the player can have another go. It:

- - - -

At this point you should have a fully working (simple) game — congratulations!

- -

All we have left to do now in this article is talk about a few other important code features that you've already seen, although you may have not realized it.

- -

Loops

- -

One part of the above code that we need to take a more detailed look at is the for loop. Loops are a very important concept in programming, which allow you to keep running a piece of code over and over again, until a certain condition is met.

- -

To start with, go to your browser developer tools JavaScript console again, and enter the following:

- -
for (let i = 1 ; i < 21 ; i++) { console.log(i) }
- -

What happened? The numbers 1 to 20 were printed out in your console. This is because of the loop. A for loop takes three input values (arguments):

- -
    -
  1. A starting value: In this case we are starting a count at 1, but this could be any number you like. You could replace the letter i with any name you like too, but i is used as a convention because it's short and easy to remember.
  2. -
  3. An exit condition: Here we have specified i < 21 — the loop will keep going until i is no longer less than 21. When i reaches 21, the loop will no longer run.
  4. -
  5. An incrementor: We have specified i++, which means "add 1 to i". The loop will run once for every value of i, until i reaches a value of 21 (as discussed above). In this case, we are simply printing the value of i out to the console on every iteration using {{domxref("Console.log", "console.log()")}}.
  6. -
- -

Now let's look at the loop in our number guessing game — the following can be found inside the resetGame() function:

- -
let resetParas = document.querySelectorAll('.resultParas p');
-for (let i = 0 ; i < resetParas.length ; i++) {
-  resetParas[i].textContent = '';
-}
- -

This code creates a variable containing a list of all the paragraphs inside <div class="resultParas"> using the {{domxref("Document.querySelectorAll", "querySelectorAll()")}} method, then it loops through each one, removing the text content of each.

- -

A small discussion on objects

- -

Let's add one more final improvement before we get to this discussion. Add the following line just below the let resetButton; line near the top of your JavaScript, then save your file:

- -
guessField.focus();
- -

This line uses the {{domxref("HTMLElement.focus", "focus()")}} method to automatically put the text cursor into the {{htmlelement("input")}} text field as soon as the page loads, meaning that the user can start typing their first guess right away, without having to click the form field first. It's only a small addition, but it improves usability — giving the user a good visual clue as to what they've got to do to play the game.

- -

Let's analyze what's going on here in a bit more detail. In JavaScript, everything is an object. An object is a collection of related functionality stored in a single grouping. You can create your own objects, but that is quite advanced and we won't be covering it until much later in the course. For now, we'll just briefly discuss the built-in objects that your browser contains, which allow you to do lots of useful things.

- -

In this particular case, we first created a guessField constant that stores a reference to the text input form field in our HTML — the following line can be found amongst our declarations near the top of the code:

- -
const guessField = document.querySelector('.guessField');
- -

To get this reference, we used the {{domxref("document.querySelector", "querySelector()")}} method of the {{domxref("document")}} object. querySelector() takes one piece of information — a CSS selector that selects the element you want a reference to.

- -

Because guessField now contains a reference to an {{htmlelement("input")}} element, it will now have access to a number of properties (basically variables stored inside objects, some of which can't have their values changed) and methods (basically functions stored inside objects). One method available to input elements is focus(), so we can now use this line to focus the text input:

- -
guessField.focus();
- -

Variables that don't contain references to form elements won't have focus() available to them. For example, the guesses constant contains a reference to a {{htmlelement("p")}} element, and the guessCount variable contains a number.

- -

Playing with browser objects

- -

Let's play with some browser objects a bit.

- -
    -
  1. First of all, open up your program in a browser.
  2. -
  3. Next, open your browser developer tools, and make sure the JavaScript console tab is open.
  4. -
  5. Type in guessField and the console will show you that the variable contains an {{htmlelement("input")}} element. You'll also notice that the console autocompletes the names of objects that exist inside the execution environment, including your variables!
  6. -
  7. Now type in the following: -
    guessField.value = 'Hello';
    - The value property represents the current value entered into the text field. You'll see that by entering this command, we've changed the text in the text field!
  8. -
  9. Now try typing in guesses and pressing return. The console will show you that the variable contains a {{htmlelement("p")}} element.
  10. -
  11. Now try entering the following line: -
    guesses.value
    - The browser will return undefined, because paragraphs don't have the value property.
  12. -
  13. To change the text inside a paragraph, you need the {{domxref("Node.textContent", "textContent")}} property instead. Try this: -
    guesses.textContent = 'Where is my paragraph?';
    -
  14. -
  15. Now for some fun stuff. Try entering the below lines, one by one: -
    guesses.style.backgroundColor = 'yellow';
    -guesses.style.fontSize = '200%';
    -guesses.style.padding = '10px';
    -guesses.style.boxShadow = '3px 3px 6px black';
    - Every element on a page has a style property, which itself contains an object whose properties contain all the inline CSS styles applied to that element. This allows us to dynamically set new CSS styles on elements using JavaScript.
  16. -
- -

Finished for now...

- -

So that's it for building the example. You got to the end — well done! Try your final code out, or play with our finished version here. If you can't get the example to work, check it against the source code.

- -

{{PreviousMenuNext("Learn/JavaScript/First_steps/What_is_JavaScript", "Learn/JavaScript/First_steps/What_went_wrong", "Learn/JavaScript/First_steps")}}

- -

In this module

- - diff --git a/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html b/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html deleted file mode 100644 index 1703f9b6a7..0000000000 --- a/files/de/learn/javascript/first_steps/lustige_geschichten_generator/index.html +++ /dev/null @@ -1,139 +0,0 @@ ---- -title: Der Lustige Geschichten Generator -slug: Learn/JavaScript/First_steps/lustige_geschichten_generator -translation_of: Learn/JavaScript/First_steps/Silly_story_generator ---- -
{{LearnSidebar}}
- -
{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
- -

In dieser Prüfung ist es deine Aufgabe das von dir in den vorherigen Artikeln gesammelten Wissen anzuwenden, indem due eine lustige Applikation schreibst, mit der man lustige Geschichten erzeugen kann. Viel Spass mit dem Lustige Geschichten Generator !

- - - - - - - - - - - - -
Vorraussetzungen:Bevor du dich an dieser Aufgabe versuchst, solltest du alle anderen Artikel dieses Moduls gelesen und bearbeitet haben.
Ziel:Verständnis von fundamentalen JavaScript Kenntnissen, wie Variablen, Operatoren und einfachen Datentypen (Zahlen, Zeichenketten, Arrays)
- -

Start

- -

Um mit deiner Aufgabe zu beginnen, solltest du::

- - - -
-

Notiz: Alternativ kannst du auch eine Seite wie JSBin oder Glitch benutzen, um die Aufgabe zu bearbeiten. Kopiere dazu einfach den Quelltext von HTML, CSS und JavaScript in einen dieser Online-Editoren. Wenn einer dieser Editoren kein extra JavaScript Panel haben sollte, kopiere das JavaScript einfach zwischen <script>-Tags in deinem HTML-Code.

-
- -

Projektbeschreibung

- -

Für diese Aufgabe geben wir dir einige HTML/CSS Codestücke, einige Textbausteine und ein paar JavaScript Funktionen in die Hand; du musst die fehlenden JavaScript-Teile ergänzen, um alles zu einem lauffähigen Programm zu kombinieren, was Folgendes tun kann:

- - - -

Der folgende Screenshot zeigt dir ein Beispiel, wie die Ausgabe deines geschriebenen Programmes aussehen wird:

- -

- -

Um dich noch mehr mit deiner Arbeit vertraut zu machen, schau dir die fertige Lösung an (ohne im Quellcode zu spicken! )

- -

Schritt-für-Schritt Anleitung

- -

In den folgenden Abschnitten wird dir erklärt, was du tun musst.

- -

Grundaufbau:

- -
    -
  1. Erzeuge eine Datei mit dem Namen main.js, und zwar im selben Verzeichnis, wie deine index.html Datei.
  2. -
  3. Verbinde deine externe JavaScript Datei main.js mit deiner HTML Datei, indem du es mithilfe des Script-tags {{htmlelement("script")}} in deinem HTML aufrufst. Füge die Zeile kurz vor dem schließenden </body> tag ein.
  4. -
- -

 Vorgegebene Variablen und Functions:

- -
    -
  1. Kopiere alle Code-Zeilen aus der Roh-Text-Datei, die unter der Überschrift "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" stehen und füge Sie an den Anfang deiner main.js Datei. Im Code wirst du 3 Variablen entdecken, die sich auf verschiedene Teile der Ausgabe beziehen: (customName) bezieht sich auf das "Enter custom name" Text Feld , the "Generate random story" button (randomize), and the {{htmlelement("p")}} element at the bottom of the HTML body that the story will be copied into (story), respectively. In addition you've got a function called randomValueFromArray() that takes an array, and returns one of the items stored inside the array at random.
  2. -
  3. Now look at the second section of the raw text file — "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside main.js: -
      -
    1. Store the first, big long, string of text inside a variable called storyText.
    2. -
    3. Store the first set of three strings inside an array called insertX.
    4. -
    5. Store the second set of three strings inside an array called insertY.
    6. -
    7. Store the third set of three strings inside an array called insertZ.
    8. -
    -
  4. -
- -

Placing the event handler and incomplete function:

- -
    -
  1. Now return to the raw text file.
  2. -
  3. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your main.js file. This: -
      -
    • Adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run.
    • -
    • Adds a partially-completed result() function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
    • -
    -
  4. -
- -

Completing the result() function:

- -
    -
  1. Create a new variable called newStory, and set it's value to equal storyText. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to storyText, we'd only be able to generate a new story once.
  2. -
  3. Create three new variables called xItem, yItem, and zItem, and make them equal to the result of calling randomValueFromArray() on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of insertX by writing randomValueFromArray(insertX).
  4. -
  5. Next we want to replace the three placeholders in the newStory string — :insertx:, :inserty:, and :insertz: — with the strings stored in xItem, yItem, and zItem. There is a particular string method that will help you here — in each case, make the call to the method equal to newStory, so each time it is called, newStory is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice.
  6. -
  7. Inside the first if block, add another string replacement method call to replace the name 'Bob' found in the newStory string with the name variable. In this block we are saying "If a value has been entered into the customName text input, replace Bob in the story with that custom name."
  8. -
  9. Inside the second if block, we are checking to see if the uk radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows: -
      -
    1. Look up the formulae for converting pounds to stone, and Fahrenheit to centigrade.
    2. -
    3. Inside the line that defines the weight variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate ' stone' onto the end of the result of the overall Math.round() call.
    4. -
    5. Inside the line that defines the temperature variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate ' centigrade' onto the end of the result of the overall Math.round() call.
    6. -
    7. Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the temperature variable, and '300 pounds' with the contents of the weight variable.
    8. -
    -
  10. -
  11. Finally, in the second-to-last line of the function, make the textContent property of the story variable (which references the paragraph) equal to newStory.
  12. -
- -

Hints and tips

- - - -

Assessment

- -

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread for this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

- -

{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

- -

In this module

- - diff --git a/files/de/learn/javascript/first_steps/silly_story_generator/index.html b/files/de/learn/javascript/first_steps/silly_story_generator/index.html new file mode 100644 index 0000000000..1703f9b6a7 --- /dev/null +++ b/files/de/learn/javascript/first_steps/silly_story_generator/index.html @@ -0,0 +1,139 @@ +--- +title: Der Lustige Geschichten Generator +slug: Learn/JavaScript/First_steps/lustige_geschichten_generator +translation_of: Learn/JavaScript/First_steps/Silly_story_generator +--- +
{{LearnSidebar}}
+ +
{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}
+ +

In dieser Prüfung ist es deine Aufgabe das von dir in den vorherigen Artikeln gesammelten Wissen anzuwenden, indem due eine lustige Applikation schreibst, mit der man lustige Geschichten erzeugen kann. Viel Spass mit dem Lustige Geschichten Generator !

+ + + + + + + + + + + + +
Vorraussetzungen:Bevor du dich an dieser Aufgabe versuchst, solltest du alle anderen Artikel dieses Moduls gelesen und bearbeitet haben.
Ziel:Verständnis von fundamentalen JavaScript Kenntnissen, wie Variablen, Operatoren und einfachen Datentypen (Zahlen, Zeichenketten, Arrays)
+ +

Start

+ +

Um mit deiner Aufgabe zu beginnen, solltest du::

+ + + +
+

Notiz: Alternativ kannst du auch eine Seite wie JSBin oder Glitch benutzen, um die Aufgabe zu bearbeiten. Kopiere dazu einfach den Quelltext von HTML, CSS und JavaScript in einen dieser Online-Editoren. Wenn einer dieser Editoren kein extra JavaScript Panel haben sollte, kopiere das JavaScript einfach zwischen <script>-Tags in deinem HTML-Code.

+
+ +

Projektbeschreibung

+ +

Für diese Aufgabe geben wir dir einige HTML/CSS Codestücke, einige Textbausteine und ein paar JavaScript Funktionen in die Hand; du musst die fehlenden JavaScript-Teile ergänzen, um alles zu einem lauffähigen Programm zu kombinieren, was Folgendes tun kann:

+ + + +

Der folgende Screenshot zeigt dir ein Beispiel, wie die Ausgabe deines geschriebenen Programmes aussehen wird:

+ +

+ +

Um dich noch mehr mit deiner Arbeit vertraut zu machen, schau dir die fertige Lösung an (ohne im Quellcode zu spicken! )

+ +

Schritt-für-Schritt Anleitung

+ +

In den folgenden Abschnitten wird dir erklärt, was du tun musst.

+ +

Grundaufbau:

+ +
    +
  1. Erzeuge eine Datei mit dem Namen main.js, und zwar im selben Verzeichnis, wie deine index.html Datei.
  2. +
  3. Verbinde deine externe JavaScript Datei main.js mit deiner HTML Datei, indem du es mithilfe des Script-tags {{htmlelement("script")}} in deinem HTML aufrufst. Füge die Zeile kurz vor dem schließenden </body> tag ein.
  4. +
+ +

 Vorgegebene Variablen und Functions:

+ +
    +
  1. Kopiere alle Code-Zeilen aus der Roh-Text-Datei, die unter der Überschrift "1. COMPLETE VARIABLE AND FUNCTION DEFINITIONS" stehen und füge Sie an den Anfang deiner main.js Datei. Im Code wirst du 3 Variablen entdecken, die sich auf verschiedene Teile der Ausgabe beziehen: (customName) bezieht sich auf das "Enter custom name" Text Feld , the "Generate random story" button (randomize), and the {{htmlelement("p")}} element at the bottom of the HTML body that the story will be copied into (story), respectively. In addition you've got a function called randomValueFromArray() that takes an array, and returns one of the items stored inside the array at random.
  2. +
  3. Now look at the second section of the raw text file — "2. RAW TEXT STRINGS". This contains text strings that will act as input into our program. We'd like you to contain these inside variables inside main.js: +
      +
    1. Store the first, big long, string of text inside a variable called storyText.
    2. +
    3. Store the first set of three strings inside an array called insertX.
    4. +
    5. Store the second set of three strings inside an array called insertY.
    6. +
    7. Store the third set of three strings inside an array called insertZ.
    8. +
    +
  4. +
+ +

Placing the event handler and incomplete function:

+ +
    +
  1. Now return to the raw text file.
  2. +
  3. Copy the code found underneath the heading "3. EVENT LISTENER AND PARTIAL FUNCTION DEFINITION" and paste it into the bottom of your main.js file. This: +
      +
    • Adds a click event listener to the randomize variable so that when the button it represents is clicked, the result() function is run.
    • +
    • Adds a partially-completed result() function definiton to your code. For the remainder of the assessment, you'll be filling in lines inside this function to complete it and make it work properly.
    • +
    +
  4. +
+ +

Completing the result() function:

+ +
    +
  1. Create a new variable called newStory, and set it's value to equal storyText. This is needed so we can create a new random story each time the button is pressed and the function is run. If we made changes directly to storyText, we'd only be able to generate a new story once.
  2. +
  3. Create three new variables called xItem, yItem, and zItem, and make them equal to the result of calling randomValueFromArray() on your three arrays (the result in each case will be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of insertX by writing randomValueFromArray(insertX).
  4. +
  5. Next we want to replace the three placeholders in the newStory string — :insertx:, :inserty:, and :insertz: — with the strings stored in xItem, yItem, and zItem. There is a particular string method that will help you here — in each case, make the call to the method equal to newStory, so each time it is called, newStory is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of the calls twice.
  6. +
  7. Inside the first if block, add another string replacement method call to replace the name 'Bob' found in the newStory string with the name variable. In this block we are saying "If a value has been entered into the customName text input, replace Bob in the story with that custom name."
  8. +
  9. Inside the second if block, we are checking to see if the uk radio button has been selected. If so, we want to convert the weight and temperature values in the story from pounds and Fahrenheit into stones and centigrade. What you need to do is as follows: +
      +
    1. Look up the formulae for converting pounds to stone, and Fahrenheit to centigrade.
    2. +
    3. Inside the line that defines the weight variable, replace 300 with a calculation that converts 300 pounds into stones. Concatenate ' stone' onto the end of the result of the overall Math.round() call.
    4. +
    5. Inside the line that defines the temperature variable, replace 94 with a calculation that converts 94 Fahrenheit into centigrade. Concatenate ' centigrade' onto the end of the result of the overall Math.round() call.
    6. +
    7. Just under the two variable definitions, add two more string replacement lines that replace '94 fahrenheit' with the contents of the temperature variable, and '300 pounds' with the contents of the weight variable.
    8. +
    +
  10. +
  11. Finally, in the second-to-last line of the function, make the textContent property of the story variable (which references the paragraph) equal to newStory.
  12. +
+ +

Hints and tips

+ + + +

Assessment

+ +

If you are following this assessment as part of an organized course, you should be able to give your work to your teacher/mentor for marking. If you are self-learning, then you can get the marking guide fairly easily by asking on the discussion thread for this exercise, or in the #mdn IRC channel on Mozilla IRC. Try the exercise first — there is nothing to be gained by cheating!

+ +

{{PreviousMenu("Learn/JavaScript/First_steps/Arrays", "Learn/JavaScript/First_steps")}}

+ +

In this module

+ + diff --git a/files/de/learn/javascript/first_steps/was_ist_javascript/index.html b/files/de/learn/javascript/first_steps/was_ist_javascript/index.html deleted file mode 100644 index 247b4744c5..0000000000 --- a/files/de/learn/javascript/first_steps/was_ist_javascript/index.html +++ /dev/null @@ -1,339 +0,0 @@ ---- -title: Was ist JavaScript? -slug: Learn/JavaScript/First_steps/Was_ist_JavaScript -translation_of: Learn/JavaScript/First_steps/What_is_JavaScript ---- -
{{LearnSidebar}}
- -
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
- -

Willkommen zum MDN-Einsteigerkurs für JavaScript! Im ersten Artikel werden wir uns JavaScript von aussen anschauen und Fragen beantworten wie "Was ist das?" oder  "Was macht das?", und wir stellen sicher, das du weißt was JavaScript ist.

- - - - - - - - - - - - -
Voraussetzungen:Umgang mit einem Computer und ein Grundverständniss von HTML und CSS
Thema:JavaScript kennenlernen, was JavaScript tun kann und wie es in einer Webseite arbeitet.
- -

Eine Experten Definition

- -

JavaScript ist eine Programmiersprache mit der sich komplexe Programme in eine Webseite realisieren lassen. Immer wenn eine Webseite mehr macht als nur statische Informationen anzuzeigen, (zum Beispiel:

- - - -

kannst du dir sicher sein das JavaScript benutzt wurde. Es ist die Dritte der Drei Standard-Technologien im Web, die anderen beiden ( HTML und CSS ) werden in anderen Bereichen des MDN eingeführt und referenziert.

- -

- - - -

Die drei Teile bauen gut auf einander auf. Hier mal ein einfaches Beispiel: Wir können zunächst HTML benutzten, um eine Struktur zu bauen.

- -
<p>Player 1: Chris</p>
- -

- -

Anschließend können wir mit einigen CSS-Regeln denn Satz schön aussehen lassen:

- -
p {
-  font-family: 'helvetica neue', helvetica, sans-serif;
-  letter-spacing: 1px;
-  text-transform: uppercase;
-  text-align: center;
-  border: 2px solid rgba(0,0,200,0.6);
-  background: rgba(0,0,200,0.3);
-  color: rgba(0,0,200,0.6);
-  box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
-  border-radius: 10px;
-  padding: 3px 10px;
-  display: inline-block;
-  cursor:pointer;
-}
- -

- -

Und zum Schluss können wir mit etwas JavaScript eine Reaktion auf das Klicken des Benutzers implementieren:

- -
var para = document.querySelector('p');
-
-para.addEventListener('click', updateName);
-
-function updateName() {
-  var name = prompt('Enter a new name');
-  para.textContent = 'Player 1: ' + name;
-}
-
- -

{{ EmbedLiveSample('A_high-level_definition', '100%', 80) }}

- -

Klick auf das Label und sieh, was passiert (den Code findest du auf GitHub und hier kannst du es in Aktion sehen).

- -

So und was kann ich jetzt damit machen?

- -

Der Kern von JavaScript ähnelt dem anderer Programmiersprachen. In JavaScript kannst du:

- - - -

Aber es gibt noch andere Funktionen die auf dem Kern von JavaScript aufbauen. Die sogenannten Application Programming Interfaces (APIs) geben dir noch mehr Funktionen mit denen du deine Projekte aufbessern kann.

- -

APIs sind von anderen Programmieren geschriebener Code die dir mehr Möglichkeiten geben für dein Programm. Die für dich schwer oder unmöglich wären selber zu programmieren. Sie sind das gleiche was Werkzeuge und Material für Handwerker sind. Es wäre deutlich schwerer alleine erst alle Werkzeuge und dann alle Materiallien herzustellen.

- -

Die APIs kann man generell in zwei Kategorien einteilen:

- -

- -

Browser APIs sind vom Webbrowser des Benutzers. Und sie können auf Ressourcen des computers zugreifen, oder erledigen Dinge die sehr komlpex sind. Ein paar Beispiele:

- - - -
-

Notiz: Viele der oben genannten Beispiele funktionieren in älteren Browsern nicht — wenn du dein Code ausprobieren willst, dann ist es eine gute Idee einen Modernen Browser wie Firefox, Chrome, Edge oder Opera zu benutzen. Es wird trotzdem nötig sein, sich mit Cross Browser Testing auseinander zu setzen, wenn es näher an eine Produktionssystem gehen soll(z.B. Echter Code die echte Kunden benutzen sollen).

-
- -

Drittanbieter-APIssind nicht standardmäßig im Browser integriert, und du wirst großenteils deren Code und Informationen von wo anders finden müssen. Zum Beispiel

- - - -
-

Notiz: Diese APIs sind sehr fortschrittlich und werden in diesem Modul nicht weiter behandelt.Du findest weitere Informationen bei unseren ModulClientbasierte Web APIs Modul.

-
- -

Es sind noch viele weitere APIs Verfügbar! Trotzdem werde jetzt nicht zu aufgeregt, denn du wirst es nicht schaffen, das nächste Facebook, Google Maps, oder Instagram zu entwickeln, nach gerade mal 24 Stunden JavaScript lernen — es gibt nämlich noch viele Sachen die Behandelt werden müssen. Und deswegen bist du hier — also lass uns weiter machen!

- -

Was genau macht JavaScript auf deiner Webseite?

- -

Here we'll start actually looking at some code, and while doing so explore what actually happens when you run some JavaScript in your page.

- -

Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

- -

- -

The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.

- -

This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS was there to affect, then errors would occur.

- -

Browser Sicherheit

- -

Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.

- -
-

Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.

-
- -

JavaScript running order

- -

When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:

- -
var para = document.querySelector('p');
-
-para.addEventListener('click', updateName);
-
-function updateName() {
-  var name = prompt('Enter a new name');
-  para.textContent = 'Player 1: ' + name;
-}
- -

Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5–8) is run. The updateName() code block (these types of reusable code block are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.

- -

If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — TypeError: para is undefined. This means that the para object does not exist yet, so we can't add an event listener to it.

- -
-

Note: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.

-
- -

Interpreted versus compiled code

- -

You might hear the terms interpreted and compiled in the context of programming. JavaScript is an interpreted language — the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

- -

Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example C/C++ are compiled into assembly language that is then run by the computer.

- -

Both approaches have different advantages, which we won't discuss at this point.

- -

Server-side versus client-side code

- -

You might also hear the terms server-side and client-side code, specially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this JavaScript module we are explicitly talking about client-side JavaScript.

- -

Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, and ASP.NET. And JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find more out about server-side JavaScript in our Dynamic Websites – Server-side programming topic.

- -

The word dynamic is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, inserting data requested from the server into it, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.

- -

A web page with no dynamically updating content is referred to as static — it just shows the same content all the time.

- -

How do you add JavaScript to your page?

- -

JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.

- -

Internal JavaScript

- -
    -
  1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
  2. -
  3. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
  4. -
  5. Next, go to your text editor and add the following just before your closing </body> tag: -
    <script>
    -
    -  // JavaScript goes here
    -
    -</script>
    -
  6. -
  7. Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line: -
    function createParagraph() {
    -  var para = document.createElement('p');
    -  para.textContent = 'You clicked the button!';
    -  document.body.appendChild(para);
    -}
    -
    -var buttons = document.querySelectorAll('button');
    -
    -for (var i = 0; i < buttons.length ; i++) {
    -  buttons[i].addEventListener('click', createParagraph);
    -}
    -
  8. -
  9. Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.
  10. -
- -
-

Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html file? Did you add your {{htmlelement("script")}} element just before the </body> tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.

-
- -
-

Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too).

-
- -

External JavaScript

- -

This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.

- -
    -
  1. First, create a new file in the same directory as your sample HTML file. Call it script.js — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
  2. -
  3. Next, copy all of the script out of your current {{htmlelement("script")}} element and paste it into the .js file. Save that file.
  4. -
  5. Now replace your current {{htmlelement("script")}} element with the following: -
    <script src="script.js"></script>
    -
  6. -
  7. Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got the JavaScript in an external file. This is generally a good thing in terms of organizing your code, and making it reusable across multiple HTML files. Plus the HTML is easier to read without huge chunks of script dumped in it.
  8. -
- -

Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).

- -

Inline JavaScript handlers

- -

Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:

- -
function createParagraph() {
-  var para = document.createElement('p');
-  para.textContent = 'You clicked the button!';
-  document.body.appendChild(para);
-}
- -
<button onclick="createParagraph()">Click me!</button>
- -

You can try this version of our demo below.

- -

{{ EmbedLiveSample('Inline_JavaScript_handlers', '100%', 150) }}

- -

This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline onclick handler to make the function run when the button is pressed.

- -

Please don't do this, however. It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()" attribute on every button you wanted the JavaScript to apply to.

- -

Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:

- -
var buttons = document.querySelectorAll('button');
-
-for (var i = 0; i < buttons.length ; i++) {
-  buttons[i].addEventListener('click', createParagraph);
-}
- -

This might look a bit longer than the onclick attribute, but this will work for all buttons no matter how many are on the page, and how many are added or removed. The JavaScript does not need to be changed.

- -
-

Note: Try editing your version of apply-javascript.html and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?

-
- -

Comments

- -

As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after 6 months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:

- - - -

So for example, we could annotate our last demo's JavaScript with comments like so:

- -
// Function: creates a new paragraph and append it to the bottom of the HTML body.
-
-function createParagraph() {
-  var para = document.createElement('p');
-  para.textContent = 'You clicked the button!';
-  document.body.appendChild(para);
-}
-
-/*
-  1. Get references to all the buttons on the page and sort them in an array.
-  2. Loop through all the buttons and add a click event listener to each one.
-
-  When any button is pressed, the createParagraph() function will be run.
-*/
-
-var buttons = document.querySelectorAll('button');
-
-for (var i = 0; i < buttons.length ; i++) {
-  buttons[i].addEventListener('click', createParagraph);
-}
- -

Summary

- -

So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript, and what kind of things you can do with it. Along the way you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.

- -

JavaScript may seem a bit daunting right now, but don't worry — in this course we will take you through it in simple steps that will make sense going forward. In the next article we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.

- -

In this module

- - - -

{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}

diff --git a/files/de/learn/javascript/first_steps/what_is_javascript/index.html b/files/de/learn/javascript/first_steps/what_is_javascript/index.html new file mode 100644 index 0000000000..247b4744c5 --- /dev/null +++ b/files/de/learn/javascript/first_steps/what_is_javascript/index.html @@ -0,0 +1,339 @@ +--- +title: Was ist JavaScript? +slug: Learn/JavaScript/First_steps/Was_ist_JavaScript +translation_of: Learn/JavaScript/First_steps/What_is_JavaScript +--- +
{{LearnSidebar}}
+ +
{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}
+ +

Willkommen zum MDN-Einsteigerkurs für JavaScript! Im ersten Artikel werden wir uns JavaScript von aussen anschauen und Fragen beantworten wie "Was ist das?" oder  "Was macht das?", und wir stellen sicher, das du weißt was JavaScript ist.

+ + + + + + + + + + + + +
Voraussetzungen:Umgang mit einem Computer und ein Grundverständniss von HTML und CSS
Thema:JavaScript kennenlernen, was JavaScript tun kann und wie es in einer Webseite arbeitet.
+ +

Eine Experten Definition

+ +

JavaScript ist eine Programmiersprache mit der sich komplexe Programme in eine Webseite realisieren lassen. Immer wenn eine Webseite mehr macht als nur statische Informationen anzuzeigen, (zum Beispiel:

+ + + +

kannst du dir sicher sein das JavaScript benutzt wurde. Es ist die Dritte der Drei Standard-Technologien im Web, die anderen beiden ( HTML und CSS ) werden in anderen Bereichen des MDN eingeführt und referenziert.

+ +

+ + + +

Die drei Teile bauen gut auf einander auf. Hier mal ein einfaches Beispiel: Wir können zunächst HTML benutzten, um eine Struktur zu bauen.

+ +
<p>Player 1: Chris</p>
+ +

+ +

Anschließend können wir mit einigen CSS-Regeln denn Satz schön aussehen lassen:

+ +
p {
+  font-family: 'helvetica neue', helvetica, sans-serif;
+  letter-spacing: 1px;
+  text-transform: uppercase;
+  text-align: center;
+  border: 2px solid rgba(0,0,200,0.6);
+  background: rgba(0,0,200,0.3);
+  color: rgba(0,0,200,0.6);
+  box-shadow: 1px 1px 2px rgba(0,0,200,0.4);
+  border-radius: 10px;
+  padding: 3px 10px;
+  display: inline-block;
+  cursor:pointer;
+}
+ +

+ +

Und zum Schluss können wir mit etwas JavaScript eine Reaktion auf das Klicken des Benutzers implementieren:

+ +
var para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  var name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+
+ +

{{ EmbedLiveSample('A_high-level_definition', '100%', 80) }}

+ +

Klick auf das Label und sieh, was passiert (den Code findest du auf GitHub und hier kannst du es in Aktion sehen).

+ +

So und was kann ich jetzt damit machen?

+ +

Der Kern von JavaScript ähnelt dem anderer Programmiersprachen. In JavaScript kannst du:

+ + + +

Aber es gibt noch andere Funktionen die auf dem Kern von JavaScript aufbauen. Die sogenannten Application Programming Interfaces (APIs) geben dir noch mehr Funktionen mit denen du deine Projekte aufbessern kann.

+ +

APIs sind von anderen Programmieren geschriebener Code die dir mehr Möglichkeiten geben für dein Programm. Die für dich schwer oder unmöglich wären selber zu programmieren. Sie sind das gleiche was Werkzeuge und Material für Handwerker sind. Es wäre deutlich schwerer alleine erst alle Werkzeuge und dann alle Materiallien herzustellen.

+ +

Die APIs kann man generell in zwei Kategorien einteilen:

+ +

+ +

Browser APIs sind vom Webbrowser des Benutzers. Und sie können auf Ressourcen des computers zugreifen, oder erledigen Dinge die sehr komlpex sind. Ein paar Beispiele:

+ + + +
+

Notiz: Viele der oben genannten Beispiele funktionieren in älteren Browsern nicht — wenn du dein Code ausprobieren willst, dann ist es eine gute Idee einen Modernen Browser wie Firefox, Chrome, Edge oder Opera zu benutzen. Es wird trotzdem nötig sein, sich mit Cross Browser Testing auseinander zu setzen, wenn es näher an eine Produktionssystem gehen soll(z.B. Echter Code die echte Kunden benutzen sollen).

+
+ +

Drittanbieter-APIssind nicht standardmäßig im Browser integriert, und du wirst großenteils deren Code und Informationen von wo anders finden müssen. Zum Beispiel

+ + + +
+

Notiz: Diese APIs sind sehr fortschrittlich und werden in diesem Modul nicht weiter behandelt.Du findest weitere Informationen bei unseren ModulClientbasierte Web APIs Modul.

+
+ +

Es sind noch viele weitere APIs Verfügbar! Trotzdem werde jetzt nicht zu aufgeregt, denn du wirst es nicht schaffen, das nächste Facebook, Google Maps, oder Instagram zu entwickeln, nach gerade mal 24 Stunden JavaScript lernen — es gibt nämlich noch viele Sachen die Behandelt werden müssen. Und deswegen bist du hier — also lass uns weiter machen!

+ +

Was genau macht JavaScript auf deiner Webseite?

+ +

Here we'll start actually looking at some code, and while doing so explore what actually happens when you run some JavaScript in your page.

+ +

Let's briefly recap the story of what happens when you load a web page in a browser (first talked about in our How CSS works article). When you load a web page in your browser, you are running your code (the HTML, CSS, and JavaScript) inside an execution environment (the browser tab). This is like a factory that takes in raw materials (the code) and outputs a product (the web page).

+ +

+ +

The JavaScript is executed by the browser's JavaScript engine, after the HTML and CSS have been assembled and put together into a web page. This ensures that the structure and style of the page are already in place by the time the JavaScript starts to run.

+ +

This is a good thing, as a very common use of JavaScript is to dynamically modify HTML and CSS to update a user interface, via the Document Object Model API (as mentioned above). If the JavaScript loaded and tried to run before the HTML and CSS was there to affect, then errors would occur.

+ +

Browser Sicherheit

+ +

Each browser tab is its own separate bucket for running code in (these buckets are called "execution environments" in technical terms) — this means that in most cases the code in each tab is run completely separately, and the code in one tab cannot directly affect the code in another tab — or on another website. This is a good security measure — if this were not the case, then pirates could start writing code to steal information from other websites, and other such bad things.

+ +
+

Note: There are ways to send code and data between different websites/tabs in a safe manner, but these are advanced techniques that we won't cover in this course.

+
+ +

JavaScript running order

+ +

When the browser encounters a block of JavaScript, it generally runs it in order, from top to bottom. This means that you need to be careful what order you put things in. For example, let's return to the block of JavaScript we saw in our first example:

+ +
var para = document.querySelector('p');
+
+para.addEventListener('click', updateName);
+
+function updateName() {
+  var name = prompt('Enter a new name');
+  para.textContent = 'Player 1: ' + name;
+}
+ +

Here we are selecting a text paragraph (line 1), then attaching an event listener to it (line 3) so that when the paragraph is clicked, the updateName() code block (lines 5–8) is run. The updateName() code block (these types of reusable code block are called "functions") asks the user for a new name, and then inserts that name into the paragraph to update the display.

+ +

If you swapped the order of the first two lines of code, it would no longer work — instead, you'd get an error returned in the browser developer console — TypeError: para is undefined. This means that the para object does not exist yet, so we can't add an event listener to it.

+ +
+

Note: This is a very common error — you need to be careful that the objects referenced in your code exist before you try to do stuff to them.

+
+ +

Interpreted versus compiled code

+ +

You might hear the terms interpreted and compiled in the context of programming. JavaScript is an interpreted language — the code is run from top to bottom and the result of running the code is immediately returned. You don't have to transform the code into a different form before the browser runs it.

+ +

Compiled languages on the other hand are transformed (compiled) into another form before they are run by the computer. For example C/C++ are compiled into assembly language that is then run by the computer.

+ +

Both approaches have different advantages, which we won't discuss at this point.

+ +

Server-side versus client-side code

+ +

You might also hear the terms server-side and client-side code, specially in the context of web development. Client-side code is code that is run on the user's computer — when a web page is viewed, the page's client-side code is downloaded, then run and displayed by the browser. In this JavaScript module we are explicitly talking about client-side JavaScript.

+ +

Server-side code on the other hand is run on the server, then its results are downloaded and displayed in the browser. Examples of popular server-side web languages include PHP, Python, Ruby, and ASP.NET. And JavaScript! JavaScript can also be used as a server-side language, for example in the popular Node.js environment — you can find more out about server-side JavaScript in our Dynamic Websites – Server-side programming topic.

+ +

The word dynamic is used to describe both client-side JavaScript, and server-side languages — it refers to the ability to update the display of a web page/app to show different things in different circumstances, generating new content as required. Server-side code dynamically generates new content on the server, e.g. pulling data from a database, whereas client-side JavaScript dynamically generates new content inside the browser on the client, e.g. creating a new HTML table, inserting data requested from the server into it, then displaying the table in a web page shown to the user. The meaning is slightly different in the two contexts, but related, and both approaches (server-side and client-side) usually work together.

+ +

A web page with no dynamically updating content is referred to as static — it just shows the same content all the time.

+ +

How do you add JavaScript to your page?

+ +

JavaScript is applied to your HTML page in a similar manner to CSS. Whereas CSS uses {{htmlelement("link")}} elements to apply external stylesheets and {{htmlelement("style")}} elements to apply internal stylesheets to HTML, JavaScript only needs one friend in the world of HTML — the {{htmlelement("script")}} element. Let's learn how this works.

+ +

Internal JavaScript

+ +
    +
  1. First of all, make a local copy of our example file apply-javascript.html. Save it in a directory somewhere sensible.
  2. +
  3. Open the file in your web browser and in your text editor. You'll see that the HTML creates a simple web page containing a clickable button.
  4. +
  5. Next, go to your text editor and add the following just before your closing </body> tag: +
    <script>
    +
    +  // JavaScript goes here
    +
    +</script>
    +
  6. +
  7. Now we'll add some JavaScript inside our {{htmlelement("script")}} element to make the page do something more interesting — add the following code just below the "// JavaScript goes here" line: +
    function createParagraph() {
    +  var para = document.createElement('p');
    +  para.textContent = 'You clicked the button!';
    +  document.body.appendChild(para);
    +}
    +
    +var buttons = document.querySelectorAll('button');
    +
    +for (var i = 0; i < buttons.length ; i++) {
    +  buttons[i].addEventListener('click', createParagraph);
    +}
    +
  8. +
  9. Save your file and refresh the browser — now you should see that when you click the button, a new paragraph is generated and placed below.
  10. +
+ +
+

Note: If your example doesn't seem to work, go through the steps again and check that you did everything right. Did you save your local copy of the starting code as a .html file? Did you add your {{htmlelement("script")}} element just before the </body> tag? Did you enter the JavaScript exactly as shown? JavaScript is case sensitive, and very fussy, so you need to enter the syntax exactly as shown, otherwise it may not work.

+
+ +
+

Note: You can see this version on GitHub as apply-javascript-internal.html (see it live too).

+
+ +

External JavaScript

+ +

This works great, but what if we wanted to put our JavaScript in an external file? Let's explore this now.

+ +
    +
  1. First, create a new file in the same directory as your sample HTML file. Call it script.js — make sure it has that .js filename extension, as that's how it is recognized as JavaScript.
  2. +
  3. Next, copy all of the script out of your current {{htmlelement("script")}} element and paste it into the .js file. Save that file.
  4. +
  5. Now replace your current {{htmlelement("script")}} element with the following: +
    <script src="script.js"></script>
    +
  6. +
  7. Save and refresh your browser, and you should see the same thing! It works just the same, but now we've got the JavaScript in an external file. This is generally a good thing in terms of organizing your code, and making it reusable across multiple HTML files. Plus the HTML is easier to read without huge chunks of script dumped in it.
  8. +
+ +

Note: You can see this version on GitHub as apply-javascript-external.html and script.js (see it live too).

+ +

Inline JavaScript handlers

+ +

Note that sometimes you'll come across bits of actual JavaScript code living inside HTML. It might look something like this:

+ +
function createParagraph() {
+  var para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+ +
<button onclick="createParagraph()">Click me!</button>
+ +

You can try this version of our demo below.

+ +

{{ EmbedLiveSample('Inline_JavaScript_handlers', '100%', 150) }}

+ +

This demo has exactly the same functionality as in the previous two sections, except that the {{htmlelement("button")}} element includes an inline onclick handler to make the function run when the button is pressed.

+ +

Please don't do this, however. It is bad practice to pollute your HTML with JavaScript, and it is inefficient — you'd have to include the onclick="createParagraph()" attribute on every button you wanted the JavaScript to apply to.

+ +

Using a pure JavaScript construct allows you to select all the buttons using one instruction. The code we used above to serve this purpose looks like this:

+ +
var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

This might look a bit longer than the onclick attribute, but this will work for all buttons no matter how many are on the page, and how many are added or removed. The JavaScript does not need to be changed.

+ +
+

Note: Try editing your version of apply-javascript.html and add a few more buttons into the file. When you reload, you should find that all of the buttons when clicked will create a paragraph. Neat, huh?

+
+ +

Comments

+ +

As with HTML and CSS, it is possible to write comments into your JavaScript code that will be ignored by the browser, and exist simply to provide instructions to your fellow developers on how the code works (and you, if you come back to your code after 6 months and can't remember what you did). Comments are very useful, and you should use them often, particularly for larger applications. There are two types:

+ + + +

So for example, we could annotate our last demo's JavaScript with comments like so:

+ +
// Function: creates a new paragraph and append it to the bottom of the HTML body.
+
+function createParagraph() {
+  var para = document.createElement('p');
+  para.textContent = 'You clicked the button!';
+  document.body.appendChild(para);
+}
+
+/*
+  1. Get references to all the buttons on the page and sort them in an array.
+  2. Loop through all the buttons and add a click event listener to each one.
+
+  When any button is pressed, the createParagraph() function will be run.
+*/
+
+var buttons = document.querySelectorAll('button');
+
+for (var i = 0; i < buttons.length ; i++) {
+  buttons[i].addEventListener('click', createParagraph);
+}
+ +

Summary

+ +

So there you go, your first step into the world of JavaScript. We've begun with just theory, to start getting you used to why you'd use JavaScript, and what kind of things you can do with it. Along the way you saw a few code examples and learned how JavaScript fits in with the rest of the code on your website, amongst other things.

+ +

JavaScript may seem a bit daunting right now, but don't worry — in this course we will take you through it in simple steps that will make sense going forward. In the next article we will plunge straight into the practical, getting you to jump straight in and build your own JavaScript examples.

+ +

In this module

+ + + +

{{NextMenu("Learn/JavaScript/First_steps/A_first_splash", "Learn/JavaScript/First_steps")}}

-- cgit v1.2.3-54-g00ecf