Lesson 01
- 1. childNodes[]
firstChild[] lastChild[]
BODY
DIV UL
LI LILI
parentNodes[]
previousSibling previousSibling
nextSibling nextSibling
firstElementChild
lastElementChild
nextElementSibling
previousElementSibling
getElementsByTagName
getElementById
getElementsByClassName
http://webclass.polyn.kiae.su/classes/homef.htm
Значения свойств:
href: http://webclass.polyn.kiae.su/classes/homef.htm
protocol: http:
hostname: webclass.polyn.kiae.su
host: webclass.polyn.kiae.su:80
port: 80
pathname: classes/homef.htm
search:
hash:
Обращение к свойству объекта класса URL:
имя_объект_класса_URL.свойство
Например, так:
document.links[0].href
document.location.host
document.links[2].hash
Обрщение к свойству объекта класса
URL: & location
g_reEmail = /^[w.=-]+@[w.-]+.[a-z]{2,4}$/;
распознание
строки
EVENT
DOM
ШПОРА
chrome dev tool hotkeys
grouping
RegExp - object <html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251" />
<title>Регулярные выражения</title>
<script type="text/javascript">
function f(){
var a = /^w+([.-]?w+)*@w+([.-]?w+)*(.w{2,4})+$/;
var inp = document.getElementById('inp');
var verno = document.getElementById('verno');
var neverno = document.getElementById('neverno');
if(inp.value.search(a) !== -1){
verno.style.display = 'inline';
neverno.style.display = 'none';
}
else{
neverno.style.display = 'inline';
verno.style.display = 'none';
}
}
</script>
</head>
<body>
<input type="text" id="inp"/>
<div style="display:none; color:#00FF00" id="verno">Верно</div>
<div style="display:none; color:red" id="neverno">Неверно</div><br />
<input type="button" value="Отправить" onclick="f()"/>
</body>
</html>
sub = s.substring(1,4);
last_char = s.charAt(s.length – 1) - last_char = s[s.length – 1];
i = s.indexOf('a');
var string_value = String(number);
string_value = number.toString( );
var u = s.toUpperCase();
if (/[^a-zа-яs]+/gi.test(text_val)) {
$('#username_message').
text('не допустимый символ').
removeClass('mess_ok').
addClass('mess_error');
}
text_val - это вал инпута
рэг дает список не допустимых
символов, а тэст ищет эти не
допустимые
strToTest.match(/^(d{5}(-d{4})?$)|wow$/
strToTest.match(/^[a-zA-Z0-9]+$/) != null
countMatches(document.getElementById('sourceText').innerHTML,/javascript/i, 10);
function countMatches(sourceString, patternToFind, patLength) {
var result=0, pos=0;
var tempString = new String(sourceString);
while ((pos = tempString.search(patternToFind)) != -1) {
result++;
pos += patLength;
tempString = tempString.substr(pos);
}
alert("Pattern was found " + result + " times!");
}
function findMatchesWithExec(sourceString, patternToFind) {
var result;
while ((result = patternToFind.exec(sourceString)) != null) {
alert("Found a match: " + result[0] + " at position: " + result.index +
"; will search next starting at: " + patternToFind.lastIndex +
"nThe exchange part was: " + result[1] +
"nThe rest of the number was: " + result[2]);
}
}
function doExec() {
findMatchesWithExec(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/g);
}
function findMatchesGlobal(sourceString, patternToFind) {
var result = sourceString.match(patternToFind);
alert("Found a total of " + result.length + " matches: " + result.join(", "));
}
function findMatchesNonGlobal(sourceString, patternToFind) {
var result = sourceString.match(patternToFind);
alert("Found a match: " + result[0] + "nThe exchange part was: " + result[1] + "nThe rest of the number was: " + result[2]);
}
function doGlobalMatch() {
findMatchesGlobal(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/g);
}
function doNonGlobalMatch() {
findMatchesNonGlobal(document.getElementById('sourceText').innerHTML,/(d{3})-(d{4})/);
}
function replaceString(sourceString, patternToFind, strReplacement) {
var result = sourceString.replace(patternToFind,strReplacement);
document.getElementById('sourceText').innerHTML = result;
}
function replaceWithFunction(sourceString, patternToFind) {
var result = sourceString.replace(patternToFind,function() {
return "JavaScript"+gCount++;
});
document.getElementById('sourceText').innerHTML = result;
}
function doReplacement() {
replaceString(document.getElementById('sourceText').innerHTML,/javascript/gi,"JavaScript");
replaceWithFunction(document.getElementById('sourceText').innerHTML,/javascript/gi,"JavaScript");
}
var gCount=0;
match
test()
exec()
STRING
search
replace
WINDOWS.close();
WINDOWS.focus();
ЗАПУСТИТЬ/ОСТАНОВИТЬ поток
open("URL","window_name","param,...",replace);
где -URL - страница, которая будет загружена в новое окно,
window_name - имя окна, которое можно использовать в
атрибуте target в контейнерах A и FORM,
replace - позволяет при открытии окна управлять записью в
массив history
window.close();
self.close();
window.opener.close();
id=window.open();
...id.close();
function myfocus(a) {
id = window.open ("","example", "scrollbars, width=300, height=200");
if(a==1) {
id.document.open();
id.document.write("<center>Открыли окно в первый раз"); }
if(a==2) {
id.document.open();
id.document.write("<center>Открыли окно во второй раз"); }
if(a==3) {
id.focus();
id.document.open();
id.document.write("<center>Открыли окно во второй раз"); }
id.document.write("<form><input type=button
onClick='window.close();' value='Закрыть окно'></center>");
id.document.close();
}
Методы объекта Location
assign(url) - загрузить документ по данному url
reload([forceget]) - перезагрузить документ по текущему URL. Аргумент forceget - булево значение,
если оно true, то документ перезагружается всегда с сервера, если false или не указано, то браузер
может взять страницу из своего кэша.
replace(url) - заменить текущий документ на документ по указанному url. Разница, по сравнению с
assign() заключается в том, что после использования replace() - страница не записывается в истории
посещений. В частности, это значит, что посетитель не сможет использовать для возврата кнопку
браузера "Назад".
toString() - возвращает строковое представление URL для объекта Location
var idp1 = null;
function start() {
d = new Date();
window.document.c1.f1.value =
d.getHours()+":"+d.getMinutes()+":"+d.getSeconds();
idp1=setTimeout("start();",500); }
function stop() {
clearTimeout(idp1);idp1=null; }
...
<form name=c1>
Текущее время:<input name=f1 size=8>
<input type=button value="Start" onClick="if(idp1==null)start();">
<input type=button value="Stop" onClick="if(idp1!=null)stop();">
</form>
WINDOWS.STATUS
WINDOWS.LOCATION
WINDOWS.HISTORY
WINDOWS.NAVIGATOR
Программируем status:
<a href="#status" onMouseover="window.status='Jump to status description';return true;" onMouseout="window.status='Status bar programming';return true;">window.status</a>
Программируем DefaultStatus:
<body onLoad="window.defaultStatus='Status bar programming';">
<script type="text/javascript">
window.status="Some text in the status bar!!";
</script>
Свойства location:
http://kuku.ru:80/r/dir/page?search#mark
Методы location:
window.location.reload(true);
window.location.replace('#top');
<form>
<input type=button value=Назад onClick=history.back()>
</form>
<form><input type=button value="Тип навигатора" onClick="window.alert(window.navigator.userAgent);">
</form>
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506)
<script>
if(navigator.mimeTypes['image/gif']!=null) document.write("Ваш браузер поддерживает GIF<br>");
if(navigator.mimeTypes['image/kuku']==null) document.write("Ваш браузер не поддерживает KUKU");
</script>
onclick="top.location.href='1.html';" /
<input
type="button"
value="Перейти на страницу 1.html в текущем фрейме"
onclick="self.location.href='1.html';" />
<input
type="button"
value="Перейти на страницу 1.html в текущем фрейме"
onclick="top.frames['имя фрейма'].location.href='1.html';" />
NAVIGATOR HYSTORY SCREEN LOCATION DOCUMENT
forms[] anchors[] links[] images[]
опр. тип браузера urlэкранистория
открытый документ
alert()
confirm()
prompt()
open()
close()
focus()
setTimeout()
clearTimeout()
scroll()
blur()
confirm()
окно ДА/НЕТ
(return true/false )
prompt()
ввод значения в
выпадаюшем окне
window.print();
windpw.open(”hello.html”);
остановка стандартного событияe.preventDefault();Event.stop(event);
events
media
function addEventHandler(oNode, evt, oFunc, bCaptures)
{
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+evt, oFunc);
else
oNode.addEventListener(evt, oFunc, bCaptures);
}
function removeEventHandler(oNode, evt, oFunc, bCaptures) {
if (typeof (window.event) != "undefined")
oNode.detachEvent("on" + evt, oFunc);
else
oNode.removeEventListener(evt, oFunc, bCaptures);
}
function getEventTarget(e) {
if (window.event) return window.event.srcElement;
else return e.target;
}
function onLinkClicked(e) {
alert("You clicked the link!");
}
function onEnableClick(e) {
var target = getEventTarget(e);
if (target.checked)
addEventHandler(document.getElementById("clickLink"), "click",
onLinkClicked, false);
else
removeEventHandler(document.getElementById("clickLink"),
"click", onLinkClicked, false);
}
function setUpClickEvent(e) {
addEventHandler(document.getElementById("Checkbox1"), "click",
onEnableClick, false);
}
addEventHandler(window, "load", setUpClickEvent, false);
function addEventHandler(oNode, evt,
oFunc, bCaptures)
{
if (typeof(window.event) != "undefined")
oNode.attachEvent("on"+evt, oFunc);
else
oNode.addEventListener(evt, oFunc,
bCaptures);
}
function removeEventHandler(oNode, evt,
oFunc, bCaptures) {
if (typeof (window.event) != "undefined")
oNode.detachEvent("on" + evt, oFunc);
else
oNode.removeEventListener(evt, oFunc,
bCaptures);
}
function getEventTarget(e) {
if (window.event) return
window.event.srcElement;
else return e.target;
}
addEventHandler(document.getElementsByTagName("body")[0],"click",bodyHandler,true);
function bodyHandler(evt) {
var e = evt || window.event;
var target = getEventTarget(e);
var str = "Event handler for body, target: " + target.getAttribute('id') + " , type: " + e.type;
if (e.eventPhase) str+=" ; phase: " + e.eventPhase;
alert(str);
}
events
What is the type
of the event?
Which HTML element is the
target of the event?
Which HTML element is the
target of the event?
Right click
function doSomething(e) {
if (!e) var e = window.event;
alert(e.type);
}
W3C/Netscape says: the target. No, says Microsoft, the srcElement.
Both properties return the HTML element the event took place on.
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
function doSomething(e) {
var code;
if (!e) var e = window.event;
if (e.keyCode) code = e.keyCode;
else if (e.which) code = e.which;
var character = String.fromCharCode(code);
alert('Character was ' + character);
}
function doSomething(e) {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
alert('Rightclick: ' + rightclick); // true or false
}
Mouse position
1. clientX,clientY
2. layerX,layerY
3. offsetX,offsetY
4. pageX,pageY
5. screenX,screenY
6. x,y
Correct script
This is the correct script for detecting the mouse coordinates:
function doSomething(e) {
var posx = 0;
var posy = 0;
if (!e) var e = window.event;
if (e.pageX || e.pageY) {
posx = e.pageX;
posy = e.pageY;
}
else if (e.clientX || e.clientY) {
posx = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
// posx and posy contain the mouse position relative to the document
// Do something with this information
}
http://www.quirksmode.org/js/events_properties.html
// Get the element, add a click listener...
document.querySelector('#parent-list').addEventListener('click', function(e) {
// e.target is the clicked element!
// If it was a list item
if(e.target && e.target.tagName == 'LI') {
// List item found! Do something now!
}
});
COOKIES
<form> <input type=button value="Показать Cookies" onClick="window.alert(window.document.cookie);"> </form>
function change_cookies() {
a = new Array();
c = new Date();
a = document.cookie.split(';');
document.cookie=a[0]+"; expires="+c.toGMTString()+";"
window.alert(document.cookie);
...
<form>
<input type=button value="Чтобы не хранить этот хлам вечно" onClick="change_cookies()">
</form>
function asign()
{
document.cookie="n1=3";
window.alert(document.cookie);
}
...
<form>
<input type=button value="Изменить n1" onClick="asign()">
</form>
<form>
<input type=button value="Показать Cookies" onClick="window.alert(window.document.cookie);">
</form>
<style type="text/css">
div{
padding-bottom:5px;
}
</style>
<script type="text/javascript">
function f(){
var namecom = document.getElementById('namecom');
var email = document.getElementById('email');
var site = document.getElementById('site');
document.cookie = 'namecom=' + encodeURIComponent(namecom.value) + '; max-age=' + (365*24*60*60) + '; path=/';
document.cookie = 'email=' + encodeURIComponent(email.value) + '; max-age=' + (365*24*60*60) + '; path=/';
document.cookie = 'site=' + encodeURIComponent(site.value) + '; max-age=' + (365*24*60*60) + '; path=/';
}
function opencookie(par){
var allcookies = document.cookie;
var pos = allcookies.indexOf(par);
var dlina = par.length;
if(pos !== -1){
var start = pos + dlina + 1;
var end = allcookies.indexOf(';', start);
if (end == -1)
end = allcookies.length;
var znachenie = allcookies.substring(start, end);
znachenie = decodeURIComponent(znachenie);
this.cooka = znachenie;
}
}
function z(){
alert('Содержимое cookies' + document.cookie);
if (document.cookie !== ''){
var namecomcooka = new opencookie('namecom');
alert(namecomcooka.cooka);
var emailcooka = new opencookie('email');
alert(emailcooka.cooka);
var sitecooka = new opencookie('site');
alert(sitecooka.cooka);
var namecom = document.getElementById('namecom');
var email = document.getElementById('email');
var site = document.getElementById('site');
namecom.value = namecomcooka.cooka;
email.value = emailcooka.cooka;
site.value = sitecooka.cooka;
}
}
</script>
</head>
<body onload="z()">
<p>Форма с полями ввода:</p>
<div><input type="text" id="namecom"/> Имя</div>
<div><input type="text" id="email"/> E-mail</div>
<div><input type="text" id="site"/> Сайт</div>
<div><input type="button" value="Отправить" onclick="f()"/></div>
</body>
document.querySelector or document.querySelectorAll
ООП
Объекты
extending
Array.prototype.longestElement =
function() {
var maxLength = 0;
for (var i=0; i < this.length; i++) {
if (this[i].toString().length > maxLength)
maxLength = this[i].toString().length;
}
return maxLength;
}
inheritancefunction Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return (this.width * this.height);
}
Rectangle.prototype.toString = function() {
return "Rectangle of width: " + this.width + " and height: " + this.height;
}
Rectangle.prototype.valueOf = function() {
return this.area();
}
Rectangle.prototype.equals = function(oRect) {
return (this.width == oRect.width && this.height == oRect.height);
}
Rectangle.prototype.compareTo = function(oRect) {
return (this.area() - oRect.area());
}
function DepthRectangle(w,h,d) {
Rectangle.call(this,w,h);
this.depth = d;
}
DepthRectangle.prototype = new Rectangle();
DepthRectangle.prototype.constructor = DepthRectangle;
DepthRectangle.prototype.volume = function() {
return (this.area() * this.depth);
}
DepthRectangle.prototype.toString = function() {
return "DepthRectangle with width: " + this.width + " & height: " + this.height + " & depth: " + this.depth;
}
var myRect = new Rectangle(5,6);
var myDeepRect = new DepthRectangle(7,8,9);
alert(myDeepRect.volume());
alert(myDeepRect.area());
alert(myRect instanceof DepthRectangle);
function Bird(name) {
this.name = name;
}
Bird.prototype.flighted = true; // Default for all Birds
Bird.prototype.isFlighted = function () { return this.flighted };
Bird.prototype.getName = function () { return this.name };
function Chicken(name) {
// Chain the constructors
Chicken.superclass.constructor.call(this, name);
}
приятно
знать
function include(file,scriptStack) {
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
if(scriptStack == 'async' && elemHasAttribute('script','async'))
script.async = true;
else if(scriptStack == 'defer')
script.defer = true;
document.getElementsByTagName('head')[0].appendChild(script);
debuggStack({'msg':'script.js(47): include '+file});
};
//Include js file with callback function
function includeWithCallBack(file, callback) {
var script = document.createElement('script');
script.src = file;
script.type = 'text/javascript';
document.getElementsByTagName('head')[0].appendChild(script);
script.onreadystatechange = function() {
if(script.readyState == "complete" || script.readyState=="loaded") {
script.onreadystatechange = false;
callback;
} else {
script.onload = function() {
callback;
};
}
};
};
function elemHasAttribute(elementName,attribute){
var element = document.createElement(elementName);
return attribute in element;
};
HTML5 feature detection
Include script
Cheack attribute
function hasColorSupport(){
input = document.createElement("input" );
input.setAttribute("type" , "color" );
var hasColorType = (input.type !== "text" );
// handle Safari/Chrome partial implementation
if(hasColorType){
var testString = "foo" ;
input.value=testString;
hasColorType = (input.value != testString);
}
return(hasColorType);
}`
function hasAutofocus() {
var element = document.createElement('input' );
return 'autofocus' in element;
}
$(function(){
if(!hasAutofocus()){
$('input[autofocus=true]' ).focus();
}
});
var frag = document.createDocumentFragment();
local & Session
storage $.fn.autosave = function(prefix){
var storage = localStorage; // or sessionStorage
var $this = $(this);
if(!prefix){ prefix = $this.attr('id'); }
prefix += ">"; // Separate prefix from input name;
function save(){
console.log('save')
$this.find('input:not(:password,
:submit)').each(function(index, element){
var key = prefix + element.name;
storage.setItem(key, $(element).val());
})
};
function restore(){
var i, key, value, name;
for(i=0; i < storage.length; i++){
key = storage.key(i);
if(0 === key.indexOf(prefix)){
value = storage.getItem(key);
name = key.replace(prefix, '');
$this.find('[name='+name+']').val(value);
}
}
};
function clear(e){
var keys = [], i, key;
// Collect Keys;
for(i=0; i < storage.length; i++){
key = storage.key(i);
if(0 === key.indexOf(prefix)){
keys.push(key);
}
}
// Remove Each Key
for(i=0; i < keys.length; i++ ){
storage.removeItem(keys[i]);
}
};
$this.change(save);
$this.submit(clear);
restore();
console.log('DONE')
$(document).ready(function() {
if (window.localStorage) {
var fromDb = localStorage.getItem("courses");
if (fromDb) {
// Read the courses from local storage, into the
global "courses" array.
courses = JSON.parse(fromDb);
}
else {
// Store the global "courses" array into local
storage.
storeCourses();
}
}
});
// Stores the global "courses" array into local
storage.
function storeCourses() {
if (window.localStorage) {
localStorage.setItem("courses",
JSON.stringify(courses));
}
}
HTML5 REF
Events
style
origin
Elems
Elems Attr
DOM
Exeptions
Categories
©Trybynenko Andrii