JavaScript

notes, terms, definitions, etc.., Future task, to do

show dynamic images based on text box using predefined list
show images based on text box

search and display a predefined list

Access Google Sheet data
Access Google Sheet data 2

password encryption on client side

Login & Sessions

Hide or Show all buttons on a page

Include js file

<script type="text/javascript" src="jsfile.js"></script>

Auto logout, timer session expire

add to html file
<script type="text/javascript" src="../inc/timeout.js"></script>

JS file code

let logoutTimer;

function resetTimer() {
clearTimeout(logoutTimer);
logoutTimer = setTimeout(() => {
alert("You have been logged out due to inactivity.");
window.location.href = "logout.php"; // Your logout script
}, 1800000); // 30 Minutes = 1800000, 15 minutes = 900000 milliseconds, 5 minutes = 300,000 milliseconds
}

['click', 'mousemove', 'keypress', 'scroll'].forEach(evt =>
window.addEventListener(evt, resetTimer)
);

resetTimer(); // Initialize timer

Auto hide div after 5 seconds or click on close X to close



Test messsage that will disappear after a certain time    x close

When Javascript is disabled, hide all content

<noscript>
<div style="position: fixed; top: 0px; left: 0px; z-index: 3000;
height: 100%; width: 100%; background-color: #000">
<p style="margin-left: 10px">This website requires JavaScript, please enable it</p>
<p align="center"><a href="http://www.google.com/search?q=enable+javascript">Click on this link to learn how to enable Javascript.</a></p>
</div>
</noscript>

Date and Time

examples of :
to string from date, substr, onChange, convert to number


First two are the year, next two is the month, next two date, next two hour, next two minute, next two secound

Current data and time :
Add 3 months or 90 days:
Add 6 months or 180 days:
Add days:
Add month(s):


Hide an html element

<div id="my-element"> </div>

const element = document.getElementById('my-element');
element.style.display = 'none';

Prompt, user input

var name = prompt(what is your name);.

Void(0)

eliminate the unwanted side-effect, because it will return the undefined primative value. Example hyperlink stops a new page or refresh.

<a href="JavaScript:Void(0);">

preventDefault() Event Method

The preventDefault() method cancels the event if it is cancelable, meaning that the default action that belongs to the event will not occur.

example, this can be useful when:
Clicking on a "Submit" button, prevent it from submitting a form
Clicking on a link, prevent the link from following the URL
Explained by 3wschool

Get screen size, change on windows resize


Javescript to get current screen size : window.innerWidth;
Put this code inside the body tag so the value change when resizing the browser
onresize="screensize()"

Check for a variable that is not created yet

use the typeof function
typeof nonexits_variable !== 'undefined'

Comparison and Logical Operators

== equal to   ===equal value and equal type
!= not equal   !==not equal value or not equal type
>greater than   <less than
>=greater than or equal to  <=less than or equal to
&&and   || or
!not  

Math Funcitons

var Math = 46.7899

Math.round() // Returns a number that is rounded to the nearest integer.

Math.ceil() // Returns a number that is greater than or equal to your argument

Math.floor() // Returns a number that is less than or equal to your argument


String Manipulation


Conditional Statements

if((condition1) {
block of code to be executed if condition1 is true
} else if (condition2) {
block of code to be executed if the condition1 is false and condition2 is true
} else {
block of code to be executed if the condition1 is false and condition2 is false
}

These are the same
var testvar = true
if (testvar === true) , no need for this
if (testvar) you can just use this for true and false variables

switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
code block
}

Foreach Example

Foreach Multidemensional Example


Find user agent

Retrieve Current URL

the matching pattern from URL_______________________________

% modulus operator by 4

if the number is zero or a modulus of 4, the value returned with by 0

 

