Photo by Gabriel Heinzer on Unsplash

JS Code Snippets

Parakh Srivastava

--

Introduction

Code snippets are small pieces of code that are often used to perform common tasks or functions. They can be a valuable tool for developers, as they allow you to quickly and easily reuse code without having to write it from scratch.

In this article, we will explore code snippets in JavaScript, including what they are, how they can be useful, and how to create and use them. We will also look at some examples of common code snippets in JavaScript and how they can be used in different contexts. Whether you are a beginner or an experienced developer, code snippets can help you save time and improve your productivity.

Slider in JS

<input type="range" min="0" max="100" value="50" class="slider">

<script>
const slider = document.querySelector('.slider');
console.log(slider.value); // logs the current value of the slider
</script>

This code snippet creates an HTML input element with a type of "range" and sets the minimum and maximum values to 0 and 100, respectively. The initial value of the slider is set to 50. The JavaScript code selects the input element using the querySelector method and stores it in a variable called slider. The current value of the slider can be accessed using the value property of the slider variable.

To use this code snippet, you can simply copy and paste it into your HTML and JavaScript files, and then customize the minimum, maximum, and initial values as needed. You can also add additional event listeners or logic to the JavaScript code to handle user input or perform other tasks when the slider value is changed.

Counter in JS

<button id="increment">Increment</button>
<button id="decrement">Decrement</button>
<p id="counter">0</p>

<script>
const incrementButton = document.querySelector('#increment');
const decrementButton = document.querySelector('#decrement');
const counter = document.querySelector('#counter');

let count = 0;

incrementButton.addEventListener('click', () => {
count += 1;
counter.textContent = count;
});

decrementButton.addEventListener('click', () => {
count -= 1;
counter.textContent = count;
});
</script>

This code snippet creates two HTML buttons, one for incrementing the counter and one for decrementing it, and a paragraph element to display the current count. The JavaScript code selects the buttons and counter-element using the querySelector method and stores them in variables. It also defines a count variable that is initialized to 0.

The code then adds event listeners to the buttons that are triggered when they are clicked. The event listener for the increment button increments the count variable by 1 and updates the counter element with the new value. The event listener for the decrement button decrements the count variable by 1 and updates the counter element with the new value.

To use this code snippet, you can simply copy and paste it into your HTML and JavaScript files and customize the buttons and counter-element as needed. You can also add additional logic or event listeners to the JavaScript code to handle different scenarios or to perform other tasks when the counter is incremented or decremented.

Image Slider in JS

<div id="slider">
<img src="image1.jpg" alt="Image 1">
<img src="image2.jpg" alt="Image 2">
<img src="image3.jpg" alt="Image 3">
</div>

<button id="prev">Prev</button>
<button id="next">Next</button>

<script>
const slider = document.querySelector('#slider');
const prevButton = document.querySelector('#prev');
const nextButton = document.querySelector('#next');
let currentIndex = 0;

prevButton.addEventListener('click', () => {
currentIndex -= 1;
if (currentIndex < 0) {
currentIndex = slider.children.length - 1;
}
showSlide(currentIndex);
});

nextButton.addEventListener('click', () => {
currentIndex += 1;
if (currentIndex > slider.children.length - 1) {
currentIndex = 0;
}
showSlide(currentIndex);
});

function showSlide(index) {
for (let i = 0; i < slider.children.length; i++) {
slider.children[i].style.display = 'none';
}
slider.children[index].style.display = 'block';
}
</script>

This code snippet creates a div element to contain the images and two buttons, one for navigating to the previous image and one for navigating to the next image. The JavaScript code selects the elements using the querySelector method and stores them in variables. It also defines a currentIndex variable that is initialized to 0 and represents the index of the current image.

The code then adds event listeners to the buttons that are triggered when they are clicked. The event listener for the previous button decrements the currentIndex variable by 1 and checks if it is less than 0. If it is, it sets the currentIndex to the last image in the slider. The event listener for the next button increments the currentIndex variable by 1 and checks if it is greater than the last image in the slider. If it is, it sets the currentIndex to the first image in the slider.

Both event listeners call the showSlide function, which takes an index as an argument and displays the image with that index by setting the display style of all images to "none" except for the image with the specified index.

To use this code snippet, you can simply copy and paste it into your HTML and JavaScript files and customize the images, slider container, and buttons as needed. You can also add additional logic or event listeners to the JavaScript code to handle different scenarios or to perform other tasks when the image is changed.

AutoScroll in JS

<div id="content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Sed iaculis nisi et lacus facilisis, in dignissim elit luctus.</p>
<p>Pellentesque viverra tellus a nisi lobortis, et ornare dolor elementum.</p>
<p>Maecenas aliquet elementum magna a dictum.</p>
<p>Suspendisse ac lectus auctor, fermentum nibh sit amet, sodales ipsum.</p>
</div>

<script>
const content = document.querySelector('#content');
let isScrolling = false;

function scrollContent() {
isScrolling = true;

const currentTop = content.scrollTop;
const destination = content.scrollHeight - content.clientHeight;
const distance = destination - currentTop;
const duration = 2000; // duration in milliseconds
const start = Date.now();

function step() {
const elapsed = Date.now() - start;
const progress = Math.min(1, elapsed / duration);
content.scrollTop = currentTop + distance * progress;

if (elapsed < duration) {
requestAnimationFrame(step);
} else {
isScrolling = false;
}
}

requestAnimationFrame(step);
}

content.addEventListener('mouseenter', () => {
isScrolling = false;
});

content.addEventListener('mouseleave', () => {
if (!isScrolling) {
scrollContent();
}
});
</script>

This code snippet creates a div element containing some content and selects it using the querySelector method. It also defines a isScrolling variable that is initialized to false and is used to track whether the content is currently scrolling.

The code then defines a scrollContent function that uses the requestAnimationFrame method to smoothly scroll the content from its current position to the bottom of the container over a specified duration. The function also updates the isScrolling variable to true while the content is scrolling.

The code adds two event listeners to the content element: one for the mouseenter event and one for the mouseleave event. The event listener for the mouseenter event sets the isScrolling variable to false when the user's mouse enters the content, which stops the scrolling. The event listener for the mouseleave event checks the value of the isScrolling variable and, if it is false, calls the scrollContent function to start scrolling again.

To use this code snippet, you can simply copy and paste it into your HTML and JavaScript files and customize the content element and the duration of the scroll as needed. You can also add additional logic or event listeners to the JavaScript code to handle different scenarios or to perform other tasks when the content is scrolled.

Conclusion

In conclusion, code snippets are small pieces of code that can be useful for quickly and easily reusing common tasks or functions in your projects. They can save you time and improve your productivity as a developer, especially if you are working on a large project with a lot of repetitive code.

There are many different code snippets available for different purposes and in different programming languages, including JavaScript. Some common examples include sliders, counters, image sliders, and auto-scrolling effects. By learning how to create and use code snippets, you can streamline your development process and build more complex and powerful projects more efficiently.

As with any tool, it is important to use code snippets responsibly and to understand how they work before incorporating them into your projects. This will help you avoid common pitfalls and ensure that your projects are of high quality and maintainable. By understanding the power and limitations of code snippets, you can leverage them to become a more efficient and effective developer

--

--