Search

Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

playing audio javascript


<!-- Buttons to control audio playback -->
<button onclick = "playAudio()" > Play Audio < /button>
<button onclick = "pauseAudio()" > Pause Audio < /button

Create an Audio object and provide the path to your audio file


var audio = new Audio('path/to/your/audiofile.mp3');

Function to play the audio


function playAudio() {
    audio.play(); // Play the audio
}

Function to pause the audio


function pauseAudio() {
    audio.pause(); // Pause the audio
}

Function to change the volume


function changeVolume(vol) {
    audio.volume = vol; // Set the volume of the audio
}

Listen for the 'ended' event on the audio element


audio.addEventListener('ended', function() {
    audio.currentTime = 0; // Reset audio to the beginning
    audio.play(); // Play the audio again
});

EXTRA BONUS fade in and fade out



<!--Input range to adjust the volume -->
<input type = "range" min = "0" max = "1" step = "0.1" value = "1" onchange = "changeVolume(this.value)" >

Function to fade out the audio


function fadeOut() {
    var fadeOutInterval = setInterval(function() {
        if (audio.volume > 0) {
            audio.volume -= 0.1; // Decrease volume by 0.1
        } else {
            clearInterval(fadeOutInterval); // Stop fading when volume reaches 0
            audio.pause(); // Pause audio playback
        }
    }, fadeInterval);
}

Function to fade in the audio

function fadeIn() {
    audio.play(); // Start audio playback
    var fadeInInterval = setInterval(function() {
        if (audio.volume < 1) {
            audio.volume += 0.1; // Increase volume by 0.1
        } else {
            clearInterval(fadeInInterval); // Stop fading when volume reaches 1
        }
    }, fadeInterval);
}

Auto like facebook 2024 on june, anti spam and no need install more aplication



This script will automatically like posts on Facebook without needing to install any additional applications. The script is designed to mimic human behavior, ensuring that your account remains safe from being banned. Simply copy and paste this script into your browser's console. I personally use Chrome, and this script is safe to use—it does not collect any of your data. You can verify its safety yourself, as it consists of only a few lines of code.

How to Use:

  1. Open Facebook in your Chrome browser.
  2. Right-click on the page and select "Inspect" or press Ctrl+Shift+I to open the Developer T
  3. Go to the "Saurces" tab.
  4. Click Snippet, make new snippet;
  5. copy the script auto like facebook to editor on right
  6. on file your made on snippet, click right and click run

The script will now run , automatically liking posts as if you were doing it manually. Feel free to monitor the console for messages indicating that posts are being liked.

Disclaimer: This script is provided for educational purposes. Use it responsibly and be aware of Facebook's terms of service.


Function to check if the element is in view


function isElementInViewport(el) {
  let rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}
Function to get all elements in the viewport




function getAllElementsInViewport() {
  // Get all elements in the document
  let allElements = document.querySelectorAll('div[aria-label=Like]:not(.sudah)');
  // Array to store elements in the viewport
  let elementsInViewport = [];
  // Iterate through all elements and check if they are in the viewport
  allElements.forEach(element => {
    if (isElementInViewport(element)) {
      elementsInViewport.push(element);
    }
  });
  return elementsInViewport;
}

Add a scroll event listener to the window


window.addEventListener('scroll', function() {
  // Get all elements in the viewport when the user scrolls
  let elementsInViewport = getAllElementsInViewport();
 // Iterate through the NodeList and check for the attribute and value
    console.log(elementsInViewport.length+' like button availible on vieport')
   let no = 0
   elementsInViewport.forEach(element => {
     no +=1;
          element.classList.add('sudah');
      let myArray = Array.from({ length: 20 }, () => getRandomNumber(0, 1));
      let randomElement = myArray[Math.floor(Math.random() * myArray.length)];
          if(randomElement==1){
             element.click(); 
             console.log(no+" element clicked")
          }else{
            console.log(no+" element not clicked")
          }
        });
});

Function to scroll the page by 40 pixels



function scrollBy40px() {
    let myArray = Array.from({ length: 20 }, () => getRandomNumber(400, 1000));
    let randomElement = myArray[Math.floor(Math.random() * myArray.length)];
  window.scrollBy(0, randomElement); // Scroll vertically by 40 pixels
  doit()
}
function doit() {
    let myArray = Array.from({ length: 20 }, () => getRandomNumber(800, 10000));
    let randomElement = myArray[Math.floor(Math.random() * myArray.length)];
    console.log('windows will scroll after random mili second. wait about '+randomElement)
    setTimeout(scrollBy40px, randomElement);
}
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
doit()
For those of you building networks on both personal Facebook accounts and Facebook fan pages, liking other people's posts is very beneficial for expanding our social network. Indirectly, Facebook's algorithm will favor our accounts, helping them grow faster. This script will make it easier to develop our Facebook pages without being considered spam

