Source Code Simple and useful JavaScript code snippets for various tasks (Part 3)

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

testrest

Member
LV
1
Joined
Oct 19, 2022
Threads
11
Likes
3
Awards
4
Credits
1,064©
Cash
0$
11. **Random Number Generator**:
```javascript
const randomNum = Math.floor(Math.random() * 100) + 1;
console.log(`Random number between 1 and 100: ${randomNum}`);
```
This code generates a random integer between 1 and 100 and logs it to the console. You can adjust the range as needed.

12. **String Interpolation**:
```javascript
const name = "Alice";
const greeting = `Hello, ${name}!`;
console.log(greeting);
```
This code uses template literals to create a dynamic string with the value of the `name` variable inserted into the greeting.

13. **Check if Element Exists**:
```javascript
if (document.getElementById("myElement")) {
console.log("Element exists.");
} else {
console.log("Element does not exist.");
}
```
This code checks if an HTML element with the ID "myElement" exists on the page and logs the result.

14. **Scroll to Top Button**:
```javascript
const scrollToTopButton = document.getElementById("scrollToTop");

scrollToTopButton.addEventListener("click", function() {
window.scrollTo({
top: 0,
behavior: "smooth"
});
});
```
This code adds a click event listener to a button with the ID "scrollToTop" that, when clicked, smoothly scrolls the page to the top.

15. **Simple Form Validation**:
```javascript
const form = document.getElementById("myForm");

form.addEventListener("submit", function(event) {
if (!form.checkValidity()) {
alert("Please fill out the required fields.");
event.preventDefault();
}
});
```
This code adds a form submission event listener to check if all required fields are filled out. If not, it displays an alert and prevents the form from submitting.

These additional JavaScript snippets cover a range of practical tasks, including random number generation, string interpolation, checking element existence, implementing a "scroll to top" button, and basic form validation.
 

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

Similar threads

Top Bottom