Одним из наиболее широко используемых языков программирования является JavaScript (JS), который используется во всех веб-приложениях для различных целей, включая проверку, создание динамической информации, интерактивную графику и отображение. JS предлагает возможность создавать всеобъемлющие, сложные веб-приложения наряду с HTML и CSS.

Пользователи могут взаимодействовать с интригующими компонентами веб-страницы с помощью JS. Но с чего начать, если вы начинающий программист с небольшим опытом работы с JS?

Лучший способ учиться — это делать, и здесь на помощь приходят простые проекты JavaScript. Мы собрали лучшие проекты JavaScript для начинающих, а также несколько более сложных, когда вы освоитесь, так что не Не волнуйтесь, если вам нужна помощь с идеями проекта!

Готовы ли вы работать над проектами JavaScript? Давайте идти.

Почему проекты JavaScript?

Ядром любого веб-приложения является JS. Твердое понимание JS открывает широкий спектр сложных и интересных возможностей трудоустройства, таких как полное программирование, разработка мобильных приложений, динамическая веб-разработка и дизайн UI/UX. С JavaScript легко получать удовольствие из-за безграничного взаимодействия языка.

Проекты — это следующий шаг к улучшению вашего резюме, если вы знакомы с основами JavaScript. Если у вас нет предварительных знаний в области программирования, вы можете прочитать книги по JS или записаться на вводные курсы по JavaScript, прежде чем вернуться к этим проектам. Поскольку исходный код доступен, вы можете понять большинство проектов JavaScript, если знакомы с HTML и CSS.

Прежде чем мы перейдем к самим проектам, давайте рассмотрим некоторые ключевые характеристики JavaScript:

  • используется для создания интерактивного веб-контента как на стороне клиента, так и на стороне сервера.
  • значительно улучшает взаимодействие с пользователем благодаря динамической функциональности.
  • Легковесный объектно-ориентированный язык.
  • Открытый, кроссплатформенный и интерпретируемый язык.
  • легко включает HTML и Java.

Лучшие проекты JavaScript для начинающих

Хотя JavaScript очень универсален, мы не хотим вас перегружать. К счастью, существует множество базовых javascript-проектов, с которых можно начать.

Чтобы упростить вам начало работы, мы начнем медленно с этих проектов JavaScript, содержащих исходный код:

Содержание

  1. JavaScript-калькулятор
  2. Игра виселицы
  3. Игра в крестики-нолики
  4. Погода
  5. Музыкальные события JavaScript
  6. Проверка формы JavaScript
  7. Отображение сведений о фотографии JavaScript
  8. Создать интерактивную целевую страницу
  9. Приложение для чата в реальном времени
  10. Редактор кода браузера JavaScript

1. Калькулятор JavaScript

Одним из простых проектов JavaScript в нашем списке является калькулятор. Будут использоваться простые HTML и CSS, а для создания всех функциональных компонентов будут использоваться базовые функции JavaScript. Для отображения кнопок мы продолжим использовать HTML, а CSS улучшит представление. Наконец, нам нужно использовать JavaScript, чтобы убедиться, что кнопки выполняют правильные действия.

Eval(), универсальная функция JS, которая разрешает код JS, служит основной функцией. Выбранное число будет показано на экране калькулятора с помощью метода display(). Имейте в виду, что программное обеспечение будет реагировать только на события мыши. Вот весь код, разбитый на разделы для HTML, CSS и JS:

HTML

<div class="calculator">
<input type="text" class="calculator-screen" value="" disabled />
  
  <div class="calculator-keys">
    
    <button type="button" class="operator" value="+">+</button>
    <button type="button" class="operator" value="-">-</button>
    <button type="button" class="operator" value="*">&times;</button>
    <button type="button" class="operator" value="/">&divide;</button>
    <button type="button" value="7">7</button>
    <button type="button" value="8">8</button>
    <button type="button" value="9">9</button>

    <button type="button" value="4">4</button>
    <button type="button" value="5">5</button>
    <button type="button" value="6">6</button>

    <button type="button" value="1">1</button>
    <button type="button" value="2">2</button>
    <button type="button" value="3">3</button>

    <button type="button" value="0">0</button>
    <button type="button" class="decimal" value=".">.</button>
    <button type="button" class="all-clear" value="all-clear">AC</button>
    <button type="button" class="equal-sign operator" value="=">=</button>
  </div>
</div>

CSS

