Для добавления JavaScript-кода на страницу, можно использовать теги <script></script>, которые рекомендуется, но не обязательно, помещать внутри контейнера <head>. Контейнеров <script> в одном документе может быть сколько угодно. Атрибут «type=’text/javascript’» указывать необязательно, так как по умолчанию стоит javascript.
Есть и другая возможность подключения JavaScript — написать скрипт в отдельном файле, а потом подключить его с помощью конструкции
<script type="text/javascript" src="http://Путь_к_файлу_со_скриптом">
</script>
Карусель из картинок
<!-- Начало скрипта -->
<BODY onload="Carousel()" background=>
<script type="text/javascript">
// 7 variables to control behavior
var Car_Image_Width=100;
var Car_Image_Height=100;
var Car_Border=true; // true or false
var Car_Border_Color="#BCBFFF";
var Car_Speed=10;
var Car_Direction=true; // true or false
var Car_NoOfSides=6; // must be 4, 6, 8 or 12
/* array to specify images and optional links.
For 4 sided carousel specify at least 2 images
For 6 sided carousel specify at least 3
For 8 sided carousel specify at least 4
For 12 sided carousel specify at least 6
If Link is not needed keep it ""
*/
Car_Image_Sources=new Array(
"адрес картинки","",
"адрес картинки","",
"адрес картинки","",
"адрес картинки","",
"адрес картинки","",
"адрес картинки","",
"адрес картинки","",
"адрес картинки",""
// NOTE No comma after last line
);
/***************** DO NOT EDIT BELOW **********************************/
CW_I=new Array(Car_NoOfSides/2+1);C_ClcW=new Array(Car_NoOfSides/2);
C_Coef=new Array(
3*Math.PI/2,0,3*Math.PI/2,11*Math.PI/6,Math.PI/6,3*Math.PI/2,7*Math.PI/4, 0,
Math.PI/4,3*Math.PI/2,5*Math.PI/3,11*Math.PI/6,0,Math.PI/6,Math.PI/3);
var C_CoefOf=Car_NoOfSides==4?0:Car_NoOfSides==6?2:Car_NoOfSides==8?5:9;
C_Pre_Img=new Array(Car_Image_Sources.length);
var C_Angle=Car_Direction?Math.PI/(Car_NoOfSides/2):0,C_CrImg=Car_NoOfSides,C_MaxW,C_TotalW,
C_Stppd=false,i,C_LeftOffset,C_HalfNo=Car_NoOfSides/2;
function Carousel(){
if(document.getElementById){
for(i=0;i<Car_Image_Sources.length;i+=2){
C_Pre_Img[i]=new Image();C_Pre_Img[i].src=Car_Image_Sources[i]}
C_MaxW=Car_Image_Width/Math.sin(Math.PI/Car_NoOfSides)+C_HalfNo+1;
Car_Div=document.getElementById("Carousel");
for(i=0;i<C_HalfNo;i++){
CW_I[i]=document.createElement("img");Car_Div.appendChild(CW_I[i]);
CW_I[i].style.position="absolute";
CW_I[i].style.top=0+"px";
CW_I[i].style.height=Car_Image_Height+"px";
if(Car_Border){
CW_I[i].style.borderStyle="solid";
CW_I[i].style.borderWidth=1+"px";
CW_I[i].style.borderColor=Car_Border_Color}
CW_I[i].src=Car_Image_Sources[2*i];
CW_I[i].lnk=Car_Image_Sources[2*i+1];
CW_I[i].onclick=C_LdLnk;
CW_I[i].onmouseover=C_Stp;
CW_I[i].onmouseout=C_Rstrt}
CarImages()}}
function CarImages(){
if(!C_Stppd){
C_TotalW=0;
for(i=0;i<C_HalfNo;i++){
C_ClcW[i]=Math.round(Math.cos(Math.abs(C_Coef[C_CoefOf+i]+C_Angle))*Car_Image_Width);
C_TotalW+=C_ClcW[i]}
C_LeftOffset=(C_MaxW-C_TotalW)/2;
for(i=0;i<C_HalfNo;i++){
CW_I[i].style.left=C_LeftOffset+"px";
CW_I[i].style.width=C_ClcW[i]+"px";
C_LeftOffset+=C_ClcW[i]}
C_Angle+=Car_Speed/720*Math.PI*(Car_Direction?-1:1);
if((Car_Direction&&C_Angle<=0)||(!Car_Direction&&C_Angle>=Math.PI/C_HalfNo)){
if(C_CrImg==Car_Image_Sources.length)C_CrImg=0;
if(Car_Direction){
CW_I[C_HalfNo]=CW_I[0];
for(i=0;i<C_HalfNo;i++)CW_I[i]=CW_I[i+1];
CW_I[C_HalfNo-1].src=Car_Image_Sources[C_CrImg];
CW_I[C_HalfNo-1].lnk=Car_Image_Sources[C_CrImg+1]}
else{ for(i=C_HalfNo;i>0;i--)CW_I[i]=CW_I[i-1];
CW_I[0]=CW_I[C_HalfNo];
CW_I[0].src=Car_Image_Sources[C_CrImg];
CW_I[0].lnk=Car_Image_Sources[C_CrImg+1]}
C_Angle=Car_Direction?Math.PI/C_HalfNo:0;C_CrImg+=2}}
setTimeout("CarImages()",50)}
function C_LdLnk(){if(this.lnk)window.location.href=this.lnk}
function C_Stp(){this.style.cursor=this.lnk?"pointer":"default";C_Stppd=true;}
function C_Rstrt(){C_Stppd=false}
</script> <div id="Carousel" style="position:relative; width:130; height:21">
<!-- Конец скрипта -->
Печатная машинка
<div id="data"></div>
<script>
(function () {
var str = 'Привет форум JavaScript',
len = str.length,
i = 0,
tId = setInterval(function () {
data.innerHTML += str[i++];
if (i == len) clearInterval(tId);
}, 400);
}());
</script>
Простой слайдер
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Простая замена картинок с помощью JQuery</title>
<style type="text/css">
div#rotator {position:relative; height:150px; margin-left: 15px;}
div#rotator ul li {float:left; position:absolute; list-style: none;}
div#rotator ul li.show {z-index:500;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<!-- Автор Dylan Wagstaff, http://www.alohatechsupport.net -->
<script type="text/javascript">
function theRotator() {
// Устанавливаем прозрачность всех картинок в 0
$('div#rotator ul li').css({opacity: 0.0});
// Берем первую картинку и показываем ее (по пути включаем полную видимость)
$('div#rotator ul li:first').css({opacity: 1.0});
// Вызываем функцию rotate для запуска слайдшоу, 5000 = смена картинок происходит раз в 5 секунд
setInterval('rotate()',5000);
}
function rotate() {
// Берем первую картинку
var current = ($('div#rotator ul li.show')? $('div#rotator ul li.show') : $('div#rotator ul li:first'));
// Берем следующую картинку, когда дойдем до последней начинаем с начала
var next = ((current.next().length) ? ((current.next().hasClass('show')) ? $('div#rotator ul li:first') :current.next()) : $('div#rotator ul li:first'));
// Расскомментируйте, чтобы показвать картинки в случайном порядке
// var sibs = current.siblings();
// var rndNum = Math.floor(Math.random() * sibs.length );
// var next = $( sibs[ rndNum ] );
// Подключаем эффект растворения/затухания для показа картинок, css-класс show имеет больший z-index
next.css({opacity: 0.0})
.addClass('show')
.animate({opacity: 1.0}, 1000);
// Прячем текущую картинку
current.animate({opacity: 0.0}, 1000)
.removeClass('show');
};
$(document).ready(function() {
// Запускаем слайдшоу
theRotator();
});
</script>
</head>
<body>
<div id="rotator">
<ul>
<li class="show"><a href="http://google.ru/"><img src="https://vavik96.com/wp-content/uploads/2014/12/3352.jpg" width="500" height="313" alt="pic1" /></a></li>
<li><a href="http://yandex.ru/"><img src="https://vavik96.com/wp-content/uploads/2014/12/3352.jpg" width="500" height="313" alt="pic2" /></a></li>
<li><a href="http://nigma.ru/"><img src="https://vavik96.com/wp-content/uploads/2014/12/3352.jpg" width="500" height="313" alt="pic3" /></a></li>
</ul>
</div>
</body>
</html>
Скрипт прыгающего текста
<script language="JavaScript">
var theText = "Название сайта";
function nextSize(i,incMethod,textLength)
{
if (incMethod == 1) return (72*Math.abs( Math.sin(i/(textLength/3.14))) );
if (incMethod == 2) return (255*Math.abs( Math.cos(i/(textLength/3.14))));
}
function sizeCycle(text,method,dis)
{
output = "";
for (i = 0; i < text.length; i++)
{
size = parseInt(nextSize(i +dis,method,text.length));
output += "<font style='font-size: "+ size +"pt'>" +text.substring(i,i+1)+ "</font>";
}
theDiv.innerHTML = output;
}
function doWave(n)
{
sizeCycle(theText,1,n);
if (n > theText.length) {n=0}
setTimeout("doWave(" + (n+1) + ")", 50);
}
</script>
<div ID="theDiv" align="center">
</div>
<script>doWave(0)</script>
Анимированая тень с помощью свойства CSS3 text-shadow и javascript
<p><input type="button" value="Вкл/Выкл анимацию" onclick="return toggleAnimation()"></p>
<div class="res" style="font-size:22px;background: none repeat scroll 0% 0% rgb(0, 0, 0); color: rgb(254, 255, 255);
text-shadow: 5px -4px 4px rgb(51, 51, 255), 1px 6px 4px rgb(255, 0, 0), -6px -2px 4px rgb(0, 255, 0);"
id="rgb">
Анимированная тень с помощью свойства CSS3 text-shadow на сайте HtmlWeb.ru
</div>
<br />
<div class="res" style="font-size:22px;background: none repeat scroll 0% 0% rgb(0, 0, 0); color: rgb(50, 50, 50);
text-shadow: 0px -1px 2px rgb(255, 255, 0), 1px -3px 3px rgb(255, 204, 0), 1px -5px 4px rgb(255, 153, 0), -3px -7px 5px rgb(255, 102, 0), 1px -9px 6px rgb(255, 51, 0), 3px -11px 7px rgb(255, 0, 0);"
id="fire">
Анимированная тень с помощью свойства CSS3 text-shadow на сайте HtmlWeb.ru
</div>
<script type="text/javascript">
var handle = false;
var textBrightness = 50;
var fireCount = 6;
var fireDelta = new Array();
var step = 0;
var angle = 0;
var radius = 6;
function animate()
{
fireDelta[fireCount - step] = Math.random() * 2 - 1;
var e = document.getElementById("fire");
var s = "";
for (var i = 0; i < fireCount; i++)
{
if (s) s += ", ";
s += Math.round(fireDelta[(i + fireCount - step) % fireCount] * i) + "px " + (-2 * i -1) + "px " + (2 + i) + "px ";
s += "rgb(255, " + (255 - i * Math.floor(255 / (fireCount - 1))) + ", 0)";
}
e.style.textShadow = s;
/* We need to change something, else the shadow will not be re-rendered. This bug was fixed in Opera 10.5. */
e.style.color = "rgb(" +
(textBrightness + step % 2) + ", " +
textBrightness + ", " +
textBrightness + ")";
step = (step + 1) % fireCount;
/* RGB */
angle -= 0.4;
if (angle <= 0) angle = Math.PI * 2;
var e = document.getElementById("rgb");
var s =
Math.round(Math.sin(angle) * radius) + "px " +
Math.round(Math.cos(angle) * radius) + "px 4px #33F, " +
Math.round(Math.sin(angle + Math.PI * 4 / 3) * radius) + "px " +
Math.round(Math.cos(angle + Math.PI * 4 / 3) * radius) + "px 4px #F00, " +
Math.round(Math.sin(angle + Math.PI * 2 / 3) * radius) + "px " +
Math.round(Math.cos(angle + Math.PI * 2 / 3) * radius) + "px 4px #0F0";
e.style.textShadow = s;
/* We need to change something, else the shadow will not be re-rendered. This bug was fixed in Opera 10.5. */
e.style.color = "rgb(" + (255 - step % 2) + ", 255, 255)";
}
function toggleAnimation()
{
for (var i = 0; i < fireCount; i++)
fireDelta[i] = Math.random() * 2 - 1;
if (handle)
{
window.clearInterval(handle);
handle = false;
}
else
handle = window.setInterval(function() { animate(); }, 100);
return false;
}
toggleAnimation();
</script>
Переливающиеся ссылки с помощью JavaScript
Скрипт вставляется в заголовок между тэгами <head> и </head>
<script type="text/javascript">
dt = new Array("red", "blue", "green", "purple", "tan", "#0000A0", "#A00000", "#00A000", "#00A0A0", "#A000A0", "#A0A000");
i1 = 0;
i2 = 2;
function cl() {
document.linkColor = dt[i1++];
document.vlinkColor = dt[i2++];
if (i1>dt.length) i1=0;
if (i2>dt.length) i2=0;
setTimeout("cl()",500);}
cl();
</script>
HTML редактор онлайн
<!DOCTYPE html>
<html>
<head>
<style>
.htmleditor_input, .htmleditor_output
{
border:1px solid #c3c3c3;
width:100%;
height:450px;
background-color:#ffffff;
color:#000000;
}
#htmleditor
{
background-color: #f1fcff;
height:500px;
width:800px;
border:solid #c3c3c3 1px;
}
.htmleditor_headerText
{
color:#005d68;
font-family:verdana;
font-size:90%;
top:8px;
padding-bottom: 7px;
}
#htmleditor_source
{
padding-left: 7px;
width:48%;
float: left;
}
#htmleditor_result
{
padding-right: 7px;
width:48%;
float: right;
}
</style>
<script>
function update()
{
var x = document.getElementById('mycode').value;
document.getElementById("display").contentDocument.body.innerHTML = x;
}
</script>
</head>
<body>
<div id="htmleditor"><div id="htmleditor_source"><div class="htmleditor_headerText">HTML редактор онлайн</div>
<textarea class="htmleditor_input" id="mycode">
ВВЕДИТЕ (СКОПИРУЙТЕ) КОД В ЭТО ОКНО
</textarea>
</div>
<div id="htmleditor_result">
<input onclick="update();" type="button" value="Показать результат">
<iframe class="htmleditor_output" id="display"></iframe>
</div>
</div>
</body>
</html>

