HTML, CSS & JavaScript for Complete Beginners Code Examples

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
var text =
'And this is Dorlcote Mill. I must '
+ 'stand a minute or two here on the bridge '
+ 'and look at it, though the clouds are '
+ 'threatening, and it is far on in the afternoon. '
+ 'Even in this leafless time of departing February '
+ 'it is pleasant to look at,–perhaps the chill, '
+ 'damp season adds a charm to the trimly kept, '
+ 'comfortable dwelling-house, as old as the elms '
+ 'and chestnuts that shelter it from the '
+ 'northern blast. ';
var text_analyzer = {
current_text : text,
get_words_array : function() {
var text = this.current_text;
var split_text = text.split(' ');
return split_text;
},
count_words : function() {
var words_array = this.get_words_array();
var length = words_array.length;
return length;
},
get_average_word_length : function() {
var all_word_lengths = 0;
var words_array = this.get_words_array();
for(var i in words_array) {
var current_word = words_array[i];
all_word_lengths = all_word_lengths +
current_word.length;
}
return all_word_lengths / words_array.length;
},
get_longest_word : function() {
var longest_length_seen_so_far = 0;
var longest_word = '';
var words_array = this.get_words_array();
for(var i in words_array) {
var current_word = words_array[i];
if(current_word.length >
longest_length_seen_so_far) {
longest_word = current_word;
longest_length_seen_so_far =
current_word.length;
}
}
return longest_word;
},
get_word_frequencies : function() {
var words_array = this.get_words_array();
var word_frequencies = {};
for(var i in words_array) {
var current_word = words_array[i];
if(! (current_word in word_frequencies)) {
word_frequencies[current_word] = 1;
}
else {
var previous_frequency =
word_frequencies[current_word];
var new_frequency = previous_frequency
+ 1;
word_frequencies[current_word] =
new_frequency;
}
}
return word_frequencies;
},
};
function print_object(the_object) {
document.write('{<br>');
for(var i in the_object) {
var key = i;
var value = the_object[i];
document.write('"' + key + '"');
document.write(' : ');
if(Array.isArray(value)) {
print_array(value);
}
else if(typeof value === 'object') {
print_object(value);
}
else {
document.write(value);
}
document.write('<br>');
}
document.write('}<br>');
}
function print_array(the_array) {
document.write('[<br>');
for(var i in the_array) {
var value = the_array[i];
if(Array.isArray(value)) {
print_array(value);
}
else if(typeof value === 'object') {
print_object(value);
}
else {
document.write(value + ',');
}
}
document.write(']<br>');
}
document.write(text_analyzer.get_word_frequencies()['on']);
var text = 'And this is Dorlcote Mill. I must ' + 'stand a minute or two here on the bridge ' + 'and look at it, though the clouds are ' + 'threatening, and it is far on in the afternoon. ' + 'Even in this leafless time of departing February ' + 'it is pleasant to look at,–perhaps the chill, ' + 'damp season adds a charm to the trimly kept, ' + 'comfortable dwelling-house, as old as the elms ' + 'and chestnuts that shelter it from the ' + 'northern blast. '; var text_analyzer = { current_text : text, get_words_array : function() { var text = this.current_text; var split_text = text.split(' '); return split_text; }, count_words : function() { var words_array = this.get_words_array(); var length = words_array.length; return length; }, get_average_word_length : function() { var all_word_lengths = 0; var words_array = this.get_words_array(); for(var i in words_array) { var current_word = words_array[i]; all_word_lengths = all_word_lengths + current_word.length; } return all_word_lengths / words_array.length; }, get_longest_word : function() { var longest_length_seen_so_far = 0; var longest_word = ''; var words_array = this.get_words_array(); for(var i in words_array) { var current_word = words_array[i]; if(current_word.length > longest_length_seen_so_far) { longest_word = current_word; longest_length_seen_so_far = current_word.length; } } return longest_word; }, get_word_frequencies : function() { var words_array = this.get_words_array(); var word_frequencies = {}; for(var i in words_array) { var current_word = words_array[i]; if(! (current_word in word_frequencies)) { word_frequencies[current_word] = 1; } else { var previous_frequency = word_frequencies[current_word]; var new_frequency = previous_frequency + 1; word_frequencies[current_word] = new_frequency; } } return word_frequencies; }, }; function print_object(the_object) { document.write('{<br>'); for(var i in the_object) { var key = i; var value = the_object[i]; document.write('"' + key + '"'); document.write(' : '); if(Array.isArray(value)) { print_array(value); } else if(typeof value === 'object') { print_object(value); } else { document.write(value); } document.write('<br>'); } document.write('}<br>'); } function print_array(the_array) { document.write('[<br>'); for(var i in the_array) { var value = the_array[i]; if(Array.isArray(value)) { print_array(value); } else if(typeof value === 'object') { print_object(value); } else { document.write(value + ','); } } document.write(']<br>'); } document.write(text_analyzer.get_word_frequencies()['on']);
var text = 
    'And this is Dorlcote Mill. I must '
  + 'stand a minute or two here on the bridge '
  + 'and look at it, though the clouds are '
  + 'threatening, and it is far on in the afternoon. '
  + 'Even in this leafless time of departing February '
  + 'it is pleasant to look at,–perhaps the chill, '
  + 'damp season adds a charm to the trimly kept, '
  + 'comfortable dwelling-house, as old as the elms '
  + 'and chestnuts that shelter it from the '
  + 'northern blast. ';
  
