Search

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.


Understanding 15 Looping Methods in JavaScript: Evaluating Advantages and Drawback

1. For Loop:

for (let i = 0; i < array.length; i++) {
    console.log(array[i]);
}

Pros: Readable and commonly used. Suitable for iterating over the length of an array or a specific number of iterations.

Cons: The number of iterations must be known beforehand. Easy to make off-by-one errors.


2. For...of Loop:

for (const item of array) {
    console.log(item);
}

Pros: Readable and simple. No need to worry about indexes or the number of iterations.

Cons: Cannot directly access the index of array elements.


1. For Loop:

for (let i = 0; i < array.length; i++) {
    console.log(array[i]);
}

Pros: Readable and commonly used. Suitable for iterating over the length of an array or a specific number of iterations.

Cons: The number of iterations must be known beforehand. Easy to make off-by-one errors.


2. For...of Loop:

for (const item of array) {
    console.log(item);
}

Pros: Readable and simple. No need to worry about indexes or the number of iterations.

Cons: Cannot directly access the index of array elements.


3. For...in Loop:

for (const key in object) {
    if (object.hasOwnProperty(key)) {
        console.log(object[key]);
    }
}

Pros: Suitable for iterating over object properties. Can be used to count the number of properties in an object.

Cons: May include properties inherited from the prototype.


4. While Loop:

let i = 0;
while (i < array.length) {
    console.log(array[i]);
    i++;
}

Pros: Suitable for cases where the number of iterations is unknown beforehand.

Cons: More prone to infinite loop errors if not managed properly.


5. Do...while Loop:

let i = 0;
do {
    console.log(array[i]);
    i++;
} while (i < array.length);

Pros: Ensures that at least one iteration is done before checking the condition.

Cons: More prone to infinite loop errors if not managed properly.


6. ForEach Loop:

array.forEach(function(item) {
    console.log(item);
});

Pros: Easy to use for iterating over each element in an array. No need to worry about indexes or the number of iterations.

Cons: Cannot use break or continue statements.


7. Map Loop:

const newArray = array.map(function(item) {
    console.log(item);
    return modifiedItem;
});

Pros: Returns a new array with the transformed results of each original array element. Suitable for data transformation operations.

Cons: Cannot use break or continue statements.


8. Filter Loop:

const filteredArray = array.filter(function(item) {
    console.log(item);
    return condition;
});

Pros: Returns a new array with elements that meet certain conditions. Suitable for data filtering operations.

Cons: Cannot use break or continue statements.


9. Reduce Loop:

const result = array.reduce(function(accumulator, item) {
    console.log(item);
    return accumulator;
}, initialValue);

Pros: Accumulates the results of each array element into a single value. Suitable for data aggregation operations.

Cons: Cannot use break or continue statements.


10. For...await Loop (asynchronous):

for await (const item of asyncIterable) {
    console.log(item);
}

Pros: Suitable for iterating over asynchronous iterable objects such as Promises or generator functions.

Cons: More complex compared to synchronous loops and requires a better understanding of asynchronous programming.


11. For...await...of Loop (asynchronous):

for await (const item of asyncIterable) {
    console.log(item);
}

Pros: Suitable for iterating over asynchronous iterable objects such as Promises or generator functions.

Cons: More complex compared to synchronous loops and requires a better understanding of asynchronous programming.


12. Loop with Object.entries():

for (const [key, value] of Object.entries(object)) {
    console.log(value);
}

Pros: Allows iteration through object properties and values.

Cons: Not suitable for objects with non-enumerable properties, such as properties inherited from the prototype.


13. Looping with Object.keys():

Object.keys(object).forEach(function(key) {
    console.log(object[key]);
});

Pros: Allows iteration through the key properties of an object. Suitable for cases where you only need to access the value of each object property.

Cons: Does not provide direct access to both the value and key of the object simultaneously.


14. Looping with Array.from():


Array.from(arrayLikeObject).forEach(function(item) {
    console.log(item);
});

15. Looping with Array.entries():

for (const [index, value] of array.entries()) {
    console.log(index, value);
}

Pros: Allows iteration through the index and value of each element in the array simultaneously.

Cons: Not suitable for non-array objects.


16. Looping with Array.from() and keys():

Array.from(array.keys()).forEach(function(index) {
    console.log(array[index]);
});

Pros: Allows iteration through the index of each element in the array.

Cons: Requires conversion of array-like object to array beforehand.



Mastering Asynchronous JavaScript: A Comprehensive Guide for Modern Developers

Introduction: In the dynamic landscape of web development, the ability to handle asynchronous operations is crucial for building responsive and efficient applications. JavaScript, as a versatile and widely-used programming language, offers a range of powerful tools for managing asynchronous tasks. This comprehensive guide aims to equip developers with a deep understanding of asynchronous JavaScript and empower them to leverage its full potential in their projects. From callbacks to promises and async/await, we'll embark on a journey to unravel the intricacies of asynchronous programming in JavaScript.

Section 1: The Evolution of Asynchronous JavaScript In this section, we'll delve into the historical evolution of asynchronous programming in JavaScript. We'll explore the challenges of synchronous code execution, the emergence of callbacks as a solution, and the limitations they presented. We'll then transition to the introduction of promises and how they revolutionized asynchronous code, paving the way for the elegant async/await syntax.

Section 2: Understanding Callbacks Callbacks have long been a fundamental concept in asynchronous JavaScript. We'll take a deep dive into understanding callbacks, their role in event-driven programming, and the potential issues associated with callback hell. Through practical examples, we'll demonstrate how to effectively use callbacks and mitigate common pitfalls.

Section 3: Embracing Promises Promises have emerged as a game-changer in asynchronous JavaScript, offering a more structured and intuitive approach to handling asynchronous operations. We'll explore the anatomy of promises, chaining multiple asynchronous tasks, error handling, and the transition from callbacks to promises. Real-world scenarios will illustrate the benefits of using promises for asynchronous code.

Section 4: Mastering async/await The async/await syntax has brought a new level of elegance and readability to asynchronous JavaScript. We'll guide developers through the syntax and semantics of async functions, the use of await to handle asynchronous operations, and error handling within async/await constructs. Practical examples will showcase the transformation of complex asynchronous code into a more linear and intuitive form.

Section 5: Concurrency and Parallelism Asynchronous JavaScript enables developers to achieve concurrency and parallelism, optimizing the utilization of system resources. We'll discuss the concepts of concurrency and parallelism in the context of JavaScript, and how asynchronous programming facilitates non-blocking I/O operations, event-driven architectures, and multi-threaded execution.

Section 6: Real-world Applications In this section, we'll demonstrate the practical applications of asynchronous JavaScript in real-world scenarios. From fetching data from remote APIs to handling user interactions and optimizing performance, we'll showcase how asynchronous programming enhances the responsiveness and efficiency of web applications.

Conclusion: Mastering asynchronous JavaScript is a fundamental skill for modern developers seeking to build robust, high-performance web applications. By gaining a comprehensive understanding of callbacks, promises, async/await, and the principles of asynchronous programming, developers can elevate their coding proficiency and deliver exceptional user experiences. This guide serves as a valuable resource for developers looking to harness the full potential of asynchronous JavaScript and navigate the complexities of modern web development with confidence.