#addEventListener
Explore tagged Tumblr posts
Text
Discover the Best DME Breast Pump Options Near Me: A Comprehensive Guide to Well Health Hub
Find the best DME breast pump options near you with Well Health Hub’s comprehensive guide. From hospital-grade pumps to wearable options, discover the perfect solution for your breastfeeding journey, including insights on using health savings accounts for purchasing DME breast pumps and tips for getting a breast pump through insurance. DME Store Locator DME Store Locator Enter Zip Code: Find…

View On WordPress
#addEventListener#appendChild#clear list#createElement#DME Store Locator#dynamic list#event listener#find stores#forEach#form submission#getElementById#HealthFirst DME#HTML template#JavaScript#MediCare Store#nearby stores#no stores found#populate list#preventDefault#sample data#textContent#user input#Well Health Hub#zip code
0 notes
Text
just screamed so loud thank you coding forum we are gonna make it!!!
so close to posting on this coding forum for assistance
3 notes
·
View notes
Text
I'm too lazy to make an actual site for random YYH character generator (not an OC generator && not ai) and I couldn't immediately find one when I double-checked so here's very simple code for a random YYH character generator.
How do I use this if it's just code?
Copy/paste it into the code editor on w3schools, alternatively copy-paste it to a text document and name it "whatever.html" (do not forget the html), and open it in a browser of your choice.
Code below (no rick-roll; explanation of the code line-by-line will follow in a reblog in case anyone is feeling curious or dubious!):
edit: please make sure the quotation marks aren't stylised when you copy them! The editor won't recognise those! Copying the text with the personal blog style my blog has, for instance, will lead to errors bc of “” when what you want is "".
<p id="demo"></p>
<button id="change">Change character</button>
<br/>
<script>
const yyhCharacters = ["Yusuke", "Kuwabara", "Kurama", "Hiei", "Keiko", "Botan", "Genkai", "Saotome Jorge", "Koenma", "Ayame", "Rando", "Kazemaru", "Kuroda", "Chinpo", "Musashi", "Kibano", "Genbu", "Byakko", "Seiryuu", "Suzaku", "Murugu", "Rinku", "Roto", "Zeru", "Chu", "Imajin", "Gaou", "En (orange)", "Ryo (scars)", "Kai (braid)", "Ichigaki", "M4 (leopard/lizard man)", "M5 (leopard man)", "Ichigaki cyborg (Gatasubal)", "Gama", "Touya", "Bakuken", "Jin", "Risho", "Makintarou", "Kuro Mamotarou", "Ura Urashima", "Shishiwakumaru", "Suzuki", "Toguro Junior", "Toguro Senior", "Karasu", "Bui", "Sakyo", "Sensui", "Itsuki", "Kamiya (the Doctor)", "Hagiri Kaname (the Sniper)", "Mitarai Kiyoshi (Seaman)", "Amanuma (GM)", "Makihara (Gourmet)", "Yomi", "Mukuro", "Raizen", "Shigure", "Atsuko", "Shizuru", "Kido Asato (shadow)", "Kaito Yu (linguistics)", "Yanagisawa (shape-shifter)", "Puu", "Ruka", "Juri", "Koto", "Sawamura", "Okubo", "Sawamura", "Murota Shigeru (pervert mind-reader)", "Yatsude", "Tarukane", "Gouki (three treasures)", "Mr. Takenaka", "Mr. [Principal] (the actual principal (not Takenaka; you got brainwashed by the english dub I'm sorry))", "Mr. Akashi", "Mr. Iwamoto"];
getRndChara();
document.getElementById("change").addEventListener("click", getRndChara);
function getRndChara() {
document.getElementById("demo").innerHTML = yyhCharacters[Math.floor(Math.random() * yyhCharacters.length)];
}
</script>
#yyh#yu yu hakusho#coding#random character generator#please dont feed this to a generative ai ill strangle u w my knees#yyh random character generator
8 notes
·
View notes
Text
JavaScript
Introduction to JavaScript Basics
JavaScript (JS) is one of the core technologies of the web, alongside HTML and CSS. It is a powerful, lightweight, and versatile scripting language that allows developers to create interactive and dynamic content on web pages. Whether you're a beginner or someone brushing up on their knowledge, understanding the basics of JavaScript is essential for modern web development.
What is JavaScript?
JavaScript is a client-side scripting language, meaning it is primarily executed in the user's web browser without needing a server. It's also used as a server-side language through platforms like Node.js. JavaScript enables developers to implement complex features such as real-time updates, interactive forms, and animations.
Key Features of JavaScript
Interactivity: JavaScript adds life to web pages by enabling interactivity, such as buttons, forms, and animations.
Versatility: It works on almost every platform and is compatible with most modern browsers.
Asynchronous Programming: JavaScript handles tasks like fetching data from servers without reloading a web page.
Extensive Libraries and Frameworks: Frameworks like React, Angular, and Vue make it even more powerful.
JavaScript Basics You Should Know
1. Variables
Variables store data that can be used and manipulated later. In JavaScript, there are three ways to declare variables:
var (old way, avoid using in modern JS)
let (block-scoped variable)
const (constant variable that cannot be reassigned)
Example:
javascript
Copy code
let name = "John"; // can be reassigned const age = 25; // cannot be reassigned
2. Data Types
JavaScript supports several data types:
String: Text data (e.g., "Hello, World!")
Number: Numeric values (e.g., 123, 3.14)
Boolean: True or false values (true, false)
Object: Complex data (e.g., { key: "value" })
Array: List of items (e.g., [1, 2, 3])
Undefined: A variable declared but not assigned a value
Null: Intentional absence of value
Example:
javascript
Copy code
let isLoggedIn = true; // Boolean let items = ["Apple", "Banana", "Cherry"]; // Array
3. Functions
Functions are reusable blocks of code that perform a task.
Example:
javascript
Copy code
function greet(name) { return `Hello, ${name}!`; } console.log(greet("Alice")); // Output: Hello, Alice!
4. Control Structures
JavaScript supports conditions and loops to control program flow:
If-Else Statements:
javascript
Copy code
if (age > 18) { console.log("You are an adult."); } else { console.log("You are a minor."); }
Loops:
javascript
Copy code
for (let i = 0; i < 5; i++) { console.log(i); }
5. DOM Manipulation
JavaScript can interact with and modify the Document Object Model (DOM), which represents the structure of a web page.
Example:
javascript
Copy code
document.getElementById("btn").addEventListener("click", () => { alert("Button clicked!"); });
Visit 1
mysite
Conclusion
JavaScript is an essential skill for web developers. By mastering its basics, you can create dynamic and interactive websites that provide an excellent user experience. As you progress, you can explore advanced concepts like asynchronous programming, object-oriented design, and popular JavaScript frameworks. Keep practicing, and you'll unlock the true power of JavaScript!
2 notes
·
View notes
Text
SE TAAA DOOOOIDO KKKKKK
Irmão eu acabei de descobrir um novo Multiverso.
Eu tava com dificuldade no código, o ChatGPT me deu um código que checa se o Modal está com .show
Porém na versão antiga do app o Show era usado, porém agora só é usado o Hide.
E eu fiz isso:
function checkModals() {
const modal = document.querySelector('.modal');
const isVisible = modal && !modal.classList.contains('hide');
Simplsmente fiz o OPOSTO, o código checa por TODOS os modais, e se 1 deles estiver SEM o hide é porquê ele tá visível, ou seja, sempre que um modal aparecer ele vai automaticamente setar um OverLay atrás dele
Eu tinha falhado em um ponto, fiz a Workspace e a Home separadamente, e isso fez com que elas usassem Modais e Estilos diferentes, a Workspace usa uma codificação Diferente porquê o código do usuário não pode interagir com o código do app, ele é limitado a renderizar dentro do iFrame e o app é forçado a definir Show e Hide por segurança.
Basicamente oque o código faz é colocar um addEventListener nos Modais
Se um Modal for aberto, o script é acionado, e o Overlay é colocado 1 número abaixo do z-index do Modal
Pro modal ter um overlay nativo ele precisa que o próprio Modal seja o background, mas por usar o Modal do WorkSpace ele não borra o fundo.
E isso é MUITO fácil de customizar, basta inserir ali o ID do modal que eu não quero Checar, e esse modal não vai ter Background porque ele não vai acionar o script
Isso pode parecer Besteira mas transcendi a realidade com isso.
O código que o GPT me deu fazia isso:
function checkModals() {
const activeModal = document.querySelector('.modal.show');
overlay.style.display = activeModal ? 'block' : 'none';
if (activeModal) {
const modalZ = parseInt(getComputedStyle(activeModal).zIndex || 10000);
overlay.style.zIndex = modalZ - 1; }}
Oque fiz foi simplesmente Inverter:
function checkModals() {
const modal = document.querySelector('.modal');
const isVisible = modal && !modal.classList.contains('hide');
overlay.style.display = isVisible ? 'block' : 'none';
if (isVisible) {
const modalZ = parseInt(getComputedStyle(modal).zIndex || 10000);
overlay.style.zIndex = modalZ - 1; }}
Ou seja.
O Overlay vai tá sempre atrás do modal.
A idéia não foi minha, na verdade pedi idéias pro GPT.
Pois como dito, não tava conseguindo por Background no Modal, e sem ele tava MUITO poluído, o Modal precisava de FOCO pro usuário ter conforto.
Só de eu ter conseguido fazer a lógica Oposta é fodástico
Peguei um código pronto, e consegui Reverter o processo.
Cuidado Sociedade
Kirey is Evolving, ele tá aprendendo a fazer Engenharia Reversa
Daqui a pouco os EUA vai ser hackeado e Kirey vai vazar na internet todas as fotos do Trump e o Elon Musk no banheiro os dois pelado se abraçando no chuveiro
0 notes
Text
Sequentielle Suche mit FileMaker und PHP
Manchmal sind es nicht die großen Frameworks oder hochkomplexen API-Integrationen, die den Unterschied machen, sondern ein bewusst einfacher, robuster Ansatz, der sich nahtlos in vorhandene Workflows integriert. Genau das war der Ausgangspunkt für eine kleine aber wirkungsvolle Lösung, die FileMaker mit einem PHP-basierten Webinterface verbindet – mit dem Ziel, eine sequentielle Suche über eine größere Datenmenge performant und flexibel umzusetzen. Das derzeitige Problem beim Kunden, vor Jahren habe ich eine Sequentielle Suche nativ in FileMaker umgesetzt. Die übliche Vorgehensweise, ein Script sucht bei jedem Tastenanschlag, genutzt werden alle Felder die in der Schnellsuche eingeschlossen sind. Über die Jahre wuchs der Datenbestand, es wurden Felder innerhalb von Ausschnitten erfasst. Es musste so kommen, der Kunde konnte die Suche kaum mehr nutzen, tippen, warten, tippen. Sehr unschön und langsam. Dann kam mir im Zuge einer Listenansicht, in die ich eine Suche integriert habe, die Idee. FileMaker überträgt per -Aus URL einfügen- Tabellendaten an ein PHP-Script. Im WebViewer wird dann die Tabelle angezeigt, nebst einem Suchfeld. Also frisch ans Werk gemacht und schnell festgestellt, die Felder in Variablen zu verpacken, macht in der Menge keinen Spaß. Also das ganze per Schleife, Feldnamen holen, die Werte dazu sammeln. In Schleife, ist das gut machbar, aber trotzdem ein nicht unerheblicher Zeitaufwand. Dann eine Eingebung, exportiere die Tabelle und verarbeite die Daten direkt auf dem Server per PHP. Vorgehen: FileMaker exportiert eine strukturierte Datenmenge als CSV – diese Datei wird im Hintergrund automatisch an ein kleines PHP-Script übermittelt. Dort wird sie interpretiert, analysiert und in einer visuellen Oberfläche dargestellt, über die eine freie Volltextsuche möglich ist. Der Clou: Mit jedem Tastendruck wird die Ergebnisliste dynamisch reduziert – und bei Bedarf lassen sich über die Enter-Taste direkt Projektnummern an ein FileMaker-Script zurückgeben, das dann wiederum die interne Detailansicht aktualisiert. Ganz ohne Datenbankabfragen im Webserver, ganz ohne MySQL, Redis oder externe Services. Die PHP-Logik bleibt dabei angenehm überschaubar. Ein Beispiel für das Parsen und Darstellen der Daten sieht so aus:
<?php $csvData = []; $data = file_get_contents("php://input"); if ($data && strlen($data) > 0) { $lines = preg_split('/\r\n|\r|\n/', $data); foreach ($lines as $line) { if (trim($line) !== "") { $csvData[] = str_getcsv($line, "\t"); // Tab-getrennt } } if (!empty($csvData) && empty(array_filter(end($csvData)))) { array_pop($csvData); } } $spaltenIndizes = range(0, count($csvData[0] ?? []) - 1); ?>
In der Darstellung im WebViewer werden alle Datensätze tabellarisch angezeigt. Der Clou kommt mit JavaScript: Dort wird bei jeder Eingabe automatisch geprüft, welche Zeilen noch zum aktuellen Suchbegriff passen. Zusätzlich hebt ein kleiner Style-Block die passenden Zellen farblich hervor, um die Treffer visuell zu unterstützen. Und weil alles clientseitig passiert, bleibt es schnell – auch bei mehreren tausend Einträgen. Besonders elegant wirkt die Integration in FileMaker: Die Projektnummern der sichtbaren Zeilen werden bei einem Enter-Klick gesammelt und per fmp://-URL an ein FileMaker-Script übergeben. Diese Direktverbindung ermöglicht, das Webinterface wie eine native Erweiterung der Datenbank zu nutzen – ohne Performanceverlust, ohne Redundanz, ohne Hürden.
document.getElementById("searchInput").addEventListener("keypress", function(event) { if (event.key === "Enter") { event.preventDefault(); const rows = document.querySelectorAll("#csvTable tbody tr:not(.hide)"); const ids = []; rows.forEach(row => { const id = row.querySelectorAll("td")[0]?.textContent.trim(); // Erste Spalte = ID if (id) ids.push(id); }); if (ids.length > 0) { const param = encodeURIComponent(ids.join("|")); const url = `fmp://$/AVAGmbH?script=Projekt_LIST_Suche_PHP¶m=${param}`; window.location.href = url; } } });
Nach dem Klick, startet das FM-Script. Wir holen uns die ID,s nach üblicher Vorgangsweise und suchen in Schleife alle ID,s zusammen. In dem Zug, wird natürlich auch das Suchfenster in FileMaker geschlossen. Diese Form der sequentiellen Suche hat sich im Test als stabil und pflegeleicht erwiesen – gerade in Szenarien, in denen FileMaker allein bei umfangreichen Datensätzen an die Grenzen kommt, etwa bei mehrdimensionalen Suchen über unstrukturierte Felder oder bei extern generierten Listen. Und auch wenn es kein High-End-AI-Suchcluster ist: Die Lösung hat Charme. Weil sie genau das tut, was sie soll. Weil sie den Workflow nicht verbiegt, sondern erweitert. Und weil sie etwas bietet, das man oft zu selten hat: unmittelbare Rückmeldung und Kontrolle über den gesamten Prozess. Jetzt wird nur noch ein wenig mit CSS das ganze verschönt, dann kann der Kunde damit arbeiten.
0 notes
Text
JavaScript 2 🧬 How to add JavaScript
New Post has been published on https://tuts.kandz.me/javascript-2-%f0%9f%a7%ac-how-to-add-javascript/
JavaScript 2 🧬 How to add JavaScript

youtube
a - Add Javascript to HTML There are two ways to add JavaScript in an HTML file 1 → by embedding JavaScript in the HEAD or BODY section 2 → by linking to an external JavaScript file You may also find inline JavaScript handlers like onclick="showSomething()" in an HTML element But this way is not recommended. Instead it is better to addEventListener to HTML element in Javascript. Placing the JavaScript in the BODY section ensures that the code will be executed after all the HTML body is parsed
0 notes
Text
<script> document.addEventListener("DOMContentLoaded", function() { document.querySelector(".post-content").addEventListener("click", function() { window.location.href = "https://yourblog.com/your-blog-post"; }); }); </script>
0 notes
Text

How Do You Implement Data Validation and Error Handling for Your Web Application’s Database Input and Output?
Introduction
In today’s digital economy, businesses rely largely on web applications for client interactions, data management, and day-to-day operations. A web application‘s effectiveness is measured by its functionality and ability to manage data accurately and avoid errors that interrupt corporate processes. Data validation and error management for database input and output are critical to ensuring reliability.
Data validation guarantees that the information entered into your database satisfies the necessary criteria, preventing invalid or damaging data from entering the system. On the other side, error handling focuses on providing tools to deal with difficulties that may arise during database operations, ensuring that the program recovers gracefully.
In this article, we’ll look at how organizations may employ good data validation and error handling in web applications to streamline processes, prevent data corruption, and improve the user experience. We’ll also look at how 8 Tech Labs, a prominent mobile app development firm, can help organizations achieve these goals with competent services.
The Importance of Data Validation and Error Handling
Effective data validation and error handling are vital for any web application that interacts with databases. Without these mechanisms in place, applications are vulnerable to:
Data corruption: Invalid data may lead to inaccurate analytics and faulty business decisions.
Security breaches: Insufficient validation can leave your application exposed to threats like SQL injection.
User frustration: Poor error handling can result in a negative user experience, reducing user satisfaction and retention.
Operational inefficiencies: Uncontrolled errors may cause downtime, affecting business continuity and leading to financial losses.
By ensuring that data is properly validated and errors are managed effectively, businesses can avoid these pitfalls, ensuring smoother operations and better user experiences. The process can also improve the overall integrity of your mobile app development and app development software, ensuring both front-end and back-end work seamlessly.
How to Implement Data Validation in Your Web Application
Implementing data validation for web application input and output is a critical task to ensure that the data entered is accurate, complete, and formatted correctly. There are several ways to implement data validation, and a combination of client-side and server-side validation is often the best approach.
1. Client-Side Validation
Client-side validation is the first line of defence and happens before the data is sent to the server. This can help catch common issues early on and improve user experience by providing instant feedback.
HTML5 Form Validation: Utilize built-in HTML5 input types such as email, number, url, and tel to ensure the input is formatted correctly.
JavaScript Validation: Use JavaScript or popular libraries (like jQuery) to add custom validation rules. This can include checking if the fields are empty, verifying email formats, or matching passwords.
Example:
document.getElementById(“submit”).addEventListener(“click”, function(event){
if(document.getElementById(“email”).value == “”){
alert(“Email is required!”);
event.preventDefault();
}
});
2. Server-Side Validation
Although client-side validation is useful for immediate feedback, it’s essential to validate data on the server side as well. Server-side validation ensures that data is checked before it is inserted into the database, preventing issues such as SQL injections or data inconsistency.
Check for Null or Empty Fields: Ensure that all required fields are provided.
Data Type Validation: Confirm that the data matches the expected data type (e.g., a date field contains a valid date).
Sanitize Inputs: Remove any special characters that may pose a security risk (e.g., SQL injection attacks).
Example (PHP):
if (empty($_POST[“email”])) {
echo “Email is required”;
} else {
$email = filter_var($_POST[“email”], FILTER_SANITIZE_EMAIL);
}
3. Regular Expressions
For more complex validation (like validating phone numbers or addresses), regular expressions are often used to match input against predefined patterns. Regular expressions ensure that data conforms to specific formats.
Best Practices for Error Handling
Error handling is just as crucial as data validation in developing a dependable web application. Here’s how firms can apply efficient error management strategies:
1. Error Logging
Keep track of errors that occur throughout your online application. These logs should include detailed information like the problem message, the user’s actions when the error occurred, and the data involved. Logs allow developers to swiftly detect and resolve issues before they affect users.
2. Graceful Degradation
In the event of a problem, offer users with clear, actionable messages rather than allowing the application to crash or display cryptic technical warnings. Graceful degradation enhances the user experience by advising them of the problem without crashing the program completely.
For example, instead of the general “500 Server Error,” the program may display “We’re having some problems right now.” “Please try again later.” This decreases user irritation while maintaining trust.
3. Custom Error Pages
Create unique error pages that match your application’s look and direct users on what to do next. For example, if a user receives a 404 error, display a page with advice on how to go to the correct content.
4. Testing and Monitoring
Regularly test your error-handling procedures by simulating various types of errors and ensuring that they are handled correctly. Implementing error-tracking software (such as Sentry or Bugsnag) can help to automate this procedure.
How 8 Tech Labs Can Help
At 8 Tech Labs, we understand the importance of building robust web applications that are both reliable and secure. Our mobile app development and app development services are tailored to meet the specific needs of businesses, ensuring that data validation and error handling are implemented effectively to maximize performance and security.
IT Strategy Development: We work with businesses to create long-term strategies that leverage cutting-edge technologies for optimal growth.
Technology Solutions: Our team provides comprehensive IT solutions that streamline operations and integrate seamlessly with existing workflows.
Digital Transformation Consulting: We guide businesses through digital transformation, ensuring that web applications, mobile apps, and other technologies align with industry best practices.
IT Advisory Services: We offer expert advice on selecting the right technologies and approaches for your web applications, ensuring smooth functionality and user satisfaction.
With 8 Tech Labs’ expertise, you can ensure that your web application remains secure, reliable, and efficient, driving both immediate and long-term growth.
Read More
#8 Tech Labs#custom software development#custom software development agency#custom software development company#software development company#software developers near me#mobile app development software#bespoke software development company#bespoke software development#software development firms#software development agency#nearshore development#software engineer companies#software development services#nearshore software development company#healthcare software development companies#application development companies#qda software#develop mobile app#software development#nearshore software development#web app development
0 notes
Text
Design Interactive Web Pages with JavaScript

This magic will be behind interactive and dynamic web pages that are actually so fascinating to users. Through TCCI Computer Coaching Institute, we enable you to master this important skill of creating web experiences which leave a mark. From basic programming to further improving the web development skills, in this blog, I guide you through the core concepts of designing interactive web pages using JavaScript.
Why JavaScript for Web Interactivity?
Real-Time User Interaction: JavaScript allows for dynamic content, such as form validation, sliders, and interactive menus.
Versatility: It powers front-end features and works seamlessly with backend technologies.
Essential for Modern Web Development: JavaScript frameworks like React and Angular dominate the industry.
Key Features for Interactivity
Event Handling: Learn how to respond to user actions like clicks and keystrokes.
DOM Manipulation: Update and modify web page elements without reloading the page.
Animation and Effects: Make transitions and animations appealing to the eye.
APIs and Data Fetching: Use external data to update in real time.
Tools and Frameworks
Begin with jQuery or go for a more advanced project with modern frameworks such as Vue.js.
Example: Interactivity with JavaScript
The most basic example would be an application for a to-do list where users can add, remove, or edit tasks.
Code example:
document.getElementById('addTask').addEventListener('click', function() {
const task = document.createElement('li');
task.textContent = document.getElementById('taskInput').value;
document.getElementById('taskList').appendChild(task);
});
How TCCI Helps You Succeed
At TCCI Computer Coaching Institute, our experienced trainers provide hands-on training on JavaScript, ensuring that you get practical experience and confidence. From basic techniques to advanced techniques, we take you through each and every step.
Enroll Now
Unleash Your Potential as a Web Developer! Join our courses at TCCI and start designing interactive web pages with JavaScript. Call us at for further details.
Call now on +91 9825618292
Get information from https://tccicomputercoaching.wordpress.com/
#TCCI Computer Coaching Institute#Best Computer Training near me#JavaScript Training in Ahmedabad#Website Designing Training Institutes in Ahmedabad#Best Computer Training Institutes in Bopal Ahmedabad
0 notes
Text
Canvas 入門 その7
画像の表示方法のパターン( ①〜③ )を練習。 JavaScript の場合、変数がグローバルスコープになるために起こる「グローバル汚染」に気をつけるべく、「即時関数」をもちいる必要があるのだけれど、Clojure では気にしなくてもいいはず。 …で、ここでは、オブジェクト(ページ、画像など)が関係するなんらかの処理を、オブジェクト自身に持たせる、という、ちょっと面倒くさい記述の練習をしている。 具体的には、なにかイベント(ここでは画像の "load" )を検出した時に実行する処理として、無名関数(コールバック関数)を設定していて、その処理のなかでは、引数としてなにか処理用の関数( "fnc" )が渡されていれば、その処理にオブジェクト自身を設定して実行する、という記述です(…ふぅ。あえての一行悪文ですが、長いねぇ)。 imgLoader では、 1.画像インスタンスを生成して、 2.「どのタイミングで実行するものか」だけを指定した、具体的な中身が未定の処理をインスタンスに設定し、 3.最後に、引数 path で具体的な画像とひもづけている ;;=================== (defn imgLoader [path fnc] ;; 1.画像のインスタンスを生成する (let [target (js/Image.)] ;; 2.画像がロード完了したときの処理を先に記述する (.addEventListener target "load" (fn [] (if fnc (fnc target)))) ;; 3.画像のロードを開始するためにパスを指定する (set! (.-src target) path) )) ;;===================
(defn render6 [name] (let [canvas (.querySelector js/document.body name) ctx (.getContext canvas "2d")] (imgLoader "./img/color.jpg" (fn [img] (do ;; パターン①:等倍 (.drawImage ctx img 100 100) ;; パターン②:大きさ指定 (.drawImage ctx img 30 10 100 100) ;; パターン③:一部を切り出し+大きさを指定 (.drawImage ctx img 10 10 110 110 10 130 50 50) ) ) ) )) ;;===================
0 notes
Text
JavaScript yang ringan dan efisien sangat penting untuk meningkatkan kinerja situs web. Dengan mengurangi ukuran dan kompleksitas kode JavaScript, Anda dapat mempercepat waktu muat halaman dan meningkatkan pengalaman pengguna. Berikut adalah langkah-langkah untuk membuat JavaScript yang lebih ringan: 1. Minifikasi Kode Minifikasi adalah proses menghapus semua karakter yang tidak perlu dari kode sumber tanpa mengubah fungsionalitasnya. Ini termasuk menghapus spasi, komentar, dan karakter baru. Anda dapat menggunakan alat seperti UglifyJS, Terser, atau terser-webpack-plugin untuk melakukan minifikasi secara otomatis. Contoh: javascript Copy code // Sebelum Minifikasi function add(a, b) { return a + b; } // Setelah Minifikasi function add(a,b){return a+b;} 2. Hapus Kode yang Tidak Digunakan Saring kode Anda untuk menemukan dan menghapus fungsi, variabel, atau bagian lain yang tidak terpakai. Anda juga bisa menggunakan alat seperti PurifyCSS atau PurgeCSS untuk membersihkan kode JavaScript yang tidak diperlukan. Contoh: javascript Copy code // Kode Tidak Digunakan function unusedFunction() { console.log(“Ini tidak digunakan”); } // Hapus fungsi yang tidak terpakai 3. Gunakan Modul dan Pembagian Kode Pecah kode JavaScript Anda menjadi modul-modul kecil yang dapat dimuat secara terpisah. Ini akan mengurangi beban awal dan hanya memuat kode yang diperlukan saat itu juga. Anda bisa menggunakan teknik code splitting dengan alat seperti Webpack. Contoh: javascript Copy code // Menggunakan dynamic import import(/* webpackChunkName: “moduleName” */ ‘./moduleName’).then(module => { // Gunakan module }); 4. Optimalkan Penggunaan Library dan Framework Jika Anda menggunakan library atau framework, pastikan untuk hanya memuat bagian yang diperlukan. Misalnya, saat menggunakan lodash, Anda bisa mengimpor hanya fungsi yang diperlukan daripada seluruh library. Contoh: javascript Copy code // Mengimpor seluruh lodash import _ from ‘lodash’; // Mengimpor hanya fungsi yang diperlukan import { debounce } from ‘lodash’; 5. Gunakan Event Delegation Alih-alih menambahkan event listener ke banyak elemen, gunakan event delegation untuk menambahkan listener pada elemen induk. Ini mengurangi jumlah event listener yang aktif di DOM. Contoh: javascript Copy code // Tanpa Delegation document.querySelectorAll(‘.item’).forEach(item => { item.addEventListener(‘click’, function() { console.log(‘Item clicked’); }); }); // Dengan Delegation document.querySelector(‘.parent’).addEventListener(‘click’, function(e) { if (e.target.classList.contains(‘item’)) { console.log(‘Item clicked’); } }); 6. Optimalkan Algoritma dan Logika Tinjau algoritma dan logika dalam kode Anda. Pastikan untuk menggunakan algoritma yang efisien dan menghindari pengulangan yang tidak perlu. Contoh: javascript Copy code // Pengulangan tidak efisien for (let i = 0; i < array.length; i++) { // Proses } // Gunakan metode yang lebih efisien array.forEach(item => { // Proses }); 7. Caché Data dan Hasil Jika Anda melakukan perhitungan yang berat atau memanggil API berulang kali, pertimbangkan untuk menyimpan hasilnya dalam variabel atau menggunakan teknik caching untuk menghindari perhitungan berulang. Contoh: javascript Copy code let cachedData = {}; function fetchData(id) { if (cachedData[id]) { return cachedData[id]; } // Lakukan fetch dan simpan hasilnya cachedData[id] = fetch(`api/data/${id}`); return cachedData[id]; } 8. Gunakan Asynchronous Loading Gunakan async atau defer pada tag Dengan mengikuti langkah-langkah di atas, Anda dapat membuat JavaScript yang lebih ringan dan efisien. Hal ini tidak hanya meningkatkan ki...
0 notes
Link
DOM AddEventListener Welcome to the second season of the JavaScript tutorials. In this series of tutorials, we are going to cover more advanced topics such as DOM, BOM, local storage, APIs, Ajax, callbacks, and asynchronous functions. In this video, you will learn how to use the 'addEventListener' inside your JavaScript code. 'addEventListener' works the same way as events, with the difference that it is written next to the JavaScript code rather than inside HTML tags. Watch The Video on Youtube
0 notes
Text
Fetch Trending Topics Get Trending Topics document.getElementById('fetch-topics-form').addEventListener('submit', async function(event) event.preventDefault(); // Prevent the default form submission const apiKey = 'AIzaSyCq8IrN3wNFCJm0W6CqnbRHBRKhTYV1_es'; // Your Google Gemini API key const url = 'https://generativelanguage.googleapis.com/v1beta/models/gemini-pro:generateContent'; const data = "contents": [ "parts": [ "text": "What are the current trending topics?" ] ] ; const response = await fetch(url, method: 'POST', headers: 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + apiKey , body: JSON.stringify(data) ); if (!response.ok) document.getElementById('topic-results').innerHTML = 'Error fetching trending topics.'; return; const result = await response.json(); const topics = result.contents[0].parts[0].text; // Adjust based on the actual response structure const topicResultsDiv = document.getElementById('topic-results'); topicResultsDiv.innerHTML = 'Trending Topics:' + topics.split(',').map(topic => `$topic.trim()`).join('') + ''; );
0 notes
Text
Quando comecei a codificar em JavaScript em 2013, pensei que jQuery era o “JavaScript” real e que jQuery deveria ser incluído em todas as páginas para executar meu código JS. Caros desenvolvedores de plug-ins Mas por que? Porque todo código que copiei do StackOverflow funcionou somente após importar o jQuery! 😅 O que há de errado com jQuery jQuery tem 90 KB, mas quando reduzido tem apenas 32 KB. Isso é tão pequeno. Um bom CDN pode entregar isso em menos de 50ms! Mas não se trata do tamanho. jQuery tem cerca de 10 mil linhas de código. Você pode não estar usando nem 10% dele. Cada linha deve ser analisada e avaliada pelo navegador, o que consome muitos recursos. Este processo afeta o tempo de renderização, especialmente em dispositivos móveis. Para ver a diferença real, aqui está a mesma funcionalidade escrita em jQuery puro e JavaScript vanilla: jQuery: // jQuery const div = $("#hello-div"); for (let i = 0; i < 10000; i += 1) div.append(" Hello world "); JavaScript baunilha: // Pure JavaScript const div = document.getElementById("hello-div"); for (let i = 0; i < 10000; i += 1) const p = document.createElement("p"); p.textContent = "Hello world"; div.appendChild(p); Aqui está a diferença de desempenho: Enquanto jQuery levou 2,4s, JavaScript puro levou apenas 0,8s. Isso mostra Vanilla JavaScript é 4x mais rápido que jQuery. Alguns anos atrás, escrever funções padrão em JavaScript vanilla era uma dor e o jQuery tornou nossas vidas mais fáceis. Mas os navegadores da web evoluíram muito. A maioria das funções que você escreveu em jQuery podem ser escritas em JavaScript puro. Aqui estão alguns exemplos: 1. Solicitações Ajax Buscando dados de um URL: jQuery: $.ajax( url: '/api.json', type: 'GET' success: (data) => console.log(data) ) JavaScript baunilha: fetch('/api.json') .then(response => response.text()) .then(body => console.log(body)) 2. Encontre elementos e manipule Encontre alguns elementos do DOM (HTML) e mude de cor: jQuery: Olácomo vai você? Meu? Eu sou bom. $("p").find("span").css("color", "red"); JavaScript baunilha: Olácomo vai você? Meu? Eu sou bom. document .querySelectorAll("p > span") .forEach((elem) => (elem.style.color = "red")); 3. Mostrar/ocultar elementos Caso de uso comum de jQuery, mostrar/ocultar algo ao clicar: jQuery: Me esconda $("#button").click(function () $("#button").hide(); ); JavaScript baunilha: Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").style.display = "none"; ); 4. Animar jQuery: Me esconda $("#button").click(function () $("#button").hide("slow"); ); JavaScript baunilha: .animate opacidade: 0; transição: opacidade 0,5s de facilidade; Me esconda document.getElementById("button").addEventListener("click", function () document.getElementById("button").classList.add("animate"); ); Você pode encontrar muito mais exemplos semelhantes em: Você pode não precisar do jQuery Você deve usar ou aprender jQuery em 2020? Do jQuery ao JavaScript – Como fazer a mudança E quanto ao suporte ao navegador? A maioria das funções que usei acima são amplamente suportadas em todos os principais navegadores. Caros desenvolvedores de plug-insCaros desenvolvedores de plug-ins Geralmente é o Internet Explorer e o Opera Mini, que não suportam alguns deles. Se ainda quiser oferecer suporte a esses navegadores antigos, você pode detectar o navegador e adicionar polyfills. Aqui estão alguns polyfills para essas funções comuns: github/eventlistener-polyfill github/buscar iamdustan/smoothscroll yola/classlist-polyfill Suporte do navegador para querySelector: Suporte do navegador para fetch: Todo mundo está se mudando, exceto WordPress Graças ao avanço feito nas ferramentas de desenvolvimento front-end e no suporte do navegador,
agora podemos descartar o jQuery como uma dependência, mas você nunca notaria o contrário Caros desenvolvedores de plug-ins Bootstrap 5 – postagem no blog GitHub.com também removeu o jQuery em 2018 – Removendo jQuery do front-end do GitHub.com. Embora todos tenham começado a se afastar do jQuery, é bastante complicado no WordPress devido ao grande número de plug-ins e temas. Da recente postagem no blog de Atualizando a versão do jQuery fornecida com o WordPress: O WordPress deve descontinuar o jQuery e migrar gradualmente para o Vanilla JavaScript. Talvez você também não precise de JavaScript Caros desenvolvedores de plug-ins Como eu disse antes, a web e o JavaScript estão evoluindo rapidamente. Da mesma forma CSS. Muitas funções que eram feitas via JavaScript agora são feitas via CSS. Isso proporciona outro aumento de desempenho. Caros desenvolvedores de plug-ins Algumas delas que podem ser feitas em CSS puro: Controle deslizante de imagem – Construtor de controle deslizante CSS, Galeria CSS, Controle deslizante CSS puro Modal – Modal CSS Puro Validação de formulário – Validação de formulário HTML Indicador de rolagem – Indicador de rolagem somente CSS Acordeão – 4 maneiras de criar acordeões incríveis somente com CSS Caixa de luz – Caixa de luz CSS pura, Caixa de luz somente CSS Guias – Guias somente CSS, Guias somente CSS do Material Design Role para cima - Puro CSS Smooth-Scroll “Voltar ao topo” Rolagem suave para links – Demonstração de rolagem suave CSS Barra de navegação fixa – Cabeçalho fixo CSS puro Caros desenvolvedores de plug-ins
0 notes
Text
<script> document.addEventListener("DOMContentLoaded", function() { document.querySelector(".post-content").addEventListener("click", function() { window.location.href = "https://yourblog.com/your-blog-post"; }); }); </script>
0 notes