JavaScript Referenz

Aus MattWiki
Version vom 27. März 2022, 20:05 Uhr von Matt (Diskussion | Beiträge)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)

Diese Seite enthält allgemeingültige Listings für diverse Aufgabenstellungen in Javascript.

Grundlagen und Referenzen der JavaScript Programmiersprache selbst siehe JavaScript Linkliste

Messageboxen

Prompt Alert Message(?)


Grundlagen

Operatoren

Strikter Vergleich mit === prüft, ob Wertinhalt und Datentyp stimmen.

if (typeof partnerRole === "undefined") {

}

Objektorientierung Basic Knowledge

Everything in JavaScript acts like an object, with the only two exceptions being null and undefined.


Functions

Definition

function myFunction() {
  alert("Calling a Function!");
}

myFunction();
//Alerts "Calling a Function!"

Functions with Parameters

function sayHello(name) {
   alert("Hi, " + name);
}

sayHello("David");
//Alerts "Hi, David"


Objects

Definition via Object Literal

Constructor Function

Methods


Arrays

Der empfohlene Weg zur Anlage von Arrays ist mittels Array Literal:

Anlage mit Array Literal

 
var courses = ["HTML", "CSS", "JS"];

Anlegen mit Konstruktor

 
var courses = new Array("HTML", "CSS", "JS");


 
 var courses = new Array(3);
courses[0] = "HTML";
courses[1] = "CSS";
courses[2] = "JS";

Die Zahl der Elemente in der Arraydefinition kann auch weggelassen werden.

Associative Arrays

JavaScript unterstützt assoziative Arrays nicht direkt.

Allerdings kann man ein leeres Array anlegen. Darin kann man mit der nachfolgen Weise neue Objekte in diesem Array anlegen. Im Ergebnis hat dieses Array dann Eigenschaften, da es eigentlich ein Objekt ist.

 
var person = []; //empty array
person["name"] = "John";
person["age"] = 46;
document.write(person["age"]);
//Outputs "46"

Standard-Methoden von Arrays

Length(?) - oder gehört das zu Objekten?


Core Objects

Math Object

Properties:

E = Eulers Konstante PI = Kreiszahl LOG2 LOG10

Date Object

setInterval(<Funktion ohne Klammern>,<Intervall in ms>)


//Fri Jan 02 1970 00:00:00
var d1 = new Date(86400000); 

//Fri Jul 03 2019 12:34:56
var d2 = new Date("July 3, 2019 12:34:56");

//Sat Jul 08 1994 22:30:00
var d3 = new Date(94,6,8,22,30,0,0);

Hinweise:

Monate werden wie Integer gezählt:
Januar = 0
Februar = 1
Dezember = 11

JavaScript Datumsberechnungen finden in millisekunden statt. Basis ist 1. Januar 1970 00:00:00 Universal Time (UTC).
Ein Tag besteht aus 86.400.000 millisekunden.

Methoden

function printTime() {
  var d = new Date();
  var hours = d.getHours(); // Get hour from current date/time
  var mins = d.getMinutes();
  var secs = d.getSeconds();
  document.body.innerHTML = hours+":"+mins+":"+secs;
}
setInterval(printTime, 1000);

Document Object Model (DOM)

All HTML elements are objects.

Document-Objekt

Das Property innerHTML kann fast bei allen HTML-Elementen verwendet werden, um ihren Inhalt zu ändern.

document.body.innerHTML = "Hello World";

Methoden des Document-Objekts

//finds element by id, return single object
document.getElementById(id) 

//finds elements by class name, return as areay
document.getElementsByClassName(name) 

//finds elements by tag name, return as areay
document.getElementsByTagName(name)

Beispiel für einzelnes Element:

Es wird angenommen, dass folgendes HTML-Element vorliegt:

<div id="oneobject"></div>


Auf dieses wird folgendermaßen zugegriffen:

var elem = document.getElementById("oneobject");
elem.innerHTML = "Hello World!";

Beispiel für Array:

<p>Hello</p>
<p>people of the</p>
<p>world</p>
<script>
var arr = document.getElementsByTagName("p");
for (var x = 0; x < arr.length; x++) {
  arr[x].innerHTML = "Hi there";
}
</script>

Liefert drei Mal "Hi there".

Methoden von Element-Objekten

childNodes returns an array of an element's child nodes. firstChild returns the first child node of an element. lastChild returns the last child node of an element. hasChildNodes returns true if an element has any child nodes, otherwise false. nextSibling returns the next node at the same tree level. previousSibling' returns the previous node at the same tree level. parentNode returns the parent node of an element

Beispiel:

<html>
  <body>
    <div id ="particularid">
      <p>Hello World</p>
      <p>Bonjour</p>
    </div>

    <script>
     var a = document.getElementById("particularid");
     var arr = a.childNodes;
     for(var x=0;x<arr.length;x++) {
       arr[x].innerHTML = "gosh";
     }
    </script>

  </body>
</html>


Attribute von Element-Objekten

<img id="img1" src="car.png" alt="" />
<script>
var el = document.getElementById("img1");
el.src = "plane.png";
</script>

CSS-Style von Element-Objekten

Es können alle CSS Eigenschaften bearbeitet werden. Wichtig ist, dass in den Namen keine Bindestriche verwendet werden können. In diesem Falle werden die Namen mit camelCase konvertiert, d.h. Bindestriche werden entfernt, dafür wird der nachfolgende Buchstabe groß geschrieben.

<div id="demo" style="width:200px">some text</div>
<script>
  var x = document.getElementById("demo");
  x.style.color = "6600FF";
  x.style.width = "100px";
</script>


Elemente erstellen

Methoden zum erstellen neuer Elemente:

  • element.cloneNode() klont ein Element und liefert es zurück.

document.createElement(element) creates a new element node. document.createTextNode(text) creates a new text node

<div id ="demo">some content</div>

<script>
  //creating a new paragraph
  var p = document.createElement("p");
  var node = document.createTextNode("Some new text");
  //adding the text to the paragraph
  p.appendChild(node);

  var div = document.getElementById("demo");
  //adding the paragraph to the div
  div.appendChild(p);
</script>


Elemente ersetzen

element.replaceChild(newNode, oldNode) ersetzt newNode durch oldNode.


Animationen

Animationen werden mit Ändern von Properties von Elementen umgesetzt.

Folgende Methoden stehen bereit:

  • setInterval(<Aufzurufende Funktion>, <Intervall in Millisekunden>)
  • clearInterval()

This code creates a timer that calls a move() function every 500 milliseconds. Now we need to define the move() function, that changes the position of the box. However, this makes our box move to the right forever. To stop the animation when the box reaches the end of the container, we add a simple check to the move() function and use the clearInterval() method to stop the timer.


var pos = 0; 
//our box element
var box = document.getElementById("box");
var t = setInterval(move, 10);

function move() {
  if(pos >= 150) {
    clearInterval(t);
  }
  else {
    pos += 1;
    box.style.left = pos+"px";
  }
}

Events

An event handler is called which could be a function, when an event occured.

Some types of events:

  • OnClick
  • OnLoad - When an element has loaded
  • OnChange - When the content of a form element has changed


Example:

<button onclick="show()">Click Me</button>
<script>
function show() {
  alert("Hello World");
}
</script>

Events can be assigned to almost all HTML elements:

var x = document.getElementById("ArbitraryElement");
x.onclick = function () {
  document.body.innerHTML = Date();
}