html {
  font-size: 62.5%;
  box-sizing: border-box;
}
*, *::before, *::after {
  margin: 0;
  padding: 0;
  box-sizing: inherit;
}
.calculator {
  border: 1px solid #ccc;
  border-radius: 5px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 400px;
}
.calculator-screen {
  width: 100%;
  font-size: 5rem;
  height: 80px;
  border: none;
  background-color: #252525;
  color: #fff;
  text-align: right;
  padding-right: 20px;
  padding-left: 10px;
}
button {
  height: 60px;
  background-color: #fff;
  border-radius: 3px;
  border: 1px solid #c4c4c4;
  background-color: transparent;
  font-size: 2rem;
  color: #333;
  background-image: linear-gradient(to bottom,transparent,transparent 50%,rgba(0,0,0,.04));
  box-shadow: inset 0 0 0 1px rgba(255,255,255,.05), inset 0 1px 0 0 rgba(255,255,255,.45), inset 0 -1px 0 0 rgba(255,255,255,.15), 0 1px 0 0 rgba(255,255,255,.15);
  text-shadow: 0 1px rgba(255,255,255,.4);
}
button:hover {
  background-color: #eaeaea;
}
.operator {
  color: #337cac;
}
.all-clear {
  background-color: #f0595f;
  border-color: #b0353a;
  color: #fff;
}
.all-clear:hover {
  background-color: #f17377;
}
.equal-sign {
  background-color: #2e86c0;
  border-color: #337cac;
  color: #fff;
  height: 100%;
  grid-area: 2 / 4 / 6 / 5;
}
.equal-sign:hover {
  background-color: #4e9ed4;
}
.calculator-keys {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  grid-gap: 20px;
  padding: 20px;

JavaScript

const calculator = {
  displayValue: '0',
  firstOperand: null,
  waitingForSecondOperand: false,
  operator: null,
};
function inputDigit(digit) {
  const { displayValue, waitingForSecondOperand } = calculator;
  if (waitingForSecondOperand === true) {
    calculator.displayValue = digit;
    calculator.waitingForSecondOperand = false;
  } else {
    calculator.displayValue = displayValue === '0' ? digit : displayValue + digit;
  }
}
function inputDecimal(dot) {
  if (calculator.waitingForSecondOperand === true) {
   calculator.displayValue = "0."
    calculator.waitingForSecondOperand = false;
    return
  }
  if (!calculator.displayValue.includes(dot)) {
    calculator.displayValue += dot;
  }
}
function handleOperator(nextOperator) {
  const { firstOperand, displayValue, operator } = calculator
  const inputValue = parseFloat(displayValue);
  
  if (operator && calculator.waitingForSecondOperand)  {
    calculator.operator = nextOperator;
    return;
  }

  if (firstOperand == null && !isNaN(inputValue)) {
    calculator.firstOperand = inputValue;
  } else if (operator) {
    const result = calculate(firstOperand, inputValue, operator);
    calculator.displayValue = `${parseFloat(result.toFixed(7))}`;
    calculator.firstOperand = result;
  }
  calculator.waitingForSecondOperand = true;
  calculator.operator = nextOperator;
}
function calculate(firstOperand, secondOperand, operator) {
  if (operator === '+') {
    return firstOperand + secondOperand;
  } else if (operator === '-') {
    return firstOperand - secondOperand;
  } else if (operator === '*') {
    return firstOperand * secondOperand;
  } else if (operator === '/') {
    return firstOperand / secondOperand;
  }
  return secondOperand;
}
function resetCalculator() {
  calculator.displayValue = '0';
  calculator.firstOperand = null;
  calculator.waitingForSecondOperand = false;
  calculator.operator = null;
}
function updateDisplay() {
  const display = document.querySelector('.calculator-screen');
  display.value = calculator.displayValue;
}
updateDisplay();
const keys = document.querySelector('.calculator-keys');
keys.addEventListener('click', event => {
  const { target } = event;
  const { value } = target;
  if (!target.matches('button')) {
    return;
  }
  switch (value) {
    case '+':
    case '-':
    case '*':
    case '/':
    case '=':
      handleOperator(value);
      break;
    case '.':
      inputDecimal(value);
      break;
    case 'all-clear':
      resetCalculator();
      break;
    default:
      if (Number.isInteger(parseFloat(value))) {
        inputDigit(value);
      }
  }
  updateDisplay();
})

2. Игра «Виселица»

Популярная игра и один из наших простых JS-проектов — палач. Его можно быстро разработать с помощью JavaScript, HTML и CSS. Имейте в виду, что JS используется для определения основных функций. HTML предназначен для отображения, тогда как CSS заботится об украшении содержимого.

В коде JS много определенных методов, поэтому сначала он может показаться сложным, но после внимательного прочтения вы обнаружите, что на самом деле все довольно просто. Запустите код, чтобы посмотреть, как он выполняется построчно.

Проверьте выполнение и код здесь.

HTML

<!DOCTYPE html>
<html t="0x31" i="YA-9517" v="1.60">
    <head>
        <title>Hangman (Game)</title>
    </head>
    <body>
        <div id="home">
            <div class="title">Hangman</div>
            <div class="button anim" onclick="startGame()">Play</div>
            <div class="foother">Coded by Thomas Hj</div>
        </div>
        <div id="result" class="h">
            <div class="title" id="rT"></div>
            <div class="body" id="rM"></div>
            <div class="button anim" onclick="startGame()">Try Again?</div>
        </div>
        <div id="pGame">
            <div id="letter"></div>
            <div id="game">
                <div class="player">
                    <div class="playerModel">
                        <div class="head" data="false" id="g4"></div>
                        <div class="body" data="false" l="false" r="false" id="g5"></div>
                        <div class="foot" data="false" l="false" r="false" id="g6"></div>
                    </div>
                </div>
                <div class="stang3" data="false" id="g3"></div>
                <div class="stang2" data="false" id="g2"></div>
                <div class="stang" data="false" id="g1"></div>
                <div class="ground" data="false" id="g0"></div>
                <div class="hintButton" data="false" id="hintButton" onclick="hint()">?</div>
            </div>
            <div id="tastatur">
                <div id="moveKeybord"><div class="marg"></div></div>
                <div id="keybord"></div>
            </div>
            <div class="hint" id="hint">
                <div class="title">Hint<div class="exit" onclick="hintExit()">X</div></div>
                <div class="body" id="hintText"></div>
            </div>
        </div>
    </body>
</html>

CSS

body {
    background-color: #eee;
    margin: 0;
}
#home {
    background: linear-gradient(#eee, #aaa);
    background: -webkit-linear-gradient(top, #eee, #aaa);
    background: -ms-linear-gradient(top, #eee, #aaa);
    background: -moz-linear-gradient(top, #eee, #aaa);
    background: -o-linear-gradient(top, #eee, #aaa);
    bottom: 0;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 99;
}
#home .title {
    font-size: 48px;
    font-weight: bold;
    margin-top: 15%;
    text-align: center;
}
#home .button {
    background: #afa;
    background: linear-gradient(#afa, #6f6);
    background: -webkit-linear-gradient(top, #afa, #6f6);
    background: -ms-linear-gradient(top, #afa, #6f6);
    background: -moz-linear-gradient(top, #afa, #6f6);
    background: -o-linear-gradient(top, #afa, #6f6);
    border-radius: 2px;
    box-shadow: 0 0 0 5px #090;
    display: table;
    font-weight: bold;
    padding: 10px 20px;
    margin: 20% auto;
}
#home .foother {
    bottom: 20px;
    font-size: 12px;
    font-style: italic;
    position: absolute;
    right: 20px;
}
.h {
    display: none;
}
#result {
    background: #700;
    background: linear-gradient(rgba(125, 0, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -webkit-linear-gradient(top, rgba(125, 0, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -ms-linear-gradient(top, rgba(125, 0, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -moz-linear-gradient(top, rgba(125, 0, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -o-linear-gradient(top, rgba(125, 0, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    bottom: 0;
    left: 0;
    position: absolute;
    right: 0;
    top: 0;
    z-index: 100;
}
#result[data="true"] {
    background: #070;
    background: linear-gradient(rgba(0, 125, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -webkit-linear-gradient(top, rgba(0, 125, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -ms-linear-gradient(top, rgba(0, 125, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -moz-linear-gradient(top, rgba(0, 125, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
    background: -o-linear-gradient(top, rgba(0, 125, 0, 0.9) 20%, rgba(0, 0, 0, 0.7) 80%);
}
#result .title {
    color: #eee;
    font-size: 48px;
    margin-top: 15%;
    text-align: center;
    text-shadow: 1px 1px 0 #000;
}
#result .body {
    color: #fff;
    margin-top: 30px;
    text-align: center;
    text-shadow: 1px 1px 0 #000;
}
#result .button {
    background:#afa;
    background: linear-gradient(#afa, #6f6);
    background: -webkit-linear-gradient(top, #afa, #6f6);
    background: -ms-linear-gradient(top, #afa, #6f6);
    background: -moz-linear-gradient(top, #afa, #6f6);
    background: -o-linear-gradient(top, #afa, #6f6);
    border-radius: 2px;
    box-shadow: 0 0 0 5px #090;
    display: table;
    font-weight: bold;
    padding: 10px 20px;
    margin: 40px auto;
    margin-bottom: 0;
}
#letter {
    font-size: 22px;
    height: 30px;
    margin: 20px;
    text-align: center;
}
.l {
    box-shadow: 0 3px 0 -1px #555;
    display: inline-block;
    margin: 1px;
    height: 20px;
    text-transform: uppercase;
    width: 20px;
}
.ls {
    box-shadow: 0 0 0 0 #555;
    width: 10px;
}
#game {
    height: 250px;
    margin: auto;
    position: relative;
    width: 220px;
}
#game .player {
    left: 53px;
    position: absolute;
    top: 90px;
    height: 130px;
    width: 75px;
}
.player .playerModel {
    height: 100%;
    position: relative;
    width: 100%;
}
.playerModel .head {
    border-radius: 50%;
    box-shadow: 0 0 0 2px #000 inset;
    height: 35px;
    margin: auto;
    width: 35px;
}
.playerModel .head[data="false"] {
    display: none;
}
.playerModel .body {
    background-color: #000;
    height: 45px;
    margin: auto;
    width: 2px;
}
.playerModel .body[data="false"] {
    display: none;
}
.playerModel .body:before, .playerModel .body:after {
    background-color: #000;
    content: "";
    display: inline-block;
    height: 30px;
    position: absolute;
    width: 2px;
}
.playerModel .body[l="false"]:before, .playerModel .body[r="false"]:after {
    display: none;
}
.playerModel .body:before {
    left: 27px;
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
}
.playerModel .body:after {
    right: 26px;
    transform: rotate(-45deg);
    -webkit-transform: rotate(-45deg);
}
.playerModel .foot {
    background-color: #000;
    height: 3px;
    margin: auto;
    width: 2px;
}
.playerModel .foot[data="false"] {
    display: none;
}
.playerModel .foot:before, .playerModel .foot:after {
    background-color: #000;
    content: "";
    display: inline-block;
    height: 40px;
    position: absolute;
    width: 2px;
}
.playerModel .foot[l="false"]:before, .playerModel .foot[r="false"]:after {
    display: none;
}
.playerModel .foot:before {
    left: 30px;
    transform: rotate(20deg);
    -webkit-transform: rotate(20deg);
}
.playerModel .foot:after {
    right: 29px;
    transform: rotate(-20deg);
    -webkit-transform: rotate(-20deg);
}
#game .stang3 {
    background-color: #000;
    height: 20px;
    left: 90px;
    position: absolute;
    top: 70px;
    width: 2px;
}
#game .stang3[data="false"] {
    display: none;
}
#game .stang2 {
    background-color: #000;
    border-radius: 5px 0 0 5px;
    bottom: 180px;
    height: 5px;
    position: absolute;
    right: 45px;
    width: 95px;
}
#game .stang2:before {
    background-color: #000;
    content: "";
    left: 50px;
    height: 5px;
    position: absolute;
    top: 17px;
    transform: rotate(45deg);
    -webkit-transform: rotate(45deg);
    width: 50px;
}
#game .stang2[data="false"] {
    display: none;
}
#game .stang {
    background-color: #000;
    bottom: 0;
    height: 180px;
    margin: auto;
    position: absolute;
    right: 45px;
    width: 5px;
}
#game .stang[data="false"] {
    display: none;
}
#game .ground {
    background-color: #000;
    border-radius: 5px;
    bottom: 0;
    left: 0;
    height: 5px;
    margin: auto;
    position: absolute;
    right: 0;
    width: 220px;
}
#game .ground[data="false"] {
    display: none;
}
#game .hintButton {
    background: #ccc;
    background: linear-gradient(transparent, rgba(0, 0, 0, 0.1));
    background: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));
    background: -ms-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));
    background: -moz-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));
    background: -o-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));
    border-radius: 8%;
    box-shadow: 1px 1px 3px #999;
    font-weight: bold;
    padding: 5px 10px;
    position: absolute;
    right: 5px;
    top: 5px;
}
#game .hintButton[data="false"] {
    display: none;
}
#tastatur {
    background-color: rgba(238, 238, 238, 0.9);
    bottom: 0;
    left: 0;
    margin: auto;
    margin-bottom: 20px;
    max-width: 500px;
    padding: 0 15px;
    position: absolute;
    right: 0;
    text-align: center;
}
#moveKeybord {
    padding: 15px;
}
.marg {
    border-bottom: solid 2px #ccc;
}
#hint {
    border-radius: 2px;
    box-shadow: 1px 1px 4px #888;
    display: none;
    left: 0;
    margin: auto;
    margin-top: 75px;
    position: absolute;
    right: 0;
    top: 0;
    width: 250px;
}
#hint .title {
    background: #fff;
    background: linear-gradient(#fff, #bbb);
    background: -webkit-linear-gradient(top, #fff, #bbb);
    background: -ms-linear-gradient(top, #fff, #bbb);
    background: -moz-linear-gradient(top, #fff, #bbb);
    background: -o-linear-gradient(top, #fff, #bbb);
    border-bottom: solid 1px #555;
    border-radius: 2px 2px 0 0;
    font-weight: bold;
    padding: 5px 10px;
    position: relative;
}
#hint .title .exit {
    background-color: #f55;
    border-radius: 50%;
    box-shadow: 1px 1px 4px #888;
    font-weight: bold;
    padding: 8px 12px;
    position: absolute;
    right: -15px;
    top: -15px;
}
#hint .body {
    background-color: #ddd;
    border-radius: 0 0 2px 2px;
    padding: 10px;
}
.b {
    background: #eee;
    background: linear-gradient(#fff, #eee);
    background: -webkit-linear-gradient(top, #fff, #eee);
    background: -ms-linear-gradient(top, #fff, #eee);
    background: -moz-linear-gradient(top, #fff, #eee);
    background: -o-linear-gradient(top, #fff, #eee);
    box-shadow: 1px 1px 1px 0 #ccc;
    display: inline-block;
    margin: 2px;
    padding: 8px;
    text-align: center;
    width: 25px;
}
.b[data="false"], .b[data="true"] {
    color: #555;
    font-weight: bold;
}
.b[data="true"] {
    background: #9f9;
}
.b[data="false"] {
    background: #aaa;
}
.anim {
    animation: button 3s infinite;
    -webkit-animation: button 3s infinite;
}
@keyframes button {
    0%, 50%, 90% {
        transform: rotate(0deg);
        -webkit-transform: rotate(0deg);
    }
    60% {
        transform: rotate(5deg) scale(1);
        -webkit-transform: rotate(5deg) scale(1);
    }
    70% {
        transform: rotate(-5deg) scale(0.97);
        -webkit-transform: rotate(-5deg) scale(0.97);
    }
    80% {
        transform: rotate(5deg) scale(1.05);
        -webkit-transform: rotate(5deg) scale(1.05);
    }
}
@-webkit-keyframes button {
    0%, 50%, 90% {
        transform: rotate(0deg);
        -webkit-transform: rotate(0deg);
    }
    60% {
        transform: rotate(5deg) scale(1);
        -webkit-transform: rotate(5deg) scale(1);
    }
    70% {
        transform: rotate(-5deg) scale(0.97);
        -webkit-transform: rotate(-5deg) scale(0.97);
    }
    80% {
        transform: rotate(5deg) scale(1.05);
        -webkit-transform: rotate(5deg) scale(1.05);
    }
}

JavaScript

/*
 * > Coded By Madelyn M
 * > 31102016
 * 
 * > #31
 */
// Word selection
// New word = ["Word name", "Hint"]
var word = [["Hangman", "That game you are playing right now."], ["Thomas Hj", "About the creator of this game."], ["HTML", "Markup language for creating Web pages."], ["CSS", "Wep page styles"], ["PHP", "A very popular server scripting language."], ["JavaScript", "Make web-page dynamic without reload the web page."], ["Java", "Run 15 billion devices.\nA program can be run in Windows, Linux and Mac"], ["SoloLearn", "A company that everyone can code for fun and share."], ["Love", "What is ?\nBaby don't hurt me\nDon't hurt me\nNo more"], ["Document", "A lot of text in the a file."], ["Playground", "There school kids go to."], ["Run", "Usain bolt."], ["Code", "var hw = 'Hello World';"], ["Samsung", "A company create Phone, Tv, Monitor, SDD, Memory chip..."], ["Super Mario", "A very popular game in Nintendo 64 that have red hat."], ["Star", "Super Mario like to get."], ["Clock", "14:12 or 14pm"], ["Binary Clock", "A clock that only use 0 or 1."], ["Sword", "Link from Zelda have on the hand."], ["Girl", "Not boy but ?"], ["Boy", "Not girl but ?"], ["Female", "Other name as girl."], ["Male", "Other name as boy."], ["Smartphone", "Something you've always on you."]]
// Game keyboard
var tastatur = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
// Game memory
var select = 0
var wordLeft = []
var fail = 0
// Web-page onload
window.onload = function() {
    gId("moveKeybord").addEventListener('touchmove', function(e) {
        wH = window.innerHeight
        tY = e.touches[0].clientY
        eL = gId("tastatur")
        resY = wH - tY - eL.offsetHeight
        if(resY < 0) {
            resY = 0
        } else if(resY > wH / 2) {
            resY = wH / 2
        }
        eL.style.bottom = resY + "px"
    }, false)
    createTastur()
}
// Start game
function startGame() {
    gId("home").className = "h"
    gId("result").className = "h"
    newGame()
}
// New game
function newGame() {
    clearTastatur()
    clearPlayer()
    createWord()
}
// Clear keyboard
function clearTastatur() {
    var e = document.getElementsByClassName("b")
    for(a = 0; a < e.length; a++) {
        e[a].setAttribute("data", "")
    }
}
// Clear player
function clearPlayer() {
    fail = 0
    wordLeft = []
    gId("g0").setAttribute("data", "false")
    gId("g1").setAttribute("data", "false")
    gId("g2").setAttribute("data", "false")
    gId("g3").setAttribute("data", "false")
    gId("g4").setAttribute("data", "false")
    gId("g5").setAttribute("data", "false")
    gId("g5").setAttribute("r", "false")
    gId("g5").setAttribute("l", "false")
    gId("g6").setAttribute("data", "false")
    gId("g6").setAttribute("l", "false")
    gId("g6").setAttribute("r", "false")
    gId("hintButton").setAttribute("data", "false")
    gId("hint").style.display = "none"
}
// Get new word
function createWord() {
    var d = gId("letter")
    d.innerHTML = ""
    select = Math.floor(Math.random() * word.length)
    for(a = 0; a < word[select][0].length; a++) {
        var x = word[select][0][a].toUpperCase()
        var b = document.createElement("span")
        b.className = "l" + (x == " " ? " ls" : "")
        b.innerHTML = "&nbsp"
        b.id = "l" + a;
        d.appendChild(b)
        
        if(x != " ") {
            if(wordLeft.indexOf(x) == -1) {
                wordLeft.push(x)
            }
        }
    }
}
// Create keyboard
function createTastur() {
    var tas = gId("keybord")
    tas.innerHTML = ""
    for(a = 0; a < tastatur.length; a++) {
        var b = document.createElement("span")
        b.className = "b"
        b.innerText = tastatur[a]
        b.setAttribute("data", "")
        b.onclick = function() {
            bTas(this)
        }
        tas.appendChild(b)
    }
}
// Game check, If show next error / game end
function bTas(a) {
    if(a.getAttribute("data") == "") {
        var x = isExist(a.innerText)
        a.setAttribute("data", x)
        if(x) {
            if(wordLeft.length == 0) {
                gameEnd(true)
            }
        } else {
            showNextFail()
        }
    }
}
// If letter "X" exist
function isExist(e) {
    e = e.toUpperCase()
    var x = wordLeft.indexOf(e)
    if(x != -1) {
        wordLeft.splice(x, 1)
        typeWord(e)
        return true
    }
    return false
}
// Show next fail drawing
function showNextFail() {
    fail++
    switch(fail) {
        case 1:
            gId("g0").setAttribute("data", "true")
            break;
        
        case 2:
            gId("g1").setAttribute("data", "true")
            break;
        
        case 3:
            gId("g2").setAttribute("data", "true")
            break;
        
        case 4:
            gId("g3").setAttribute("data", "true")
            gId("hintButton").setAttribute("data", "true")
            break;
        
        case 5:
            gId("g4").setAttribute("data", "true")
            break;
        
        case 6:
            gId("g5").setAttribute("data", "true")
            break;
        
        case 7:
            gId("g5").setAttribute("l", "true")
            break;
        
        case 8:
            gId("g5").setAttribute("r", "true")
            break;
        
        case 9:
            gId("g6").setAttribute("data", "true")
            gId("g6").setAttribute("l", "true")
            break;
        
        case 10:
            gId("g6").setAttribute("r", "true")
            gameEnd(false)
            break;
    }
}
function typeWord(e) {
    for(a = 0; a < word[select][0].length; a++) {
        if(word[select][0][a].toUpperCase() == e) {
            gId("l" + a).innerText = e
        }
    }
}
// Game result
function gameEnd(e) {
    var d = gId("result")
    d.setAttribute("data", e)
    if(e) {
        gId("rT").innerText = "You Win!"
        gId("rM").innerHTML = "Congratulations, you found the word!<br/><br/>Good Job!"
    } else {
        gId("rT").innerText = "You Lose!"
        gId("rM").innerHTML = "The word was <br/><br/>\"" + word[select][0].toUpperCase() + "\"<br/><br/>Better luck next time."
    }
    d.className = ""
}
// Show hint
function hint() {
    gId("hintText").innerText = word[select][1]
    gId("hint").style.display = "block"
}
// Exit hint
function hintExit() {
    gId("hint").style.display = "none"
}
// Get HTML ID element by name
function gId(a) {
    return document.getElementById(a)
}

3. Игра в крестики-нолики

Создать собственную игру в крестики-нолики с помощью JavaScript очень просто. Полный код можно посмотреть здесь, и он проведет вас через каждый шаг создания доски 3x3 для игры в крестики-нолики. Затем, для вашей собственной практики и опыта, вы можете впоследствии расшириться до NxN. HTML и CSS проекта относительно просты. Автор начинает с псевдокода, прежде чем углубляться в конкретное объяснение каждой функции.

HTML

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tic-tac-toe</title>
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
  </head>
  <body onload="initialize()">
    <h1>Tic-Tac-Toe</h1>
    <table id="table_game">
      <tr><td class="td_game"><div id="cell0" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell1" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell2" onclick="cellClicked(this.id)" class="fixed"></div></td></tr>
      <tr><td class="td_game"><div id="cell3" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell4" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell5" onclick="cellClicked(this.id)" class="fixed"></div></td></tr>
      <tr><td class="td_game"><div id="cell6" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell7" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell8" onclick="cellClicked(this.id)" class="fixed"></div></td></tr>
    </table>
    <div id="restart" title="Start new game" onclick="restartGame(true)"><span style="vertical-align:top;position:relative;top:-10px">#</span></div>
    <table>
      <tr><th class="th_list">Computer</th><th class="th_list" style="padding-right:10px;padding-left:10px">Draws</th><th class="th_list">Player</th></tr>
      <tr><td class="td_list" id="computer_score">0</td><td class="td_list" style="padding-right:10px;padding-left:10px" id="tie_score">0</td><td class="td_list" id="player_score">0</td></tr>
    </table>
    <!-- The modal dialog for announcing the winner -->
    <div id="winAnnounce" class="modal">
      <!-- Modal content -->
      <div class="modal-content">
        <span class="close" onclick="closeModal('winAnnounce')">&times;</span>
        <p id="winText"></p>
      </div>
    </div>
    <!-- The dialog for getting feedback from the user -->
    <div id="userFeedback" class="modal">
      <!-- Modal content -->
      <div class="modal-content">
        <p id="questionText"></p>
        <p><button id="yesBtn">Yes</button>&nbsp;<button id="noBtn">No</button></p>
      </div>
    </div>
    <!-- The options dialog -->
    <div id="optionsDlg" class="modal">
      <!-- Modal content -->
      <div class="modal-content">
        <h2>How would you like to play?</h2>
          <h3>Difficulty:</h3>
          <label><input type="radio" name="difficulty" id="r0" value="0">easy&nbsp;</label>
          <label><input type="radio" name="difficulty" id="r1" value="1" checked>hard</label><br>
          <h3>Play as:</h3>
          <label><input type="radio" name="player" id="rx" value="x" checked>X (go first)&nbsp;</label>
          <label><input type="radio" name="player" id="ro" value="o">O<br></label>
          <p><button id<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tic-tac-toe</title>
    <link href="https://fonts.googleapis.com/css?family=Indie+Flower" rel="stylesheet">
  </head>
  <body onload="initialize()">
    <h1>Tic-Tac-Toe</h1>
    <table id="table_game">
      <tr><td class="td_game"><div id="cell0" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell1" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell2" onclick="cellClicked(this.id)" class="fixed"></div></td></tr>
      <tr><td class="td_game"><div id="cell3" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell4" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell5" onclick="cellClicked(this.id)" class="fixed"></div></td></tr>
      <tr><td class="td_game"><div id="cell6" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell7" onclick="cellClicked(this.id)" class="fixed"></div></td><td class="td_game"><div id="cell8" onclick="cellClicked(this.id)" class="fixed"></div></td></tr>
    </table>
    <div id="restart" title="Start new game" onclick="restartGame(true)"><span style="vertical-align:top;position:relative;top:-10px">#</span></div>
    <table>
      <tr><th class="th_list">Computer</th><th class="th_list" style="padding-right:10px;padding-left:10px">Draws</th><th class="th_list">Player</th></tr>
      <tr><td class="td_list" id="computer_score">0</td><td class="td_list" style="padding-right:10px;padding-left:10px" id="tie_score">0</td><td class="td_list" id="player_score">0</td></tr>
    </table>
    <!-- The modal dialog for announcing the winner -->
    <div id="winAnnounce" class="modal">
      <!-- Modal content -->
      <div class="modal-content">
        <span class="close" onclick="closeModal('winAnnounce')">&times;</span>
        <p id="winText"></p>
      </div>
    </div>
    <!-- The dialog for getting feedback from the user -->
    <div id="userFeedback" class="modal">
      <!-- Modal content -->
      <div class="modal-content">
        <p id="questionText"></p>
        <p><button id="yesBtn">Yes</button>&nbsp;<button id="noBtn">No</button></p>
      </div>
    </div>
    <!-- The options dialog -->
    <div id="optionsDlg" class="modal">
      <!-- Modal content -->
      <div class="modal-content">
        <h2>How would you like to play?</h2>
          <h3>Difficulty:</h3>
          <label><input type="radio" name="difficulty" id="r0" value="0">easy&nbsp;</label>
          <label><input type="radio" name="difficulty" id="r1" value="1" checked>hard</label><br>
          <h3>Play as:</h3>
          <label><input type="radio" name="player" id="rx" value="x" checked>X (go first)&nbsp;</label>
          <label><input type="radio" name="player" id="ro" value="o">O<br></label>
          <p><button id="okBtn" onclick="getOptions()">Play</button></p>
      </div>
    </div>
  </body>
</html>
="okBtn" onclick="getOptions()">Play</button></p>
      </div>
    </div>
  </body>
</html>

CSS

body {
    background-color: rgb(32, 32, 32);
    background-image: url("https://janschreiber.github.io/img2/black-chalk.jpg");
    color: rgb(230, 230, 230);
    text-align: center;
    font-family: 'Indie Flower', 'Comic Sans', cursive;
    font-size: 0.7em;
}
h1 {
    line-height: 1em;
    margin-bottom: 0;
    padding-bottom: 5px;
    font-size: 2.8em;
    font-weight: bold;
}
h2 {
    font-size: 1.3em;
    font-weight: bold;
    padding: 0;
    margin: 0;
}
h3 {
    font-size: 1.1em;
    text-decoration: underline;
    text-decoration-style: dashed;
    padding: 0;
    margin: 10px 0 2px 0;
}
table {
    margin: 2% auto;
    border-collapse: collapse;
}
#table_game {
    position: relative;
    font-size: 120px;
    margin: 1% auto;
    border-collapse: collapse;
}
.td_game {
    border: 4px solid rgb(230, 230, 230);
    width: 90px;
    height: 90px;
    padding: 0;
    vertical-align: middle;
    text-align: center;
}
.fixed {
    width: 90px;
    height: 90px;
    line-height: 90px;
    display: block;
    overflow: hidden;
    cursor: pointer;
}
.td_list {
    text-align: center;
    font-size: 1.3em;
    font-weight: bold;
}
.th_list {
    font-size: 1.3em;
    font-weight: bold;
    text-align: center;
    text-decoration: underline;
}
#restart {
    font-size: 3em;
    width: 1em;
    height: 0.9em;
    cursor: pointer;
    margin: 0 auto;
    overflow: hidden;
}
.x {
    color: darksalmon;
    position: relative;
    top: -8px;
    font-size: 1.2em;
    cursor: default;
}
.o {
    color: aquamarine;
    position: relative;
    top: -7px;
    font-size: 1.0em;
    cursor: default;
}
/* modal background */
.modal {
    display: none;
    position: fixed;
    z-index: 1;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    overflow: auto; /* enable scroll if needed */
    background-color: black; /* fallback color */
    background-color: rgba(0, 0, 0, 0.6);
}
/* modal content */
.modal-content {
    background-color: rgb(240, 240, 240);
    color: rgb(32, 32, 32);
    font-size: 2em;
    font-weight: bold;
    /* 16 % from the top and centered */
    margin: 16% auto;
    padding: 20px;
    border: 2px solid black;
    border-radius: 10px;
    width: 380px;
    max-width: 80%;
}
.modal-content p {
    margin: 0;
    padding: 0;
}
/* close button for modal dialog */
.close {
    color: rgb(170, 170, 170);
    float: right;
    position: relative;
    top: -25px;
    right: -10px;
    font-size: 34px;
    font-weight: bold;
}
.close:hover,
.close:focus {
    color: black;
    text-decoration: none;
    cursor: pointer;
}
.win-color {
    background-color: rgb(240, 240, 240);
}

JavaScript

"use strict";
/*
A SIMPLE TIC-TAC-TOE GAME IN JAVASCRIPT
(1) Grid layout
The game grid is represented in the array Grid.cells as follows:
[0] [1] [2]
[3] [4] [5]
[6] [7] [8]
The cells (array elements) hold the following numeric values:
0 if not occupied, 1 for player, 3 for computer.
This allows us to quickly get an overview of the game state:
if the sum of all the cells in a row is 9, the computer wins,
if it is 3 and all the cells are occupied, the human player wins,
etc.
(2) Strategy of makeComputerMove()
The computer first  looks for almost completed rows, columns, and
diagonals, where there are two fields occupied either by the human
player or by the computer itself. If the computer can win by
completing a sequence, it does so; if it can block the player from
winning with the next move, it does that. If none of that applies,
it plays the center field if that's free, otherwise it selects a
random free field. This is not a 100 % certain strategy, but the
gameplay experience is fairly decent.
*/
//==================================
// EVENT BINDINGS
//==================================
// Bind Esc key to closing the modal dialog
document.onkeypress = function (evt) {
    evt = evt || window.event;
    var modal = document.getElementsByClassName("modal")[0];
    if (evt.keyCode === 27) {
        modal.style.display = "none";
    }
};
// When the user clicks anywhere outside of the modal dialog, close it
window.onclick = function (evt) {
    var modal = document.getElementsByClassName("modal")[0];
    if (evt.target === modal) {
        modal.style.display = "none";
    }
};
//==================================
// HELPER FUNCTIONS
//==================================
function sumArray(array) {
    var sum = 0,
        i = 0;
    for (i = 0; i < array.length; i++) {
        sum += array[i];
    }
    return sum;
}
function isInArray(element, array) {
    if (array.indexOf(element) > -1) {
        return true;
    }
    return false;
}
function shuffleArray(array) {
    var counter = array.length,
        temp,
        index;
    while (counter > 0) {
        index = Math.floor(Math.random() * counter);
        counter--;
        temp = array[counter];
        array[counter] = array[index];
        array[index] = temp;
    }
    return array;
}
function intRandom(min, max) {
    var rand = min + Math.random() * (max + 1 - min);
    return Math.floor(rand);
}
// GLOBAL VARIABLES
var moves = 0,
    winner = 0,
    x = 1,
    o = 3,
    player = x,
    computer = o,
    whoseTurn = x,
    gameOver = false,
    score = {
        ties: 0,
        player: 0,
        computer: 0
    },
    xText = "<span class=\"x\">&times;</class>",
    oText = "<span class=\"o\">o</class>",
    playerText = xText,
    computerText = oText,
    difficulty = 1,
    myGrid = null;
//==================================
// GRID OBJECT
//==================================
// Grid constructor
//=================
function Grid() {
    this.cells = new Array(9);
}
// Grid methods
//=============
// Get free cells in an array.
// Returns an array of indices in the original Grid.cells array, not the values
// of the array elements.
// Their values can be accessed as Grid.cells[index].
Grid.prototype.getFreeCellIndices = function () {
    var i = 0,
        resultArray = [];
    for (i = 0; i < this.cells.length; i++) {
        if (this.cells[i] === 0) {
            resultArray.push(i);
        }
    }
    // console.log("resultArray: " + resultArray.toString());
    // debugger;
    return resultArray;
};
// Get a row (accepts 0, 1, or 2 as argument).
// Returns the values of the elements.
Grid.prototype.getRowValues = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        console.error("Wrong arg for getRowValues!");
        return undefined;
    }
    var i = index * 3;
    return this.cells.slice(i, i + 3);
};
// Get a row (accepts 0, 1, or 2 as argument).
// Returns an array with the indices, not their values.
Grid.prototype.getRowIndices = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        console.error("Wrong arg for getRowIndices!");
        return undefined;
    }
    var row = [];
    index = index * 3;
    row.push(index);
    row.push(index + 1);
    row.push(index + 2);
    return row;
};
// get a column (values)
Grid.prototype.getColumnValues = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        console.error("Wrong arg for getColumnValues!");
        return undefined;
    }
    var i, column = [];
    for (i = index; i < this.cells.length; i += 3) {
        column.push(this.cells[i]);
    }
    return column;
};
// get a column (indices)
Grid.prototype.getColumnIndices = function (index) {
    if (index !== 0 && index !== 1 && index !== 2) {
        console.error("Wrong arg for getColumnIndices!");
        return undefined;
    }
    var i, column = [];
    for (i = index; i < this.cells.length; i += 3) {
        column.push(i);
    }
    return column;
};
// get diagonal cells
// arg 0: from top-left
// arg 1: from top-right
Grid.prototype.getDiagValues = function (arg) {
    var cells = [];
    if (arg !== 1 && arg !== 0) {
        console.error("Wrong arg for getDiagValues!");
        return undefined;
    } else if (arg === 0) {
        cells.push(this.cells[0]);
        cells.push(this.cells[4]);
        cells.push(this.cells[8]);
    } else {
        cells.push(this.cells[2]);
        cells.push(this.cells[4]);
        cells.push(this.cells[6]);
    }
    return cells;
};
// get diagonal cells
// arg 0: from top-left
// arg 1: from top-right
Grid.prototype.getDiagIndices = function (arg) {
    if (arg !== 1 && arg !== 0) {
        console.error("Wrong arg for getDiagIndices!");
        return undefined;
    } else if (arg === 0) {
        return [0, 4, 8];
    } else {
        return [2, 4, 6];
    }
};
// Get first index with two in a row (accepts computer or player as argument)
Grid.prototype.getFirstWithTwoInARow = function (agent) {
    if (agent !== computer && agent !== player) {
        console.error("Function getFirstWithTwoInARow accepts only player or computer as argument.");
        return undefined;
    }
    var sum = agent * 2,
        freeCells = shuffleArray(this.getFreeCellIndices());
    for (var i = 0; i < freeCells.length; i++) {
        for (var j = 0; j < 3; j++) {
            var rowV = this.getRowValues(j);
            var rowI = this.getRowIndices(j);
            var colV = this.getColumnValues(j);
            var colI = this.getColumnIndices(j);
            if (sumArray(rowV) == sum && isInArray(freeCells[i], rowI)) {
                return freeCells[i];
            } else if (sumArray(colV) == sum && isInArray(freeCells[i], colI)) {
                return freeCells[i];
            }
        }
        for (j = 0; j < 2; j++) {
            var diagV = this.getDiagValues(j);
            var diagI = this.getDiagIndices(j);
            if (sumArray(diagV) == sum && isInArray(freeCells[i], diagI)) {
                return freeCells[i];
            }
        }
    }
    return false;
};
Grid.prototype.reset = function () {
    for (var i = 0; i < this.cells.length; i++) {
        this.cells[i] = 0;
    }
    return true;
};
//==================================
// MAIN FUNCTIONS
//==================================
// executed when the page loads
function initialize() {
    myGrid = new Grid();
    moves = 0;
    winner = 0;
    gameOver = false;
    whoseTurn = player; // default, this may change
    for (var i = 0; i <= myGrid.cells.length - 1; i++) {
        myGrid.cells[i] = 0;
    }
    // setTimeout(assignRoles, 500);
    setTimeout(showOptions, 500);
    // debugger;
}
// Ask player if they want to play as X or O. X goes first.
function assignRoles() {
    askUser("Do you want to go first?");
    document.getElementById("yesBtn").addEventListener("click", makePlayerX);
    document.getElementById("noBtn").addEventListener("click", makePlayerO);
}
function makePlayerX() {
    player = x;
    computer = o;
    whoseTurn = player;
    playerText = xText;
    computerText = oText;
    document.getElementById("userFeedback").style.display = "none";
    document.getElementById("yesBtn").removeEventListener("click", makePlayerX);
    document.getElementById("noBtn").removeEventListener("click", makePlayerO);
}
function makePlayerO() {
    player = o;
    computer = x;
    whoseTurn = computer;
    playerText = oText;
    computerText = xText;
    setTimeout(makeComputerMove, 400);
    document.getElementById("userFeedback").style.display = "none";
    document.getElementById("yesBtn").removeEventListener("click", makePlayerX);
    document.getElementById("noBtn").removeEventListener("click", makePlayerO);
}
// executed when player clicks one of the table cells
function cellClicked(id) {
    // The last character of the id corresponds to the numeric index in Grid.cells:
    var idName = id.toString();
    var cell = parseInt(idName[idName.length - 1]);
    if (myGrid.cells[cell] > 0 || whoseTurn !== player || gameOver) {
        // cell is already occupied or something else is wrong
        return false;
    }
    moves += 1;
    document.getElementById(id).innerHTML = playerText;
    // randomize orientation (for looks only)
    var rand = Math.random();
    if (rand < 0.3) {
        document.getElementById(id).style.transform = "rotate(180deg)";
    } else if (rand > 0.6) {
        document.getElementById(id).style.transform = "rotate(90deg)";
    }
    document.getElementById(id).style.cursor = "default";
    myGrid.cells[cell] = player;
    // Test if we have a winner:
    if (moves >= 5) {
        winner = checkWin();
    }
    if (winner === 0) {
        whoseTurn = computer;
        makeComputerMove();
    }
    return true;
}
// Executed when player hits restart button.
// ask should be true if we should ask users if they want to play as X or O
function restartGame(ask) {
    if (moves > 0) {
        var response = confirm("Are you sure you want to start over?");
        if (response === false) {
            return;
        }
    }
    gameOver = false;
    moves = 0;
    winner = 0;
    whoseTurn = x;
    myGrid.reset();
    for (var i = 0; i <= 8; i++) {
        var id = "cell" + i.toString();
        document.getElementById(id).innerHTML = "";
        document.getElementById(id).style.cursor = "pointer";
        document.getElementById(id).classList.remove("win-color");
    }
    if (ask === true) {
        // setTimeout(assignRoles, 200);
        setTimeout(showOptions, 200);
    } else if (whoseTurn == computer) {
        setTimeout(makeComputerMove, 800);
    }
}
// The core logic of the game AI:
function makeComputerMove() {
    // debugger;
    if (gameOver) {
        return false;
    }
    var cell = -1,
        myArr = [],
        corners = [0,2,6,8];
    if (moves >= 3) {
        cell = myGrid.getFirstWithTwoInARow(computer);
        if (cell === false) {
            cell = myGrid.getFirstWithTwoInARow(player);
        }
        if (cell === false) {
            if (myGrid.cells[4] === 0 && difficulty == 1) {
                cell = 4;
            } else {
                myArr = myGrid.getFreeCellIndices();
                cell = myArr[intRandom(0, myArr.length - 1)];
            }
        }
        // Avoid a catch-22 situation:
        if (moves == 3 && myGrid.cells[4] == computer && player == x && difficulty == 1) {
            if (myGrid.cells[7] == player && (myGrid.cells[0] == player || myGrid.cells[2] == player)) {
                myArr = [6,8];
                cell = myArr[intRandom(0,1)];
            }
            else if (myGrid.cells[5] == player && (myGrid.cells[0] == player || myGrid.cells[6] == player)) {
                myArr = [2,8];
                cell = myArr[intRandom(0,1)];
            }
            else if (myGrid.cells[3] == player && (myGrid.cells[2] == player || myGrid.cells[8] == player)) {
                myArr = [0,6];
                cell = myArr[intRandom(0,1)];
            }
            else if (myGrid.cells[1] == player && (myGrid.cells[6] == player || myGrid.cells[8] == player)) {
                myArr = [0,2];
                cell = myArr[intRandom(0,1)];
            }
        }
        else if (moves == 3 && myGrid.cells[4] == player && player == x && difficulty == 1) {
            if (myGrid.cells[2] == player && myGrid.cells[6] == computer) {
                cell = 8;
            }
            else if (myGrid.cells[0] == player && myGrid.cells[8] == computer) {
                cell = 6;
            }
            else if (myGrid.cells[8] == player && myGrid.cells[0] == computer) {
                cell = 2;
            }
            else if (myGrid.cells[6] == player && myGrid.cells[2] == computer) {
                cell = 0;
            }
        }
    } else if (moves === 1 && myGrid.cells[4] == player && difficulty == 1) {
        // if player is X and played center, play one of the corners
        cell = corners[intRandom(0,3)];
    } else if (moves === 2 && myGrid.cells[4] == player && computer == x && difficulty == 1) {
        // if player is O and played center, take two opposite corners
        if (myGrid.cells[0] == computer) {
            cell = 8;
        }
        else if (myGrid.cells[2] == computer) {
            cell = 6;
        }
        else if (myGrid.cells[6] == computer) {
            cell = 2;
        }
        else if (myGrid.cells[8] == computer) {
            cell = 0;
        }
    } else if (moves === 0 && intRandom(1,10) < 8) {
        // if computer is X, start with one of the corners sometimes
        cell = corners[intRandom(0,3)];
    } else {
        // choose the center of the board if possible
        if (myGrid.cells[4] === 0 && difficulty == 1) {
            cell = 4;
        } else {
            myArr = myGrid.getFreeCellIndices();
            cell = myArr[intRandom(0, myArr.length - 1)];
        }
    }
    var id = "cell" + cell.toString();
    // console.log("computer chooses " + id);
    document.getElementById(id).innerHTML = computerText;
    document.getElementById(id).style.cursor = "default";
    // randomize rotation of marks on the board to make them look
    // as if they were handwritten
    var rand = Math.random();
    if (rand < 0.3) {
        document.getElementById(id).style.transform = "rotate(180deg)";
    } else if (rand > 0.6) {
        document.getElementById(id).style.transform = "rotate(90deg)";
    }
    myGrid.cells[cell] = computer;
    moves += 1;
    if (moves >= 5) {
        winner = checkWin();
    }
    if (winner === 0 && !gameOver) {
        whoseTurn = player;
    }
}
// Check if the game is over and determine winner
function checkWin() {
    winner = 0;
    // rows
    for (var i = 0; i <= 2; i++) {
        var row = myGrid.getRowValues(i);
        if (row[0] > 0 && row[0] == row[1] && row[0] == row[2]) {
            if (row[0] == computer) {
                score.computer++;
                winner = computer;
                // console.log("computer wins");
            } else {
                score.player++;
                winner = player;
                // console.log("player wins");
            }
            // Give the winning row/column/diagonal a different bg-color
            var tmpAr = myGrid.getRowIndices(i);
            for (var j = 0; j < tmpAr.length; j++) {
                var str = "cell" + tmpAr[j];
                document.getElementById(str).classList.add("win-color");
            }
            setTimeout(endGame, 1000, winner);
            return winner;
        }
    }
    // columns
    for (i = 0; i <= 2; i++) {
        var col = myGrid.getColumnValues(i);
        if (col[0] > 0 && col[0] == col[1] && col[0] == col[2]) {
            if (col[0] == computer) {
                score.computer++;
                winner = computer;
                // console.log("computer wins");
            } else {
                score.player++;
                winner = player;
                // console.log("player wins");
            }
            // Give the winning row/column/diagonal a different bg-color
            var tmpAr = myGrid.getColumnIndices(i);
            for (var j = 0; j < tmpAr.length; j++) {
                var str = "cell" + tmpAr[j];
                document.getElementById(str).classList.add("win-color");
            }
            setTimeout(endGame, 1000, winner);
            return winner;
        }
    }
    // diagonals
    for (i = 0; i <= 1; i++) {
        var diagonal = myGrid.getDiagValues(i);
        if (diagonal[0] > 0 && diagonal[0] == diagonal[1] && diagonal[0] == diagonal[2]) {
            if (diagonal[0] == computer) {
                score.computer++;
                winner = computer;
                // console.log("computer wins");
            } else {
                score.player++;
                winner = player;
                // console.log("player wins");
            }
            // Give the winning row/column/diagonal a different bg-color
            var tmpAr = myGrid.getDiagIndices(i);
            for (var j = 0; j < tmpAr.length; j++) {
                var str = "cell" + tmpAr[j];
                document.getElementById(str).classList.add("win-color");
            }
            setTimeout(endGame, 1000, winner);
            return winner;
        }
    }
    // If we haven't returned a winner by now, if the board is full, it's a tie
    var myArr = myGrid.getFreeCellIndices();
    if (myArr.length === 0) {
        winner = 10;
        score.ties++;
        endGame(winner);
        return winner;
    }
    return winner;
}
function announceWinner(text) {
    document.getElementById("winText").innerHTML = text;
    document.getElementById("winAnnounce").style.display = "block";
    setTimeout(closeModal, 1400, "winAnnounce");
}
function askUser(text) {
    document.getElementById("questionText").innerHTML = text;
    document.getElementById("userFeedback").style.display = "block";
}
function showOptions() {
    if (player == o) {
        document.getElementById("rx").checked = false;
        document.getElementById("ro").checked = true;
    }
    else if (player == x) {
        document.getElementById("rx").checked = true;
        document.getElementById("ro").checked = false;
    }
    if (difficulty === 0) {
        document.getElementById("r0").checked = true;
        document.getElementById("r1").checked = false;
    }
    else {
        document.getElementById("r0").checked = false;
        document.getElementById("r1").checked = true;
    }
    document.getElementById("optionsDlg").style.display = "block";
}
function getOptions() {
    var diffs = document.getElementsByName('difficulty');
    for (var i = 0; i < diffs.length; i++) {
        if (diffs[i].checked) {
            difficulty = parseInt(diffs[i].value);
            break;
            // debugger;
        }
    }
    if (document.getElementById('rx').checked === true) {
        player = x;
        computer = o;
        whoseTurn = player;
        playerText = xText;
        computerText = oText;
    }
    else {
        player = o;
        computer = x;
        whoseTurn = computer;
        playerText = oText;
        computerText = xText;
        setTimeout(makeComputerMove, 400);
    }
    document.getElementById("optionsDlg").style.display = "none";
}
function closeModal(id) {
    document.getElementById(id).style.display = "none";
}
function endGame(who) {
    if (who == player) {
        announceWinner("Congratulations, you won!");
    } else if (who == computer) {
        announceWinner("Computer wins!");
    } else {
        announceWinner("It's a tie!");
    }
    gameOver = true;
    whoseTurn = 0;
    moves = 0;
    winner = 0;
    document.getElementById("computer_score").innerHTML = score.computer;
    document.getElementById("tie_score").innerHTML = score.ties;
    document.getElementById("player_score").innerHTML = score.player;
    for (var i = 0; i <= 8; i++) {
        var id = "cell" + i.toString();
        document.getElementById(id).style.cursor = "default";
    }
    setTimeout(restartGame, 800);
}