full script---- copy to your snippets
-----------------------------------------------------------

// Function to check if the element is in view
function isElementInViewport(el) {
  let rect = el.getBoundingClientRect();
  return (
    rect.top >= 0 &&
    rect.left >= 0 &&
    rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) &&
    rect.right <= (window.innerWidth || document.documentElement.clientWidth)
  );
}

// Function to get all elements in the viewport
function getAllElementsInViewport() {
  // Get all elements in the document
  let allElements = document.querySelectorAll('div[aria-label=Like]:not(.sudah)');

  // Array to store elements in the viewport
  let elementsInViewport = [];

  // Iterate through all elements and check if they are in the viewport
  allElements.forEach(element => {
    if (isElementInViewport(element)) {
      elementsInViewport.push(element);
    }
  });

  return elementsInViewport;
}

// Add a scroll event listener to the window
window.addEventListener('scroll', function() {
  // Get all elements in the viewport when the user scrolls
  let elementsInViewport = getAllElementsInViewport();
 // Iterate through the NodeList and check for the attribute and value
    console.log(elementsInViewport.length+' like button availible on vieport')
   let no = 0
   elementsInViewport.forEach(element => {
     no +=1;
          element.classList.add('sudah');
      let myArray = Array.from({ length: 20 }, () => getRandomNumber(0, 1));
      let randomElement = myArray[Math.floor(Math.random() * myArray.length)];
          if(randomElement==1){
             element.click(); 
             console.log(no+" element clicked")
          }else{
            console.log(no+" element not clicked")
          }
         
        });
});
// Function to scroll the page by 40 pixels
function scrollBy40px() {
    let myArray = Array.from({ length: 20 }, () => getRandomNumber(400, 1000));
    let randomElement = myArray[Math.floor(Math.random() * myArray.length)];
  window.scrollBy(0, randomElement); // Scroll vertically by 40 pixels
  doit()
}

function doit() {
    let myArray = Array.from({ length: 20 }, () => getRandomNumber(800, 10000));
    let randomElement = myArray[Math.floor(Math.random() * myArray.length)];
    console.log('windows will scroll after random mili second. wait about '+randomElement)
    setTimeout(scrollBy40px, randomElement);
}
function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}
doit()

-----------------------------------------------------

for more, just watch this video

Demystifying AJAX: Choosing the Best Method for Data Fetching in JavaScript

1. Using XMLHttpRequest to load data from a URL


function loadDataWithXHR() {
    const xhr = new XMLHttpRequest();
    xhr.open("GET", "https://jsonplaceholder.typicode.com/posts/1", true);
    xhr.onload = function() {
        if (xhr.status === 200) {
            console.log('XMLHttpRequest:', xhr.responseText);
        } else {
            console.error("Error loading data");
        }
    };
    xhr.send();
}
loadDataWithXHR(); // Call the function to load data using XMLHttpRequest

Purpose: Sending HTTP requests to the server and handling the response directly.

Pros: Compatible with most browsers, including older ones.

Cons: Complex API and requires more code compared to modern methods.


2. Using Fetch API to load data from a URL

Purpose: Loading data from a URL in a more modern and understandable way.

Pros: Simpler and more readable syntax, promise support.

Cons: Not supported by all browsers, requires polyfill or transpiler to support older browsers.



function loadDataWithFetch() {
    fetch("https://jsonplaceholder.typicode.com/posts/1")
        .then(response => response.json())
        .then(data => {
            console.log('Fetch API:', data);
        })
        .catch(error => console.error('Error:', error));
}
loadDataWithFetch(); // Call the function to load data using Fetch API

3. Using jQuery to load data from a URL


function loadDataWithjQuery() {
    $.ajax({
        url: "https://jsonplaceholder.typicode.com/posts/1",
        type: "GET",
        success: function(data) {
            console.log('jQuery AJAX:', data);
        },
        error: function() {
            console.error("Error loading data");
        }
    });
}
loadDataWithjQuery(); // Call the function to load data using jQuery AJAX

Purpose: Facilitates interaction with DOM and AJAX requests with concise syntax.

Pros: Concise and easy-to-use syntax, compatible with various browsers.

Cons: Not included in the browser's built-in functionalities, requires additional library and larger file size.



4. Using Axios to load data from a URL