While Loop
while (i < 3) {
text += "The number is " + i;
i++;

function

function showDistance(speed, time) {
var $text = speed * time;
document.getElementById("showdistance").innerHTML = $text;
}

showDistance(10, 5);

function inside a variable

view source to see js code

Return value from function ___________________

Return value from js function, return true or false __________________

Return value from input, get input value __________________

 

Array

var groceries = ["Milk", "Eggs", "Frosted Flakes", "Salami", "Juice"];

groceries.push("Bananas"); //Adds and item to the end of an array

groceries.unshift("Bananas"); //Adds and item to the beginning of an array

groceries..pop(); //Removes the last item in the array

groceries.shift(); //Removes the first item in the array<

Combining Arrays

var good = ["Mario", "Luigi", "Kirby", "Yoshi"];
var bad = ["Bowser", "Koopa Troopa", "Goomba"];

var goodAndBad = good.concat(bad);


Array for loop

Code ________________
<div id="hmong1"></div>

var names = ["choj", "nub", "tsawb", "looj"];

for (i = 0; i < names.length; i++) {
    var hmong_para = document.createElement("p");
    var hmong_node = document.createTextNode(names[i]);
    hmong_para.appendChild(hmong_node);
    var hmong_element = document.getElementById("hmong1");
    hmong_element.appendChild(hmong_para);
}

Shuffle an Array

multidimensional array

var arg = [
  ['apple', 'orange', 'pear'],
  ['carrots', 'beans', 'peas'],
  ['cookies', 'cake', 'muffins', 'pie']
];

var arg = [
  ['0,0', '0,1', '0,2'],
  ['1,0', '1,1', '1,2'],
  ['2,0', '2,1', '2,2', '2,3']
];

document.getElementById("multiarray").innerHTML = arg[2][3];
Returns = pie

Code executed example

Create a new Array from another existing Array (Not a reference)

Use the Slice Command

var Array1 = [
['laug', 'old'],
['hluas', 'young'],
['teeb', 'light'],
['dlub', 'dark']
];

var newArray = Array1.slice();

Arrary Length testing

Play Sound from a static button

Create two column table with sound and multideminsion array

Get parameter from last page, get method

parameter bobby     parameter Johny     parameter takiski     parameter Timithoy    


Build a Quiz

Examples of :
Sort by 2nd column in multidimension array
Removing an element
Ajax insert into database without browser refresh or redirect

create html elements completely from JS, Show and get coodinates of an element, add event listener, change background, random number

example on dom page


Find location of scroll and execute function based one where you are

In this example we are looking at a div called container, and its height
example

var content_height = container.offsetHeight;
var current_y = window.innerHeight + window.pageYOffset;
// console.log(current_y + '/' + content_height);
if(current_y >= content_height) {
loadMore(); // execute the function loadMore
}

browser detect

On enter key submit

On enter key in text box execute

Pick Random Number - no repeated number
test / quizz app example ( hmong people app )

Find the position of a dom element
This can be used to position other dom elements like a nav drop down into the proper position because screen sizes change

test div to check for position
click to check the width again


Get all links and change them

Append text to a div

The append text is :


Check if a value in a list is in and array



Analog clock

W3C tutorial

Digital CLock



Check Radion Button

Male
Female



drop down select

x 12 = 0



Dice Game
Link to Dice Game

DOM get last time page was updated This does not work if using PHP or any other server side scripting language. It will always pick the recent date and time the page was executed.
Use the php javascript mix version.



Toggle class and text



Form auto calculate, check box is checked, string to int, onkeyup, getElementsByName

$ add the extra special

$ white $ black $ red $ blue $ yellow $ green

$ tip

$ How many would you like =$

Total : $



From Validation check html page

do not allow for copy and paste
<input name='email' type='text' size='35' maxlength='45' oncopy="return false" onpaste="return false">


check for number , isnumber
if (isNaN($additional_donation.value) == true) { do something; }


ES 6 printing a variable with text, string method
Use the back tick symbol also called acute (under the Tilde ) instead of the single quote

let firstname= 'Tim';
let lastname = 'Roose';
document.getElementById("es6printtest").innerHTML = `His name is ${firstname} ${lastname}`;

JS results :



ES6 string methods to review startsWith, endsWith, includes, repeat,