4. Погодное приложение

Еще один распространенный проект JavaScript — приложение погоды. В этом проекте всякий раз, когда изменяется название местоположения, отображение погоды обновляется без необходимости обновления страницы. Также довольно стильным является пользовательский интерфейс.

Имейте в виду, что большинство погодных приложений получают доступ к данным о погоде через API. Мы будем использовать самый известный и широко используемый API — OpenWeatherMap.

Посмотрите это видео на YouTube, в котором подробно рассказывается о функциональности и коде приложения погоды. Как обычно, файлов три: main.js, main.css и index.html. Удобнее поддерживать разные файлы, хотя весь код может содержаться в одном файле (HTML).

Файл GitHub: Приложение Погода

5. Музыкальные события JavaScript

В этом разделе вы узнаете о прослушивателях событий, которые реагируют на события клавиатуры. Например, нажатие клавиши «S» вызовет определенное событие. Каждый будет иметь уникальный код и порядок действий.

Мы также узнаем, как добавлять и воспроизводить аудиофайлы в дополнение к слушателям событий. Поскольку основное внимание здесь уделяется JavaScript, вы увидите, что мы добавили очень простой CSS. Для правильной работы приложения вам потребуется импортировать собственные звуки и фоновые изображения.

HTML

<html>
<head>
 <meta charset="UTF-8">
 <meta name="viewport" content="width=device-width, initial-scale=1">
 <title>KeyBoard Music</title>