function loadDataWithAxios() {
    axios.get("https://jsonplaceholder.typicode.com/posts/1")
        .then(response => {
            console.log('Axios:', response.data);
        })
        .catch(error => console.error('Error:', error));
}
loadDataWithAxios(); // Call the function to load data using Axios

Purpose: Easy-to-use HTTP client library for making AJAX requests.

Pros: Easy-to-read and understand syntax, promise support, cancellation feature, and better error handling.

Cons: Requires additional installation, not included in the browser's built-in functionalities.



5. Using Async/Await with Fetch API to load data from a URL


async function loadDataWithAsyncAwait() {
    try {
        const response = await fetch("https://jsonplaceholder.typicode.com/posts/1");
        const data = await response.json();
        console.log('Async/Await with Fetch API:', data);
    } catch (error) {
        console.error('Error:', error);
    }
}
loadDataWithAsyncAwait(); // Call the function to load data using Async/Await with Fetch API

Purpose: Loading data asynchronously with cleaner syntax using async/await.

Pros: Easier-to-read syntax, reduces "callback hell," promise support.

Cons: Not supported by all browsers, requires polyfill or transpiler to support older browsers.


Determining the best method depends on the specific needs of your project. However, here are some general considerations:


Fetch API: If you're looking for a modern solution and want to avoid dependency on third-party libraries, Fetch API is a good choice. It has a simple and understandable syntax and supports promises.


Axios: If you need advanced feature support such as request cancellation or better error handling, Axios is a good choice. It also has an easy-to-read and understand syntax.


Async/Await with Fetch API: If you want to avoid callback hell and prefer cleaner, more maintainable code, using async/await with Fetch API is a good choice. However, keep in mind that async/await is not supported in all browsers without polyfills or transpilers.


Each of these options has its own advantages and disadvantages, and the best one depends on the needs and preferences of your specific project.



Maximizing Code Efficiency: Best Practices for Optimizing Key Existence Checks in JavaScript


const obj = { name: 'John', age: 30, [Symbol('id')]: 123 };

1. `in` Operator

console.log('name' in obj);   // ---> true
console.log('gender' in obj); // ---> false

Pros:

- Easy to use.

- Can check for inherited properties (properties from the prototype chain).

Cons:

- Includes inherited properties, not just own properties.


2. `hasOwnProperty()`

console.log(obj.hasOwnProperty('name'));   // ---> true
console.log(obj.hasOwnProperty('gender'));//---> false

Pros:

- Checks only own properties of the object, not inherited ones.

Cons:

- If the object has a property that overrides this method, the result might be unexpected.


3. `Object.prototype.hasOwnProperty.call()`

console.log(Object.prototype.hasOwnProperty.call(obj, 'name'));   // ---> true
console.log(Object.prototype.hasOwnProperty.call(obj, 'gender'));//---> false

Pros:

- Avoids issues if the object has a property that overrides `hasOwnProperty`.

Cons:

- More verbose compared to using `hasOwnProperty` directly.


4. Direct Property Access

console.log(obj.name !== undefined);   // ---> true
console.log(obj.gender !== undefined);//---> false

Pros:

- Very simple and easy to understand.

Cons:

- Cannot distinguish between properties that don't exist and properties that exist but have the value `undefined`.


5. `Object.keys()`

console.log(Object.keys(obj).includes('name'));   // ---> true
console.log(Object.keys(obj).includes('gender'));//---> false

Pros:

- Returns an array of the object's own property names.

Cons:

- Inefficient for large objects because it creates an array of all keys.


6. `Object.hasOwn()`

console.log(Object.hasOwn(obj, 'name'));   // ---> true
console.log(Object.hasOwn(obj, 'gender'));//---> false

Pros:

- Modern alternative to `hasOwnProperty`, more readable and writable.

Cons:

- Not supported in older environments (introduced in ECMAScript 2022).


7. `Object.prototype.propertyIsEnumerable()`

console.log(obj.propertyIsEnumerable('name'));     // ---> true
console.log(obj.propertyIsEnumerable('toString'));//---> false
console.log(obj.propertyIsEnumerable('gender'));  // ---> false

Pros:

- Checks if a property is an own property and is enumerable (iterable).

Cons:

- Not very commonly used, so it might be less familiar.


8. Using `Map`

const map = new Map();
map.set('name', 'John');
console.log(map.has('name')); // ---> true
console.log(map.has('age')); // ---> false

Pros:

- Ideal for dynamic key-value collections.

Cons:

- Not suitable for simple objects or structured data like JSON.


9. Using `WeakMap`

const weakObj = {};
const weakMap = new WeakMap();
weakMap.set(weakObj, 'some value');
console.log(weakMap.has(weakObj));    // ---> true
const anotherObj = {};
console.log(weakMap.has(anotherObj));//---> false

