Javascript etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster
Javascript etiketine sahip kayıtlar gösteriliyor. Tüm kayıtları göster

21 Mart 2018 Çarşamba

Javascript ve DOM

Giriş
Not : Eskiden js sadece tarayıcı üzerinde çalışırdı. Artık bu söylem doğru değil. Node.js gibi sunucu üzerinde çalışan js kütüphaneleri de var. Dolayısıyla her Javascript kütüphanesinde DOM desteği olmayabilir.

Hem Javascript hem de JQuery DOM nesnelerine erişmemize izin verirler. JQuery DOM nesnelerine # işareti ve id ile erişmemizi sağlar.
<div id="div1">Loading...</div>
<div id="div2">Loading...</div>
<script type="text/javascript">
  $(document).ready(function() {
    $("#div1").load("path/to/file.php");
    $("#div2").load("path/to/file.php");
  });
</script>
Javascript ise getElementById() ile erişmemizi sağlar.
appendChild
Elimizde şöyle bir HTML olsun.
<div id="field1">
  ...
</div>
DOM'a yeni bir  nesne eklemek için şöyle yaparız.
<script>
  function add() {
    
    var div1 = document.createElement('div');
    div1.innerHTML = '...';
    document.getElementById('field1').appendChild(div1);
  
  }
</script>

addEventListener
DOM içindeki birçok event'i dinleyebiliriz. Bunun için DOM elemanını bulup addEventListener ("event tipi", metod ismi) şeklinde bir çağrı yapmak gerekir. Bir event'i dinlemekten vazgeçersek removeEventListener çağrısı yaparız.
Şöyle bir html olsun
<div id="body_visusal_editor">click to add one element</div>
Div'e tıklamayı şöyle dinleriz.
function myfunc(tag, type) {...}

var elem = document.getElementById("body_visusal_editor");
elem.addEventListener("click", myfunc())
querySelectorAll metodu
Şöyle yaparız.
var videos = document.querySelectorAll('video'),\n" +
[].forEach.call(videos, function(video) { video.muted = true; });
window
En çok karşımıza çıkan kodlar şöyle
window.location.hostname
www.google.com gibi bir çıktı verir.
HTML Eventleri
onclick
Bir çok yerde onClick olarak kullanılsa da aslında doğrusu onclick. Şöyle kullanırız. addEventListener ("click",...) yapmaktan daha kolaydır.
button.onclick = function() { doThis(arg); };

HTML Nesneleri
canvas
Elimizde şöyle bir canvas olsun
canvas id="CanvasFlynn" width="2" height="2"
 style="width: 100px; height: 100px; ..."></canvas>
Canvas'ın piksellerini şöyle doldurabiliriz.

function draw()
{
    var cnvs = document.getElementById("CanvasFlynn"); //Assume it's 2x2 pixels
    var cont  = cnvs.getContext("2d");
    var imdt  = cont.getImageData(0, 0, 2, 2);
    var r     = [ 255 , 0 , 0 , 255 ];
    var g     = [ 0 , 255 , 0 , 255 ];
    var b     = [ 0 , 0 , 255 , 255 ];
    var a     = [ 255 , 255 ,255 ,255 ];
    var index = 0;
    for ( var i = 0 ; i < imdt.data.length / 4 ; i++ )
    {
        index              = 4*i;
        imdt.data[index]   = r[i];
        imdt.data[index+1] = g[i];
        imdt.data[index+2] = b[i];
        imdt.data[index+3] = a[i];
    }
  
    cont.putImageData(imdt, 0, 0);
}
draw();
div
innerHTML
Elimizde şöyle bir html olsun
<html>
<head>
    <script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
</head>
<body>
    <button class="loadButton" value="input1.txt">Load file 1</button>
    <button class="loadButton" value="input2.txt">Load file 2</button>
    <div id="view"></div>
</body>
<script>
Bu html'deki div alanları şöyle değiştirilir.
document.getElementById("view").innerHTML = "..."
paragraph
Şöyle bir HTML olsun.
<p id="p">Hello</p>
P alanı şöyle değiştirilir.
document.getElementById('p').onclick = function() {
  this.textContent = 'Bob';
};
pre
pre div ile aynı şekilde çalışıyor. Şöyle bir HTML olsun
<pre id="output"></pre>
Bu html'deki pre alanı şöyle değiştirilir.
document.getElementById('output').innerHTML = JSON.stringify(myset, 0, 2);
table
deleteRow
Şöyle yaparız.
var id = ...;
var table = document.getElementById("table");
rowsCount = table.querySelectorAll('tr[id="' + id + '"');

for (var i = 0; i < rowsCount.length; i++) {
  table.deleteRow(rowsCount[i].rowIndex);
}
insertRow
Şöyle yaparız.
var row = table.insertRow();
row.id = ...;
var col1 = row.insertCell(0);
var col2 = row.insertCell(1);
var col3 = row.insertCell(2);

col1.innerHTML = ...;
col2.innerHTML = ...;col3.innerHTML = ...;

textarea
value
Kutunun içindeki metine erişilebilir. Elimizde şöyle bir html olsun
<html>

<body>
  <textarea id=contactMe rows=4 cols=40>Enter your comment...</textarea>
  <script src="contactBox.js">
  </script>
</body>

</html>
contact.js'nin içi de şöyle olsun. Metin kutusuna tıklanınca kutunun için silinir.
function ClearText(e) {

  //alert(document.getElementById('contactMe').value);
  if (document.getElementById('contactMe').value == 'Enter your comment...') {
    document.getElementById('contactMe').value = "";
  }

}


var x = document.getElementById('contactMe');
x.addEventListener('click', ClearText, false);



4 Temmuz 2016 Pazartesi

Javascript ve Class

Giriş
Javascript Object Model açıklaması şöyle
JavaScript is an object-based language based on prototypes, rather than being class-based. Because of this different basis, it can be less apparent how JavaScript allows you to create hierarchies of objects and to have inheritance of properties and their values.
Class-based object-oriented languages, such as Java and C++, are founded on the concept of two distinct entities: classes and instances.
  • A class defines all of the properties (considering methods and fields in Java, or members in C++, to be properties) that characterize a certain set of objects. A class is an abstract thing, rather than any particular member of the set of objects it describes. For example, the Employee class could represent the set of all employees.
  • An instance, on the other hand, is the instantiation of a class; that is, one of its members. For example, Victoria could be an instance of the Employee class, representing a particular individual as an employee. An instance has exactly the same properties of its parent class (no more, no less).
A prototype-based language, such as JavaScript, does not make this distinction: it simply has objects. A prototype-based language has the notion of a prototypical object, an object used as atemplate from which to get the initial properties for a new object. Any object can specify its own properties, either when you create it or at run time. In addition, any object can be associated as the prototype for another object, allowing the second object to share the first object's properties.
class nasıl tanımlanır
Şöyle yaparız.
class Quizer {
  constructor(quizObj) {
    this.quiz = quizObj;
  }
  print() {
    console.log(this.quiz.title);
  }
};
class nasıl yaratılır
Şöyle yaparız.
var quizObjects = { title: "Quiz1" };
var quiz = new Quizer(quizObjects);
quiz.print(); //Quiz1