</head>
<body>
 <div class="keys">
   <div data-key="65" class="key">
     <kbd>A</kbd>
   </div>
   <div data-key="83" class="key">
     <kbd>S</kbd>
   </div>
   <div data-key="68" class="key">
     <kbd>D</kbd>
   </div>
   <div data-key="70" class="key">
     <kbd>F</kbd>
   </div>
   <div data-key="71" class="key">
     <kbd>G</kbd>
   </div>
   <div data-key="72" class="key">
     <kbd>H</kbd>
   </div>
   <div data-key="74" class="key">
     <kbd>J</kbd>
   </div>
   <div data-key="75" class="key">
     <kbd>K</kbd>
   </div>
   <div data-key="76" class="key">
     <kbd>L</kbd>
   </div>
 </div>
 <audio data-key="65" src="sounds/clap.wav"></audio>
 <audio data-key="83" src="sounds/chord.wav"></audio>
 <audio data-key="68" src="sounds/ride.wav"></audio>
 <audio data-key="70" src="sounds/openhat.wav"></audio>
 <audio data-key="71" src="sounds/tink.wav"></audio>
 <audio data-key="72" src="sounds/kick.wav"></audio>
 <audio data-key="74" src="sounds/swipe.wav"></audio>
 <audio data-key="75" src="sounds/tom.wav"></audio>
 <audio data-key="76" src="sounds/boom.wav"></audio>
