• 🌙 Community Spirit

    Ramadan Mubarak! To honor this month, Crax has paused NSFW categories. Wishing you peace and growth!

Source Code Simple and useful JavaScript code snippets for various tasks (Part 2) (1 Viewer)

Currently reading:
 Source Code Simple and useful JavaScript code snippets for various tasks (Part 2) (1 Viewer)

Recently searched:

testrest

Member
LV
1
Joined
Oct 19, 2022
Threads
11
Likes
3
Awards
4
Credits
1,067©
Cash
0$
6. **Iterating Over an Array**:
```javascript
const numbers = [1, 2, 3, 4, 5];
numbers.forEach(function(number) {
console.log(number);
});
```
This code uses the `forEach` method to iterate over each element in the `numbers` array and print them to the console.

7. **Toggle CSS Class**:
```javascript
const element = document.getElementById("myElement");
element.classList.toggle("active");
```
Replace "myElement" with the ID of an HTML element. This code toggles the CSS class "active" on the specified element, allowing you to control its styling.

8. **LocalStorage**:
```javascript
localStorage.setItem("username", "John");
const savedUsername = localStorage.getItem("username");
console.log(savedUsername);
```
This code stores the value "John" in the browser's local storage under the key "username" and then retrieves and logs it to the console.

9. **Timer (setTimeout)**:
```javascript
setTimeout(function() {
console.log("Delayed message");
}, 2000); // Delays for 2 seconds (2000 milliseconds)
```
This code sets a timer to execute a function after a 2-second delay. It's commonly used for tasks like showing notifications.

10. **Basic Animation (CSS Transitions)**:
```javascript
const element = document.getElementById("myElement");
element.style.transition = "transform 1s ease-in-out";
element.style.transform = "translateX(100px)";
```
Replace "myElement" with the ID of an HTML element. This code adds a CSS transition to smoothly animate the horizontal translation of the element by 100 pixels over 1 second with an ease-in-out timing function.

These additional JavaScript snippets cover tasks such as iterating over arrays, toggling CSS classes, working with local storage, setting timers, and creating basic animations. They expand your toolkit for web development and interactivity.
 

Create an account or login to comment

You must be a member in order to leave a comment

Create account

Create an account on our community. It's easy!

Log in

Already have an account? Log in here.

Tips
Recently searched:

Similar threads

Users who are viewing this thread

Top Bottom