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

 

Commenting rules: Politeness is the only rule. We respect your right to disagree with anything we say. But comments with profanity and insults will be deleted.
Subscribe
Notify of
guest


0 Comments
Inline Feedbacks
View all comments