var text_analyzer = {
    current_text : text,
    get_words_array : function() {
        var text = this.current_text;
        var split_text = text.split(' ');
        return split_text;
    },
    count_words : function() {
        var words_array = this.get_words_array();
        var length = words_array.length;
        return length;
    },
    get_average_word_length : function() {
      var all_word_lengths = 0;
      var words_array = this.get_words_array();
      for(var i in words_array) {
          var current_word = words_array[i];
          all_word_lengths = all_word_lengths +
              current_word.length;
      }
      return all_word_lengths / words_array.length;
    },
    get_longest_word : function() {
        var longest_length_seen_so_far = 0;
        var longest_word = '';
        var words_array = this.get_words_array();
        for(var i in words_array) {
            var current_word = words_array[i];
            if(current_word.length > 
                longest_length_seen_so_far) {
                longest_word = current_word;
                longest_length_seen_so_far =
                    current_word.length;
            }
        }
        return longest_word;
    },
    get_word_frequencies : function() {
        var words_array = this.get_words_array();
        var word_frequencies = {};
        for(var i in words_array) {
            var current_word = words_array[i];
            if(! (current_word in word_frequencies)) {
                word_frequencies[current_word] = 1;
            }
            else {
                var previous_frequency = 
                    word_frequencies[current_word];
                var new_frequency = previous_frequency
                    + 1;
                word_frequencies[current_word] =
                    new_frequency;
            }
        }
        return word_frequencies;
    },
};