Pros:

- Useful for memory-efficient key-value pairs where keys are objects.

Cons:

- Keys must be objects, and it's not enumerable or iterable.


10. `Reflect.has()`

console.log(Reflect.has(obj, 'name'));   // ---> true
console.log(Reflect.has(obj, 'gender'));//---> false

Pros:

- Similar to the `in` operator but more consistent as part of the Reflect API.

Cons:

- Less commonly used than the `in` operator.


11. Using Try-Catch (for special cases)

const objWithGetter = {
  get name() {
    throw new Error('Error accessing name');
  },
  age: 30
};
function hasProperty(obj, key) {
  try {
    return key in obj;
  } catch (e) {
    return false;
  }
}
console.log(hasProperty(objWithGetter, 'name'));//---> false
console.log(hasProperty(objWithGetter, 'age'));//---> true

Pros:

- Handles cases where accessing properties might throw errors (e.g., getters).

Cons:

- More complex and typically not needed unless dealing with potential errors.


12. `Object.getOwnPropertyNames()`

console.log(Object.getOwnPropertyNames(obj).includes('name'));   // ---> true
console.log(Object.getOwnPropertyNames(obj).includes('gender'));//---> false

Pros:

- Returns an array of all own property names (including non-enumerable properties).

Cons:

- Inefficient for large objects because it creates an array of all property names.


13. `Object.getOwnPropertySymbols()`

const sym = Symbol('id');
const symObj = { [sym]: 'symbolic value' };
console.log(Object.getOwnPropertySymbols(symObj).includes(sym));       // ---> true
const anotherSym = Symbol('another');
console.log(Object.getOwnPropertySymbols(symObj).includes(anotherSym));//---> false

Pros:

- Allows checking for symbol-keyed properties.

Cons:

- Not useful for checking regular string-keyed properties.


14. `Object.entries()`

console.log(Object.entries(obj).some(([key]) => key === 'name'));   // ---> true
console.log(Object.entries(obj).some(([key]) => key === 'gender'));//---> false

Pros:

- Checks both keys and values, useful for more complex checks.

Cons:

- Inefficient for large objects because it creates an array of all entries.


15. `Object.fromEntries()`

const objArray = [['name', 'John'], ['age', 30]];
const newObj = Object.fromEntries(objArray);
console.log('name' in newObj);   // ---> true
console.log('gender' in newObj);//---> false

Pros:

- Useful for creating objects from key-value pairs.

Cons:

- Requires array input, not a direct check.


About Modern JavaScript (ES6+)

Modern JavaScript (ES6+) is the latest version of the JavaScript programming language, which includes features and syntax enhancements introduced in ECMAScript 2015 (ES6) and later versions. ES6+ brings significant improvements to JavaScript, such as arrow functions, template literals, destructuring assignment, classes, modules, and more. These features enhance the readability, maintainability, and expressiveness of JavaScript code, making it more powerful and efficient for modern web development.

 learning modern JavaScript (ES6+) is definitely worth it in 2024 and beyond. JavaScript remains a fundamental language for web development, and its popularity continues to grow with the rise of frontend frameworks like React, Vue, and Angular, as well as backend frameworks like Node.js. ES6+ features and syntax enhancements have become standard in modern web development, and mastering them will make you a more proficient and versatile developer. Additionally, as the JavaScript ecosystem continues to evolve, staying up-to-date with the latest language features will ensure that you are well-equipped to tackle new challenges and opportunities in the field of web development.

 differences between modern JavaScript (ES6+) and the earlier versions of JavaScript. Here are some key differences:

  1. Arrow Functions: ES6 introduced arrow functions, which provide a more concise syntax for defining functions and handle the "this" keyword differently compared to traditional function expressions.

  2. Template Literals: ES6 introduced template literals, which allow for easier string interpolation and multiline strings compared to the traditional string concatenation.

  3. Destructuring Assignment: ES6 introduced destructuring assignment, which provides a convenient way to extract values from arrays or objects and assign them to variables.

  4. Classes: ES6 introduced class syntax for defining objects and their prototypes, providing a more familiar and structured way to work with object-oriented programming in JavaScript.

  5. Modules: ES6 introduced native support for modules, allowing developers to organize their code into reusable and maintainable modules.

  6. Let and Const: ES6 introduced block-scoped variables using the "let" and "const" keywords, providing a more predictable and controlled way to declare variables.

  7. Promises: ES6 introduced native support for promises, providing a cleaner and more structured way to work with asynchronous operations compared to callback-based approaches.

