Inhaltsverzeichnis

var num = 5;
var greeting = "Hallo";
var isLogged = true;
var colors = ["Rot", "Grün", "Blau"];
var person = { name: "John", age: 30 };
 
var emptyValue = null;
var undefinedValue = undefined;
var x = 5;
var y = 3;
 
var sum = x + y; // 8
var difference = x - y; // 2
var product = x * y; // 15
var quotient = x / y; // 1.6666666666666667
var remainder = x % y; // 2
 
x += 1; // x ist jetzt 6
y -= 1; // y ist jetzt 2
 
var isEqual = x == y; // false
var isGreater = x > y; // true
 
var logicalAnd = (x > 0) && (y < 10); // true
var logicalOr = (x > 0) || (y > 10); // true
var logicalNot = !isGreater; // false
 
x++; // x ist jetzt 7
y--; // y ist jetzt 1
var colors = ["Rot", "Grün", "Blau"];
 
console.log(colors[0]); // Rot
console.log(colors[1]); // Grün
 
colors.push("Gelb");
console.log(colors); // ["Rot", "Grün", "Blau", "Gelb"]
 
colors.pop();
console.log(colors); // ["Rot", "Grün", "Blau"]
var age = 18;
 
if (age >= 18) {
  console.log("Du bist volljährig.");
} else {
  console.log("Du bist minderjährig.");
}
 
 
for (var i = 0; i < 5; i++) {
  console.log(i);
}
 
var j = 0;
while (j < 5) {
  console.log(j);
  j++;
}
 
 
var day = "Montag";
 
switch (day) {
  case "Montag":
    console.log("Heute ist Montag.");
    break;
  case "Dienstag":
    console.log("Heute ist Dienstag.");
    break;
  default:
    console.log("Ein anderer Tag.");
    break;
}
function greet(name) {
  console.log("Hallo, " + name + "!");
}
 
function add(a, b) {
  return a + b;
}
 
greet("John"); // Hallo, John!
var result = add(3, 5); // 8
var person = {
  name: "John",
  age: 30,
  isStudent: true,
  greet: function() {
    console.log("Hallo, ich bin " + this.name + ".");
  }
};
 
console.log(person.name); // John
console.log(person.age); // 30
person.greet(); // Hallo, ich bin John.

Javascript ist eine Scriptsprache mit der sich das DOM Element einer Website im Browser des Besuchers bearbeiten lässt und Inhalte dynamisch nachgeladen werden können. Javascript hat dabei keinen Zugriff auf das Dateisystem des Benutzers.

Man kann HTML Elemente mit Javascript anhand ihrer „Klasse“ oder ihrer „id“ ansprechen. (siehe CSS)

var div = document.getElementById('id'); // return = html element
div = document.getElementsByClassName('class'); // return = array of html elements

XML

var domParser = new DOMParser();
var doc = domParser.parseFromString(res['content'], 'text/xml');
var div;
doc.querySelectorAll('item').forEach((item) => {
    div = document.createElement('div');
    div.innerHTML = '<a target="_blank" href="' + item.querySelector('link').textContent + '">' + item.querySelector('title').textContent + '</a>';
    document.getElementById("ajax").appendChild(div);
})

JSON

var json = JSON.parse(jsonData);
var jsonStr = JSON.stringify(jsonData);

AJAX

Ajax (Asynchronous Javascript And Xhtml) ist eine Technik wobei Inhalte von einem Server nachgeladen bzw. verändert werden nachdem die HTTP Seite fertig geladen wurde.

function ajaxGet() {
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            document.getElementById("ajax").innerHTML = this.responseText;
        }
    };
    xhttp.open("GET", "ajax.php", true);
    xhttp.send();
}

function ajaxPOST() {
    var params = "a=1&b=2&c=3";
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if(this.readyState == 4 && this.status == 200) {
            document.getElementById("ajax").innerHTML = this.responseText;
        }
    };
    xhttp.open("POST", "ajax.php", true);
    xhttp.send(params);
}

<div id="ajax">
<button type="button" onclick="ajaxGet()">Ajax</button>
</div>
function file_get_contents(filename) {
    fetch(filename).then((resp) => resp.text()).then(function(data) {
        alert(data);
    });
}

https://www.mediaevent.de/javascript/ajax-2-xmlhttprequest.html