</body>
  </html>

CSS

html {
 font-size: 12px;
 background: url('drums.jpg') top center;
 background-size: 80%;
}
.keys {
 display: flex;
 flex: 1;
 align-items: top;
 justify-content: center;
}
.key {
 border: 0.4rem solid blue;
 border-radius: 0.5rem;
 margin: 1rem;
 font-size: 2rem;
 padding: 1rem 0.5rem;
 transition: all 0.01s ease;
 width: 5rem;
 text-align: center;
 color: black;
 text-shadow: 0 0 0.5rem yellow;
}

JavaScript

function removeTransition(event) {
 if (event.propertyName !== 'transform') return
 event.target.classList.remove('playing')
}
function playSound(event) {
 const audio = document.querySelector(`audio[data-key="${event.keyCode}"]`)
 const key = document.querySelector(`div[data-key="${event.keyCode}"]`)
 if (!audio) return
 key.classList.add('playing')
 audio.currentTime = 0
 audio.play()
}
const keys = Array.from(document.querySelectorAll('.key'))
keys.forEach((key) => key.addEventListener('transitionend', removeTransition))
window.addEventListener('keydown', playSound)

6. Проверка формы JavaScript

Многие веб-сайты используют проверку формы как удобную функцию для проверки информации о пользователе на стороне клиента, включая данные карты и адреса. Пользователь может ввести число, оставить поле пустым или ввести только одну букву в обязательном поле ввода, например, если требуется имя поля. JS имеет возможность проверить эти данные.