These are just a few examples of the many enhancements and additions that ES6 brought to JavaScript, making it more powerful, expressive, and developer-friendly.

Here's an example of an arrow function in modern JavaScript (ES6+):

Traditional Function Expression:

function multiply(a, b) {
  return a * b;
}

Arrow Function Equivalent:

const multiply = (a, b) => a * b;

In the arrow function example, the parameters are enclosed in parentheses, followed by the arrow (=>) and the expression to be returned. Arrow functions provide a more concise syntax for defining functions, especially for simple one-liners like the example above.


! Here's an example of using template literals in modern JavaScript (ES6+):

Traditional String Concatenation:

const name = "Alice";
const greeting = "Hello, " + name + "!";

Template Literal Equivalent:

const name = "Alice";
const greeting = `Hello, ${name}!`;

In the template literal example, the string is enclosed in backticks (`), and the variable "name" is interpolated using the ${} syntax. This provides a more convenient and readable way to perform string interpolation and create multiline strings.

example of using destructuring assignment in modern JavaScript (ES6+):

Destructuring Assignment with Arrays:

const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;

console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]

Destructuring Assignment with Objects:

const person = { name: "Alice", age: 30, city: "New York" };
const { name, age } = person;

console.log(name); // Output: "Alice"
console.log(age); // Output: 30

In the examples above, destructuring assignment allows you to extract values from arrays or objects and assign them to variables using a concise and expressive syntax. This feature is particularly useful for working with complex data structures in JavaScript.

example of using classes in modern JavaScript (ES6+):

class Animal {
  constructor(name, sound) {
    this.name = name;
    this.sound = sound;
  }

  makeSound() {
    console.log(`${this.name} makes a ${this.sound} sound.`);
  }
}

const cat = new Animal("Cat", "meow");
cat.makeSound(); // Output: Cat makes a meow sound.

In the example above, the "Animal" class is defined using the class syntax introduced in ES6. It has a constructor method for initializing object properties and a method called "makeSound" for displaying the sound of the animal. This class-based approach provides a more structured and familiar way to work with object-oriented programming in JavaScript.

 example of using modules in modern JavaScript (ES6+):

Module Export (math.js):

export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;

Module Import (main.js):

import { add, subtract } from './math.js';

console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2

In the example above, the "math.js" file exports two functions using the "export" keyword, and the "main.js" file imports and uses these functions using the "import" statement. This modular approach allows developers to organize their code into reusable and maintainable modules, making it easier to manage and scale large codebases.

 example of using block-scoped variables with "let" and "const" in modern JavaScript (ES6+):

Using "let" for Block-Scoped Variables:

function printNumbers() {
  for (let i = 0; i < 5; i++) {
    console.log(i);
  }
  console.log(i); // Error: i is not defined
}
printNumbers();

Using "const" for Block-Scoped Constants:

const PI = 3.14;
// PI = 3.14159; // Error: Assignment to constant variable
console.log(PI); // Output: 3.14

In the examples above, the "let" keyword is used to declare block-scoped variables, and the "const" keyword is used to declare block-scoped constants. Block-scoped variables and constants provide a more predictable and controlled way to declare variables, reducing the risk of unintended variable hoisting and reassignment.

function fetchData() {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      const data = "This is the fetched data";
      resolve(data);
    }, 2000);
  });
}

fetchData()
  .then((data) => {
    console.log(data); // Output after 2 seconds: This is the fetched data
  })
  .catch((error) => {
    console.error(error);
  });

you don't need to install anything specific, as ES6+ features are supported by modern web browsers and Node.js. However, if you want to ensure compatibility with older browsers or use the latest language features without worrying about compatibility, you can use a transpiler like Babel.

Here's what you can do to start using ES6+ features:

  1. For Browser Development:

    • Use a modern web browser that supports ES6+ features. Most modern browsers like Chrome, Firefox, Safari, and Edge have good support for ES6+ features.
    • If you need to support older browsers, you can use a tool like Babel to transpile your ES6+ code into ES5, which is widely supported across browsers.
  2. For Node.js Development:

    • Use a recent version of Node.js, as it has good support for ES6+ features.
    • If you need to use the latest language features without worrying about Node.js version compatibility, you can use Babel to transpile your code.
  3. Using Babel:

    • If you choose to use Babel, you can install it using npm (Node.js package manager) by running the following command in your project directory:
      npm install @babel/core @babel/cli @babel/preset-env --save-dev
      
    • You can then configure Babel to transpile your ES6+ code by creating a .babelrc file in your project directory and specifying the preset configuration.

By following these steps, you can start using modern JavaScript (ES6+) features in your web development projects.