Cookies

document.cookie = "username=manuel; expires=Thu, 12 Sep 2019 16:42:45 GMT; path=/";
console.log(document.cookie);

Local storage

// create an array
var json_arr = {};
json_arr["name1"] = "value1";
json_arr["name2"] = "value2";
json_arr["name3"] = "value3";

// convert to JSON
var json_string = JSON.stringify(json_arr);
        
// Store
localStorage.setItem("jsondata", json_string);

// Retrieve
document.getElementById("ajax").innerHTML = JSON.stringify(JSON.parse(localStorage.getItem("jsondata")));

IndexedDB

var request = indexedDB.open("MyFriends");

request.onupgradeneeded = function() {
  // The database did not previously exist, so create object stores and indexes.
  var db = request.result;
  var store = db.createObjectStore("friends", {keyPath: "id"});
  var titleIndex = store.createIndex("by_name", "name");
  var authorIndex = store.createIndex("by_phone", "phone");

  // Populate with initial data.
  store.put({name: "Leopold S", phone: "123", id: 1});
  store.put({name: "Adam E", phone: "456", id: 2});
  store.put({name: "Jango B", phone: "789", id: 3});
};

request.onsuccess = function() {
  db = request.result;
};

API

index.html

<html>
<head>
    <meta http-equiv='Content-Type' content='text/html; charset=utf-8' />
    <script src="https://cdn.zarat.ml/zquery.js"></script>   
    <style>
        .item { display:none; }
    </style>
</head>
<body>
    <a class="link" id="link1" data-value="a">Link 1</a> 
    <a class="link" id="link2" data-value="b">Link 2</a> 
    <a class="link" id="link3" data-value="c">Link 3</a>
    
    <a onclick="$('#ajax').addClass('item')">hide</a>
    <a onclick="$('#ajax').removeClass('item')">show</a>
    
    <div id="ajax" class="item">ajax</div>
    
    <script type="text/javascript">
    $(function() { console.log('ZQuery loaded!'); });
    
    var a = [1,2,3];
    $(a).each(function(e) { console.log(e); });
    
    $('.link').each(function(e) { console.log(e.id); });
    
    $('#link3').append($('#link1'));
    
    $('#link1').prepend($('#link2'));
    
    $().log($('#link1').attr('data-value'));
    
    $('#link1').append($('<a href="#" id="link0" data-value="d">Link 0</a>'));
    
    $('.link').on('click', function(e) {  
        $().ajax({ 
            method: "post", 
            action: "ajax.php", 
            contentType: 'application/x-www-form-urlencoded',
            data: 'id=' + e.target.getAttribute('data-value'),
            success: function(data) { 
                try { 
                    var res = JSON.parse(data.responseText);
                    $('#ajax').removeClass('item');
                    $('#ajax').html(res['id'] + " = " + res['value']); 
                } catch(e) { } 
            } 
        });
    });
    </script>
</body>
</html>

ajax.php

<?php 
header("Content-Type: application/json");
echo json_encode(array_merge($_REQUEST, array('value' => date('d.m.Y H:i:s'))));
?>

Image upload with preview

<input type="file" accept="image/*" onchange="loadFile(event)" multiple>
<div id="output"></div>

<script>
var loadFile = function(e) {    
    
    var output = document.getElementById('output')
    
    // delete all files
    var child = output.lastElementChild;  
    while (child) { 
        output.removeChild(child); 
        child = output.lastElementChild; 
    } 
    
    // loop over all files
    var count = e.target.files.length;
    var img;    
    for (i = 0; i < count; i++) {
        var reader = new FileReader();
        reader.onload = function(event) {
            img = new Image();
            img.src = event.target.result;
            img.style = "height: 100px; width: 100px";
            document.getElementById('output').appendChild(img);            
        }
        reader.readAsDataURL(event.target.files[i]);
    }
}
</script>

https://www.mediaevent.de/javascript/ajax-2-xmlhttprequest.html

Forms

http://jsfiddle.net/UeSsu/1/

Format

https://codepen.io/559wade/pen/LRzEjj

http://jsfiddle.net/UEVv6/2/

Sortable Lists

https://jsfiddle.net/james2doyle/q8cuM/

Dragable

https://www.kirupa.com/html5/drag.htm

https://codepen.io/LANparty/pen/wePYXb