Следующий проект влечет за собой базовую проверку формы. Конечно, для проекта также потребуются HTML-компоненты. Мы просто включили минимум HTML-компонентов без значительного стиля.

Вот весь код простой формы с фундаментальными проверками:

HTML и JAVASCRIPT

<html>
  <head>
     <title>Form Validation</title>
        <script type = "text/javascript">
        function validate() {
        var text;
           if( document.myForm.name.value == "" ) {
             text = "Name cannot be empty";
              document.getElementById("demo").innerHTML = text;
              document.myForm.name.focus() ;
              return false;
           }
           if( document.myForm.email.value == "" ) {
             text = "E-mail cannot be empty";
              document.getElementById("demo").innerHTML = text;
              document.myForm.email.focus() ;
              return false;
           }
      var emailID = document.myForm.email.value;
      atposn = emailID.indexOf("@");
      dotposn = emailID.lastIndexOf(".");
      if (atposn < 1 || ( dotposn - atposn < 2 )) {
      text = "Please enter valid email ID";
      document.getElementById("demo").innerHTML = text;
      document.myForm.email.focus() ;
      return false;
    }
           if( document.myForm.phone.value == "" || isNaN( document.myForm.phone.value ) ||
              document.myForm.phone.value.length != 10 ) {
              text = "Please enter a valid 10-digit phone number";
              document.getElementById("demo").innerHTML = text;
              document.myForm.phone.focus() ;
              return false;
           }
           if( document.myForm.subject.value == "0" ) {
              text = "Please provide your area of expertise";
              document.getElementById("demo").innerHTML = text;
              return false;
           }
           return( true );
        }
     </script>
  </head>
  <body>
     <form action = "" name = "myForm" onsubmit = "return(validate());">
   	 <h1 align="center">USER REGISTRATION</H1>
        <table align="center" cellspacing = "3" cellpadding = "3" border = "3">
           <tr>
              <td align = "right">Name</td>
              <td><input type = "text" name = "name" /></td>
           </tr>
           <tr>
              <td align = "right">E-mail</td>
              <td><input type = "text" name = "email" /></td>
           </tr>
           <tr>
              <td align = "right">Phone Number</td>
              <td><input type = "text" name = "phone" /></td>
           </tr>
           <tr>
              <td align = "right">Subject</td>
              <td>
                 <select name = "subject">
                    <option value = "0" selected>Select</option>
                    <option value = "1">HTML</option>
                    <option value = "2">JavaScript</option>
                    <option value = "3">CSS</option>
                    <option value = "4">JSP</option>
                 </select>
              </td>
           </tr>
        </table>
        <p id="demo" style="color:red; text-align:center"></p>
  <div style="text-align:center"><input type = "submit" value = "Submit" /></div>
     </form>
  </body>