function print_object(the_object) {
    document.write('{
'); for(var i in the_object) { var key = i; var value = the_object[i]; document.write('"' + key + '"'); document.write(' : '); if(Array.isArray(value)) { print_array(value); } else if(typeof value === 'object') { print_object(value); } else { document.write(value); } document.write('
'); } document.write('}
'); } function print_array(the_array) { document.write('[
'); for(var i in the_array) { var value = the_array[i]; if(Array.isArray(value)) { print_array(value); } else if(typeof value === 'object') { print_object(value); } else { document.write(value + ','); } } document.write(']
'); } document.write(text_analyzer.get_word_frequencies()['on']);

Chapter 12 “Program” starting code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<script>
function submit() {
document.getElementById("output").innerHTML =
'You just clicked submit!';
}
</script>
<textarea id="input"></textarea>
<br>
<button onclick="submit()">Submit</button>
<br>
<div id="output"></div>
<script> function submit() { document.getElementById("output").innerHTML = 'You just clicked submit!'; } </script> <textarea id="input"></textarea> <br> <button onclick="submit()">Submit</button> <br> <div id="output"></div>
 
 
 
 
 
 

Chapter 12 four rectangles example. Remove the lines that say “remove this line” otherwise the code will not work.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<style>
div {
/* remove this line
border:5px solid #000;
float:left;
margin: 10px;
padding:10px;
remove this line too */
}
</style>
<div>
Rectangle 1
</div>
<div>
Rectangle 2
</div>
<div>
Rectangle 3
</div>
<div>
Rectangle 4
</div>
<script>
/* remove this line
var all_rectangles = document.querySelectorAll('div');
function change_background() {
this.style.background = 'red';
}
function reset_background() {
this.style.background = 'transparent';
}
for(var i = 0; i < all_rectangles.length; i++) {
all_rectangles[i].addEventListener("mouseover", change_background);
all_rectangles[i].addEventListener("mouseout", reset_background);
}
remove this line too */
</script>
<style> div { /* remove this line border:5px solid #000; float:left; margin: 10px; padding:10px; remove this line too */ } </style> <div> Rectangle 1 </div> <div> Rectangle 2 </div> <div> Rectangle 3 </div> <div> Rectangle 4 </div> <script> /* remove this line var all_rectangles = document.querySelectorAll('div'); function change_background() { this.style.background = 'red'; } function reset_background() { this.style.background = 'transparent'; } for(var i = 0; i < all_rectangles.length; i++) { all_rectangles[i].addEventListener("mouseover", change_background); all_rectangles[i].addEventListener("mouseout", reset_background); } remove this line too */ </script>


Rectangle 1
Rectangle 2
Rectangle 3
Rectangle 4

Chapter 13 cookie-related code:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<p>Who that cares much to know the history of man, and how the
mysterious mixture behaves under the varying experiments of Time,
has not dwelt, at least briefly, on the life of Saint Theresa,
has not smiled with some gentleness at the thought of the little
girl walking forth one morning hand-in-hand with her still
smaller brother, to go and seek martyrdom in the country of
the Moors?
</p>
<div>+ Increase size</div>
<div>- Decrease size</div>
<script>
/* remove this line
function areCookiesEnabled() {
document.cookie = "verify=1";
if(document.cookie.length >= 1
&& document.cookie.indexOf("verify=1") !== -1) {
return true;
}
return false;
}
if(areCookiesEnabled()) {
document.write('We have cookies!');
}
function setCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
if(!value) {
value = "";
}
cookie = name + "=" + value + expires + "; path=/";
document.cookie = cookie;
}
function getCookie(name) {
var result = document.cookie.match("\\b" + name + "=([^;]*)\\b");
if(result) {
return result[1];
}
else {
return null;
}
};
function deleteCookie(name) {
var past_date = new Date(1976, 8, 16);
var expired_string = 'expires=' + past_date.toUTCString();
var expired_cookie = name + '=; ' + expired_string + '; path=/';
document.cookie = expired_cookie;
}
deleteCookie('size-preference');
var current_size_setting = 16;
var cookie_value = getCookie('size-preference');
if(cookie_value !== null && cookie_value !== "") {
current_size_setting = cookie_value;
current_size_setting = current_size_setting * 1;
var all_paragraphs = document.querySelectorAll('p');
var the_paragraph = all_paragraphs[0];
the_paragraph.style.fontSize = current_size_setting + 'px';
}
function change_size() {
var all_paragraphs = document.querySelectorAll('p');
var the_paragraph = all_paragraphs[0];
var current_button = this;
if(current_button.innerHTML === '+ Increase size') {
current_size_setting = current_size_setting + 2;
the_paragraph.style.fontSize = current_size_setting + 'px';
}
else {
current_size_setting = current_size_setting - 2;
the_paragraph.style.fontSize = current_size_setting + 'px';
}
setCookie('size-preference', current_size_setting, 365);
}
var change_size_buttons = document.querySelectorAll("div");
for(var i = 0; i < change_size_buttons.length; i++) {
change_size_buttons[i].addEventListener("click", change_size);
}
remove this line */
</script>
<p>Who that cares much to know the history of man, and how the mysterious mixture behaves under the varying experiments of Time, has not dwelt, at least briefly, on the life of Saint Theresa, has not smiled with some gentleness at the thought of the little girl walking forth one morning hand-in-hand with her still smaller brother, to go and seek martyrdom in the country of the Moors? </p> <div>+ Increase size</div> <div>- Decrease size</div> <script> /* remove this line function areCookiesEnabled() { document.cookie = "verify=1"; if(document.cookie.length >= 1 && document.cookie.indexOf("verify=1") !== -1) { return true; } return false; } if(areCookiesEnabled()) { document.write('We have cookies!'); } function setCookie(name,value,days) { var expires = ""; if (days) { var date = new Date(); date.setTime(date.getTime() + (days*24*60*60*1000)); expires = "; expires=" + date.toUTCString(); } if(!value) { value = ""; } cookie = name + "=" + value + expires + "; path=/"; document.cookie = cookie; } function getCookie(name) { var result = document.cookie.match("\\b" + name + "=([^;]*)\\b"); if(result) { return result[1]; } else { return null; } }; function deleteCookie(name) { var past_date = new Date(1976, 8, 16); var expired_string = 'expires=' + past_date.toUTCString(); var expired_cookie = name + '=; ' + expired_string + '; path=/'; document.cookie = expired_cookie; } deleteCookie('size-preference'); var current_size_setting = 16; var cookie_value = getCookie('size-preference'); if(cookie_value !== null && cookie_value !== "") { current_size_setting = cookie_value; current_size_setting = current_size_setting * 1; var all_paragraphs = document.querySelectorAll('p'); var the_paragraph = all_paragraphs[0]; the_paragraph.style.fontSize = current_size_setting + 'px'; } function change_size() { var all_paragraphs = document.querySelectorAll('p'); var the_paragraph = all_paragraphs[0]; var current_button = this; if(current_button.innerHTML === '+ Increase size') { current_size_setting = current_size_setting + 2; the_paragraph.style.fontSize = current_size_setting + 'px'; } else { current_size_setting = current_size_setting - 2; the_paragraph.style.fontSize = current_size_setting + 'px'; } setCookie('size-preference', current_size_setting, 365); } var change_size_buttons = document.querySelectorAll("div"); for(var i = 0; i < change_size_buttons.length; i++) { change_size_buttons[i].addEventListener("click", change_size); } remove this line */ </script>

Who that cares much to know the history of man, and how the mysterious mixture behaves under the varying experiments of Time, has not dwelt, at least briefly, on the life of Saint Theresa, has not smiled with some gentleness at the thought of the little girl walking forth one morning hand-in-hand with her still smaller brother, to go and seek martyrdom in the country of the Moors?

+ Increase size
- Decrease size

Chapter 24 Reading Journal example (live demo)

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<style>
.title {
font-style:italic;
}
.publication-year {
font-size:90%; padding-left:1em;
}
.active-list-item {
border:1px solid #000;
}
.bio {
position:absolute;
top:5%;
left:5%;
margin:5%;
padding:2% 5%;
border-radius:10px;
box-shadow: 5px 5px 5px #000;
background:#fff;
border:1px solid #ccc;
}
</style>
<h1>My Reading Journal</h1>
<ul>
<li data-isbn="9780679604136">
<span class="author">Rebecca Stott</span>, <span class="title">
Darwin’s Ghosts: The Secret History of Evolution</span> <span class="publication-year">2012</span>
</li>
<li data-isbn="9780520258327">
<span class="author">David W. Deamer</span>, <span class="title">
First Life: Discovering the Connections Between Stars, Cells, and
How Life Began</span> <span class="publication-year">2011</span>
</li>
<li data-isbn="9781118964781">
<span class="author">Alister E. McGrath</span>, <span class="title">Dawkins’ God: From The Selfish Gene to The God Delusion</span>
<span class="publication-year">2015</span>
</li>
</ul>
<script>
var books = {
'9780679604136' : {
'publisher' : 'Random House Publishing Group',
'pages' : '432',
},
'9780520258327' : {
'publisher' : 'University of California Press',
'pages' : '271',
},
'9781118964781' : {
'publisher' : 'John Wiley & Sons',
'pages' : '208',
},
};
var authors = {
'Rebecca Stott' : {
'born' : '1964',
'degree' : 'PhD',
'profession' : 'Professor at the University of East Anglia',
'other-works' : ['Ghostwalk (2007)', 'The Coral Thief (2009)'],
},
'David W. Deamer' : {
'born' : '1939',
'degree' : 'PhD',
'profession' : 'Research professor at UCSC',
'other-works' : ['Membrane Structure (2012)'],
},
'Alister E. McGrath' : {
'born' : '1953',
'degree' : 'PhD',
'profession' : 'Professor at Oxford University',
'other-works' : ['Mere Theology (2010)', 'C. S. Lewis, A Life (2013)']
}
}
var all_book_list_items = document.querySelectorAll('li');
for(var i = 0; i < all_book_list_items.length; i++) {
all_book_list_items[i].addEventListener('click', function() {
if(this.querySelectorAll('.extras').length) {
var the_extras_span = this.querySelectorAll('.extras')[0];
this.removeChild(the_extras_span);
this.className = '';
return;
}
this.className = 'active-list-item';
var isbn = this.getAttribute('data-isbn');
var book_object = books[isbn];
this.innerHTML = this.innerHTML + '<span class="extras">'
+ '<br> Publisher: ' + book_object.publisher
+ '. Page count: ' + book_object.pages + '</span>';
});
};
document.body.addEventListener('click', function(event) {
var clicked_element = event.target;
if (clicked_element.classList.contains("author")) {
var author_name = clicked_element.innerHTML;
var author_object = authors[author_name];
var bio_div = document.createElement('div');
bio_div.className = 'bio';
bio_div.innerHTML = '<h2>' + author_name + ' ('
+ author_object.degree + ')</h2>';
bio_div.innerHTML += '<h3>' + author_object.profession + '</h3>';
bio_div.innerHTML += '<div>Born: ' + author_object.born + '<br>';
bio_div.innerHTML += 'Other works: '
+ author_object['other-works'].join(', ');
bio_div.innerHTML += '</div>';
bio_div.addEventListener('click', function() {
//this.parentElement.removeChild(this);
document.body.removeChild(this);
});
document.getElementsByTagName('body')[0].appendChild(bio_div);
}
});
</script>
<style> .title { font-style:italic; } .publication-year { font-size:90%; padding-left:1em; } .active-list-item { border:1px solid #000; } .bio { position:absolute; top:5%; left:5%; margin:5%; padding:2% 5%; border-radius:10px; box-shadow: 5px 5px 5px #000; background:#fff; border:1px solid #ccc; } </style> <h1>My Reading Journal</h1> <ul> <li data-isbn="9780679604136"> <span class="author">Rebecca Stott</span>, <span class="title"> Darwin’s Ghosts: The Secret History of Evolution</span> <span class="publication-year">2012</span> </li> <li data-isbn="9780520258327"> <span class="author">David W. Deamer</span>, <span class="title"> First Life: Discovering the Connections Between Stars, Cells, and How Life Began</span> <span class="publication-year">2011</span> </li> <li data-isbn="9781118964781"> <span class="author">Alister E. McGrath</span>, <span class="title">Dawkins’ God: From The Selfish Gene to The God Delusion</span> <span class="publication-year">2015</span> </li> </ul> <script> var books = { '9780679604136' : { 'publisher' : 'Random House Publishing Group', 'pages' : '432', }, '9780520258327' : { 'publisher' : 'University of California Press', 'pages' : '271', }, '9781118964781' : { 'publisher' : 'John Wiley & Sons', 'pages' : '208', }, }; var authors = { 'Rebecca Stott' : { 'born' : '1964', 'degree' : 'PhD', 'profession' : 'Professor at the University of East Anglia', 'other-works' : ['Ghostwalk (2007)', 'The Coral Thief (2009)'], }, 'David W. Deamer' : { 'born' : '1939', 'degree' : 'PhD', 'profession' : 'Research professor at UCSC', 'other-works' : ['Membrane Structure (2012)'], }, 'Alister E. McGrath' : { 'born' : '1953', 'degree' : 'PhD', 'profession' : 'Professor at Oxford University', 'other-works' : ['Mere Theology (2010)', 'C. S. Lewis, A Life (2013)'] } } var all_book_list_items = document.querySelectorAll('li'); for(var i = 0; i < all_book_list_items.length; i++) { all_book_list_items[i].addEventListener('click', function() { if(this.querySelectorAll('.extras').length) { var the_extras_span = this.querySelectorAll('.extras')[0]; this.removeChild(the_extras_span); this.className = ''; return; } this.className = 'active-list-item'; var isbn = this.getAttribute('data-isbn'); var book_object = books[isbn]; this.innerHTML = this.innerHTML + '<span class="extras">' + '<br> Publisher: ' + book_object.publisher + '. Page count: ' + book_object.pages + '</span>'; }); }; document.body.addEventListener('click', function(event) { var clicked_element = event.target; if (clicked_element.classList.contains("author")) { var author_name = clicked_element.innerHTML; var author_object = authors[author_name]; var bio_div = document.createElement('div'); bio_div.className = 'bio'; bio_div.innerHTML = '<h2>' + author_name + ' (' + author_object.degree + ')</h2>'; bio_div.innerHTML += '<h3>' + author_object.profession + '</h3>'; bio_div.innerHTML += '<div>Born: ' + author_object.born + '<br>'; bio_div.innerHTML += 'Other works: ' + author_object['other-works'].join(', '); bio_div.innerHTML += '</div>'; bio_div.addEventListener('click', function() { //this.parentElement.removeChild(this); document.body.removeChild(this); }); document.getElementsByTagName('body')[0].appendChild(bio_div); } }); </script>

My Reading Journal

  • Rebecca Stott, Darwin’s Ghosts: The Secret History of Evolution 2012
  • David W. Deamer, First Life: Discovering the Connections Between Stars, Cells, and How Life Began 2011
  • Alister E. McGrath, Dawkins’ God: From The Selfish Gene to The God Delusion 2015
Comments
If you have a comment, please email me at contact@hawramani.com