devwiki:javascript

Differences

This shows you the differences between two versions of the page.


Previous revision
devwiki:javascript [2024/02/03 15:18] (current) – [Timer operation] ying
Line 1: Line 1:
 +====== Javascript Advance and Modules ======
 +
 +  * as javascript program becomes complex, it has new concepts of modules, (like python module, a library of functions)
 +  * as javascript is inside different browser, means it needs browser support, modern new browser has support new feature of js, but js need to tell them, how modern this JS code is, like type attribute. <code html>
 +<!doctype html>
 +<script type="module">
 +  // note: module need browser access via http, not file:///
 +  import {sayHi} from './say.js';
 +  document.body.innerHTML = sayHi('John');
 +</script>
 +</code>
 +  * ref: https://javascript.info/js
 +
 +
 +===== other new ES6 codes =====
 +
 +  * ref : https://zellwk.com/blog/es6/
 +
 +  * new let vs var<code>
 +let a = 1 // block scope; local block accessible only
 +var b = 1 // function scope; global accessible when global declare, local only when local declare
 +</code>
 +  * unpack assignment (destructuring assignment, as from js1.7 = ES6) <code>
 +[a, b] = [10, 20]; // Destructuring arrays
 +// same as  pyhton: a,b = [10,20]
 +const my_data = {
 +  firstName: 'Any',
 +  lastName: 'One'
 +}
 +let { firstName, lastName } = my_data // destructuring objects, note the variable name must be same as key name
 +</code>
 +
 +====== Useful code ======
 +
 +  * time left countdown (pure js): https://www.codegrepper.com/code-examples/javascript/make+time+left+from+date.now+javascript
 +  * javascript date and timezone: https://flaviocopes.com/javascript-dates/
 +  * time related lib: https://momentjs.com/timezone/
 +
 +  * confetti from tsparticles:
 +    * https://dev.to/matteobruni/how-to-create-beautiful-confetti-animations-with-tsparticles-193
 +    * https://github.com/matteobruni/tsparticles
 +  * button click confetti:
 +    * https://codemyui.com/confetti-pop-out-on-button-click/
 +
 +====== array operation ======
 +  * array to string <code javascript>
 +const fruits = ["Banana", "Orange", "Apple", "Mango"];
 +let text = fruits.join(';');
 +</code>
 +  * process array <code javascript>
 +// process like police man in back-door truck, first in last out, last in first out
 +let truck_queue = ['Bob', 'Willy', 'Mini'];
 +deploy_police = main_queue.pop(); // left ['Bob', 'Willy'] output 'Mini'
 +// add new police
 +cats.push('Puff', 'George'); // left ['Bob', 'Willy', 'Puff', 'George']
 +
 +// process like coffee shop, first in first out, last in last out
 +let coffee_queue = ['Bob', 'Willy', 'Mini'];
 +cur_customer = coffee_queue.shift(); // left ['Willy', 'Mini'], output 'Bob'
 +
 +// also can cut queue to like this
 +coffee_queue.unshift('Puff', 'George'); // ['Puff', 'George', 'Willy', 'Bob']
 +
 +// also add new to coffee queue normall
 +coffee_queue.push('Sam'); // ['Puff', 'George', 'Willy', 'Bob', 'Sam']
 +</code>
 +
 +====== UI interaction operation ======
 +
 +  * scroll to top for scrollable element <code javascript>
 +document.getElementById("coinbox_content").scrollTop = 0
 +
 +#css part
 +.coinbox_content{
 +    float: left;
 +    width: 430px;
 +    height: 100%;
 +    overflow: auto;
 +}
 +</code>
 +
 +====== Timer operation ======
 +
 +  * If the timer is intended to run indefinitely and you want a continuous countdown, the setInterval method is a simple and suitable choice. To stop, you need to explicitly clear it using clearInterval.
 +  * If you want more control over the execution, especially if there are additional conditions for stopping or restarting the timer, the setTimeout recursive approach might be preferred.
 +
 +<code javascript>
 +let timer = 5 * 60; // Convert minutes to seconds
 +const timerIndicator = document.getElementById('timerIndicator');
 +
 +// method a: Display count down, bad: will still run after time=0
 +setInterval(function() {
 +    timer--;
 +    timerIndicator.textContent = formatTimer(timer);
 +    if (timer <= 0) {
 +        alert('Form submit');
 +    }
 +}, 1000);
 +
 +// method b: will not run after time=0
 +function updateTimer() {
 +    timer--;
 +    timerIndicator.textContent = formatTimer(timer);
 +    if (timer <= 0) {
 +        alert('Form submit');
 +    } else {
 +        setTimeout(updateTimer, 1000);
 +    }
 +}
 +updateTimer(); // Start the timer.
 +// end of method b
 +
 +function formatTimer(seconds) {
 +    const minutes = Math.floor(seconds / 60);
 +    const remainingSeconds = seconds % 60;
 +    return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
 +}
 +</code>
 +
 +====== HTML5 and Javscript ======
 +
 +  * store data
 +    * localStorage: store locally for ever, across different browser windows
 +    * session storage: store locally while the tab is open, remove once closed
 +    * cookie: store locally and server on requests, across different browser, support old html4, expire by defined expire
 +  * example code <code javascript>
 +localStorage.setItem('user','lucy')
 +console.log(localStorage.getItem('user'))
 +
 +localStorage.removeItem('user')
 +localStorage.clear()
 +
 +// cookie is simple, all in 1 line text, that is for all keys and datas
 +document.cookie = "user=lucy"; // default cookie till the tab session close
 +
 +utc_date = new Date("2030/12/31").toUTCString()
 +console.log(utc_date)
 +document.cookie = "user=lucy;expires="+utc_date+";SameSite=lax" // cookie with expire date in UTC standard format
 +document.cookie = "score=121;expires="+utc_date+";SameSite=lax";
 +
 +// read cookie
 +function getCookie(name) {
 +  const value = `; ${document.cookie}`;
 +  const parts = value.split(`; ${name}=`);
 +  if (parts.length === 2) return parts.pop().split(';').shift();
 +}
 +console.log(document.cookie)
 +console.log(getCookie('user'))
 +
 +//to remove cookie, just set expire to early date
 +</code>
 +  * note on SameSite attribute needed nowadays to secure cookie been sent to 3rd site:
 +    * option: (SameSite=lax) for normal, (SameSite=strict) for same url, (SameSite=None;Secure) for all but https only.
 +    * https://www.ruanyifeng.com/blog/2019/09/cookie-samesite.html
 +    * https://www.netsparker.com/blog/web-security/same-site-cookie-attribute-prevent-cross-site-request-forgery/