</html>

7. JavaScript Отображение сведений о фотографии

Здесь мы разместим несколько фотографий на веб-сайте. Дополнительная информация появится, когда зритель наведет курсор на фотографии. Вы можете использовать фотографии, которые у вас уже есть, или загрузить новые откуда угодно.

Мы снова объединили JS с простыми HTML и CSS. Большую часть работы выполняют последние. Благодаря этому проекту вы узнаете, как работают события наведения мыши (наведения и выхода).

Попробуйте этот проект слайд-шоу W3Schools, чтобы сделать его более сложным. Графика изменится, когда пользователь наведет на нее указатель мыши, если вы замените события onClick событиями onmousehover и onmouseout.

HTML, CSS и JAVASCRIPT

<!DOCTYPE html>
<html>
 <head>
   <title>My Sun Sign Infos</title>
 </head>
 <script>
 function display(element){
   document.getElementById('image').innerHTML = element.alt;
 }
 function revert(){
   document.getElementById('image').innerHTML = "Hover over a sunsign image to display details.";
 }
</script>
 <style>
 #image{
     width: 650px;
     height: 70px;
     border:5px solid pink;
     background-color: black;
     background-repeat: no-repeat;
     color:white;
     background-size: 100%;
     font-family: Didot;
     font-size: 150%;
     line-height: 60px;
     text-align: center;
 }
 img{
 width: 200px;
 height: 200px;
 border-radius: 50%;
 }
 </style>
 <body>
   <div>
   <p id = "image">Hover over a sunsign image to display details.<p>
   <img alt = "Sagittarius are beautiful, loyal and passionate." src = "saggi.jpg" onmouseover = "display(this)" onmouseout = "revert()">
   <img alt = "Pisces are dreamy, helpful and love everyone!" src = "pisces.jpg" onmouseover = "display(this)" onmouseout = "revert()">
   <img alt = "Leo are strong and fearless. They aim for and achieve a lot!" src = "leo.jpg" onmouseover = "display(this)" onmouseout = "revert()">
   <img alt = "Scorpions are friends for life. They are trustworthy and truthful." src = "scorpio.jpg" onmouseover = "display(this)" onmouseout = "revert()">
   </div>
 </body>
</html>

8. Создайте интерактивную целевую страницу

Этот проект предполагает создание динамической целевой страницы, которая отображает соответствующее изображение и приветствие в зависимости от времени суток, сохраняя при этом ваше имя и введенный текст в локальном хранилище. Вы можете узнать больше о компонентах JS этого проекта, посмотрев это видео на YouTube.

HTML

<time id="time"></time>
    <h1>
      <span id="greeting"></span>
      <span id="name" contenteditable="true"></span>
    </h1>

<h2>What Is Your Focus For Today?</h2>
    <h2 id="focus" contenteditable="true"></h2>

CSS

* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
body {
  font-family: &#039;Quicksand&#039;, sans-serif;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  height: 100vh;
  color: black;
}
#time {
  font-size: 8rem;
}
h1 {
  margin-bottom: 3rem;
}
h2 {
  margin-bottom: 0.5rem;
  opacity: 0.6;
}
@media (max-width: 700px) {
  #time {
    font-size: 6rem;
  }

JavaScript

// DOM Elements
const time = document.getElementById('time'),
  greeting = document.getElementById('greeting'),
  name = document.getElementById('name'),
  focus = document.getElementById('focus');
// Options
const showAmPm = true;
// Show Time
function showTime() {
  let today = new Date(),
    hour = today.getHours(),
    min = today.getMinutes(),
    sec = today.getSeconds();
  // Set AM or PM
  const amPm = hour >= 12 ? 'PM' : 'AM';
  // 12hr Format
  hour = hour % 12 || 12;
  // Output Time
  time.innerHTML = `${hour}<span>:</span>${addZero(min)}<span>:</span>${addZero(
    sec
  )} ${showAmPm ? amPm : ''}`;
  setTimeout(showTime, 1000);
}
// Add Zeros
function addZero(n) {
  return (parseInt(n, 10) < 10 ? '0' : '') + n;
}
// Set Background and Greeting
function setBgGreet() {
  let today = new Date(),
    hour = today.getHours();
  if (hour < 12) {
    // Morning
    document.body.style.backgroundImage = "url('https://i.ibb.co/7vDLJFb/morning.jpg')";
    greeting.textContent = 'Good Morning, ';
  } else if (hour < 18) {
    // Afternoon
    document.body.style.backgroundImage = "url('https://i.ibb.co/3mThcXc/afternoon.jpg')";
    greeting.textContent = 'Good Afternoon, ';
  } else {
    // Evening
    document.body.style.backgroundImage = "url('https://i.ibb.co/924T2Wv/night.jpg')";
    greeting.textContent = 'Good Evening, ';
    document.body.style.color = 'white';
  }
}
// Get Name
function getName() {
  if (localStorage.getItem('name') === null) {
    name.textContent = '[Enter Name]';
  } else {
    name.textContent = localStorage.getItem('name');
  }
}
// Set Name
function setName(e) {
  if (e.type === 'keypress') {
    // Make sure enter is pressed
    if (e.which == 13 || e.keyCode == 13) {
      localStorage.setItem('name', e.target.innerText);
      name.blur();
    }
  } else {
    localStorage.setItem('name', e.target.innerText);
  }
}
// Get Focus
function getFocus() {
  if (localStorage.getItem('focus') === null) {
    focus.textContent = '[Enter Focus]';
  } else {
    focus.textContent = localStorage.getItem('focus');
  }
}
// Set Focus
function setFocus(e) {
  if (e.type === 'keypress') {
    // Make sure enter is pressed
    if (e.which == 13 || e.keyCode == 13) {
      localStorage.setItem('focus', e.target.innerText);
      focus.blur();
    }
  } else {
    localStorage.setItem('focus', e.target.innerText);
  }
}
name.addEventListener('keypress', setName);
name.addEventListener('blur', setName);
focus.addEventListener('keypress', setFocus);
focus.addEventListener('blur', setFocus);
// Run
showTime();
setBgGreet();
getName();
getFocus()

9. Приложение для чата в реальном времени

Создавать чат-приложения сравнительно легко, и для их создания с нуля можно использовать JavaScript. Этот проект немного пугает, потому что он использует и React, и Node.js. Но это полезный способ запачкать руки и получить опыт работы с этим бесценным оборудованием.

На GitHub исходный код можно посмотреть здесь.

10. Редактор кода браузера JavaScript

Несмотря на то, что существует множество редакторов кода JS, всегда приятно иметь возможность создать свой собственный. Этот проект посвящен созданию редактора кода в браузере с использованием языка JS. Он использует различные практические методы JS и даже имеет подсветку синтаксиса!

Исходный код этого проекта можно найти здесь.

HTML

<main class="view">
	<h1 class="title">
		Micro Code Editor
		<small>With syntax highlight*</small>
	</h1>
<div class="window">
  <div class="window-header">
   <div class="action-buttons"></div>
   <select class="language">
    <option value="javascript" selected>JavaScript</option>
    <option value="markup">HTML</option>
    <option value="php">PHP</option>
   </select>
  </div>
  <div class="window-body">
   <textarea class="code-input">// Switch the language and put some code on me :)           ↑↑↑↑↑↑
// This is a 'Hello World' example.
function greetings(name){
    name = name || "stranger";
    return "Hello, " + name + "!";
}
window.onLoad = alert(greetings());</textarea>
   <pre class="code-output">
    <code class="language-javascript">
     
    </code>
   </pre>
  </div>
 </div>
 <div class="credits">
  *thanks to <a href="https://twitter.com/leaverou">Lea Verou</a> for <a href="http://prismjs.com/">Prism.js</a>
 </div>
</main>

CSS

@import url(https://fonts.googleapis.com/css?family=Lato:300,400,700|PT+Mono);
@color-1st: LightCoral;
@color-2nd: GhostWhite;
@color-3rd: Gainsboro;
body{
 background:@color-1st;
 font-family:Lato, sans-serif;
 font-size:15px;
 margin:0;
}
*, *:before, *:after{
 box-sizing:border-box;
}
*:focus{
 outline:none;
}
a{
 text-decoration:none;
 color:inherit;
}
main{
 min-height:100vh;
 display:flex;
 display:-webkit-flex;
 -webkit-align-items:center;
 align-items:center;
 -webkit-flex-direction:column;
 flex-direction:column;
}
.title{
 color:#fff;
 text-align:center;
 font-weight:300;
 text-shadow:0 1px 0 rgba(0,0,0,0.2);
 font-size:2.8em;
 margin-top:1.5em;
 
 small{
  display:block;
  font-size:0.6em;
  margin-top:0.4em;
 }
}
.credits{
 color:#fff;
 text-shadow:0 1px 0 rgba(0,0,0,0.2);
 margin-top:2em;
 font-size:0.8em;
 opacity:0.5;
}
.window{
 width:547px;
 background:@color-2nd;
 border-radius:0.3rem;
 box-shadow:0 8px 12px rgba(0,0,0,0.1);
 overflow:hidden;
 
 .window-header{
  height:37px;
  background:@color-3rd;
  position:relative;
  
  .action-buttons{
   position:absolute;
   top:50%;
   left:10px;
   margin-top:-5px;
   width:10px;
   height:10px;
   background:Crimson;
   border-radius:50%;
   box-shadow:
    15px 0 0 Orange,
    30px 0 0 LimeGreen;
  }
  
  .language{
   display:inline-block;
   position:absolute;
   right:10px;
   top:50%;
   margin-top:-10px;
   height:21px;
   padding:0 1em;
   text-align:right;
   -webkit-appearance:none;
   appearance:none;
   border:none;
   background:transparent;
   font-family:Lato, sans-serif;
   color:DimGrey;
   
   &:before{
    content:'asd';
   }
   
   &:hover{
    background:rgba(0,0,0,0.1);
   }
  }
 }
 
 .window-body{
  position:relative;
  height:300px;
  
  .code-input, .code-output{
   position:absolute;
   top:0;
   left:0;
   width:100%;
   height:100%;
   padding:1rem;
   border:none;
   font-family:'PT Mono', monospace;
   font-size:0.8rem;
   background:transparent;
   white-space:pre-wrap;
   line-height:1.5em;
   word-wrap: break-word;
  }
  
  .code-input{
   opacity:0.7;
   margin:0;
   color:#999;
   resize:none;
  }
  
  .code-output{
   pointer-events:none;
   z-index:3;
   margin:0;
   overflow-y:auto;
   
   code{
    position:absolute;
    top:0;
    left:0;
    margin:0;
    padding:1rem;
    display:block;
    color:#666;
    font-size:0.8rem;
    font-family:'PT Mono', monospace;
   }
  }
 }
}
// Prism.js colors
a.token{
 text-decoration:none;
}
.token
{
 
 &.selector, &.punctuation, &.keyword{
  color:PaleVioletRed;
 }
 
 &.property, &.number, &.string, &.punctuation, &.tag-id{
  color:DodgerBlue;
 }
 
 &.function, &.attr-name{
  color:CadetBlue;
 }
 
 &.atrule{
  .atrule-id{
   color:BlueViolet; 
  }
 }
 
 &.boolean{
  color:LightSlateGray;
 }
 
 &.comment{
  color:DarkGrey;
 }
}
.language-php{
 .variable{
  color:CadetBlue;
 }
}

JavaScript

;var MicroCode = (function(){
	return {
		init: function(inputSel, outputSel, languageSel){
			this.focusInput(inputSel);
			this.listenForInput(inputSel);
			this.listenForLanguage(languageSel, '.code-output', inputSel);
			this.renderOutput(outputSel, $(inputSel)[0].value);
			this.listenerForScroll(inputSel, outputSel);
		},
		
		listenForInput: function(inputSel){
			var self = this;
$(inputSel).on('input keydown', function(key){
    var input = this,
     selStartPos = input.selectionStart,
     inputVal = input.value;
    if(key.keyCode === 9){
     input.value = inputVal.substring(0, selStartPos) + "    " + inputVal.substring(selStartPos, input.value.length);
     input.selectionStart = selStartPos + 4;
     input.selectionEnd = selStartPos + 4;
     key.preventDefault();
    }
    self.renderOutput('.code-output', this.value);
   });
   Prism.highlightAll();
  },
  
  listenForLanguage: function(languageSel, outputSel, inputSel){
   var self = this;
   $(languageSel).on('change', function(){
    $('code', outputSel)
     .removeClass()
     .addClass('language-' + this.value)
     .removeAttr('data-language');
    
    $(outputSel)
     .removeClass()
     .addClass('code-output language-' + this.value);
    
    $(inputSel)
     .val('');
    
    $('code', outputSel)
     .html('');
    
    self.focusInput(inputSel);
   });
  },
  
  listenerForScroll: function(inputSel, outputSel){
   $(inputSel).on('scroll', function(){
    console.log(this.scrollTop);
    $(outputSel)[0].scrollTop = this.scrollTop;
   });
  },
  
  renderOutput: function(outputSel, value){
   $('code', outputSel)
    .html(value.replace(/&/g, "&amp;").replace(/</g, "&lt;")
    .replace(/>/g, "&gt;") + "\n");
   
   Prism.highlightAll();
  },
  
  focusInput: function(inputSel){
   var input = $(inputSel);
   
   input.focus();
   
   input[0].selectionStart = input[0].value.length;
   input[0].selectionEnd = input[0].value.length;
  }
 }
})();
MicroCode.init('.code-input', '.code-output', '.language')

Создавайте проекты JavaScript прямо сейчас!

Были рассмотрены только 15 из многих интересных проектов JavaScript. Тем не менее, эти примеры проектов JavaScript могут значительно повысить ценность вашего портфолио и охватывают почти все основные идеи JavaScript.

Хотите узнать больше о JavaScript? С помощью наших проектов HTML расширьте свое понимание того, как он взаимодействует с HTML. И после того, как вы получите уверенность?