Guide on initiating automatic page scrolling to a specific position on a webpage using sound cues

I am currently working on developing an interactive web comic using HTML, CSS, and JavaScript. The goal is to create a scrolling animation that moves from one point to another at a specific speed, showcasing multiple jpg images in a sequential manner.

In essence, I want the page to automatically scroll down when a reader reaches a certain pre-defined position on the page, similar to how it is done in this example webtoon:

Additionally, I would like to incorporate sound effects into the web comic, mimicking the features found in the provided link...

I have attempted to achieve this functionality with the script provided above, but encountered challenges with controlling the start and stop positions for the scroll. Moreover, I aim to ensure that the scroll only occurs once per page load.

<SCRIPT language=JavaScript1.2>
//change 1 to another integer to alter the scroll speed. Greater is faster

var speed=1

var currentpos=0,alt=1,curpos1=0,curpos2=-1

function initialize(){

startit()

}

function scrollwindow(){

if (document.all &&

!document.getElementById)

temp=document.body.scrollTop

else

temp=window.pageYOffset

if (alt==0)

alt=2

else

alt=1

if (alt==0)

curpos1=temp

else

curpos2=temp

if (curpos1!=curpos2){

if (document.all)

currentpos=document.body.scrollTop+speed

else

currentpos=window.pageYOffset+speed

window.scroll(0,currentpos)

}

else{

currentpos=0

window.scroll(0,currentpos)

}

}

function startit(){

setInterval("scrollwindow()",50)

}

window.onload=initialize

</SCRIPT>

Thank you in advance for any assistance!

Answer №1

Implementing an auto scroll function that activates when the user scrolls beyond 300px is fairly simple. Below is a basic script for achieving this:

var canScroll = true;

$(window).scroll(function () {

        var currentPosition = $(document).scrollTop();
        console.log(currentPosition);

        if(currentPosition > 300 && currentPosition < 400 && canScroll == true ) {
            canScroll = false;

            $('html,body').animate({
                scrollTop: $("#scrollTo").offset().top
            }, 2000);

        }
    })

UPDATE

Currently, this feature only works once. To reset the scroll state and allow it to run again, add another conditional statement after the initial one like so:

if (currentPosition > 0 && currentPosition < 300 && canScroll == false) {
        canScroll = true;   
    }

UPDATE

In order to incorporate sound playback, you can utilize the new .play command within the existing IF statement. Here's an example of how to use the .play code:

$('#videoId').get(0).play();

UPDATE

The following code snippet demonstrates the functionality by determining the position of the div instead of setting it manually. You can test it out on JSFiddle - https://jsfiddle.net/3fxcbs2k/3/

var canScroll = true;

$(window).scroll(function (e) {

    var currentPosition = $(document).scrollTop();
    var startPos = $("#scrollTOO").position();
    var finishPos = $("#scrollTo");

    if(currentPosition > startPos.top && startPos.top + 100 && canScroll == true ) {
        canScroll = false;

        $('html,body').animate({scrollTop: finishPos.offset().top}, 2000);

    } 
    if (currentPosition > 0 && currentPosition < 300 && canScroll == false) {
        canScroll = true;   
    }
})

To specify the starting point for scrolling, modify the value of

var startPos = $("      ").position();

And to set the ending position, adjust the value of

var finishPos = $("      ");

Audio

<audio id="sound">
    <source src="sound.mp3" type="audio/mpeg">
</audio>

var canScroll = true;

$(window).scroll(function (e) {

var currentPosition = $(document).scrollTop();
var startPos = $("#scrollTOO").position();
var finishPos = $("#scrollTo");

The Jquery play invocation looks like - $('#sound').get(0).play();

You can simply add it to the triggered action, as shown below.

    if(currentPosition > startPos.top && startPos.top + 100 && canScroll == true ) {
        canScroll = false;

        $('html,body').animate({scrollTop: finishPos.offset().top}, 2000);
        $('#sound').get(0).play();

    } 
    if (currentPosition > 0 && currentPosition < 300 && canScroll == false) {
        canScroll = true;   
    }
})

If you want to create multiple points, follow these steps

Think of the variables as identifiers that can be referenced later in the code. After the equals sign are their corresponding values. For instance;

var startPos = $("#scrollTOO").position();

startPos is the unique variable name, and its value is derived from the position of the div with the ID 'scrollTOO'.

To introduce more start and end points, you'll need to declare additional variables. One for each start and end point. For example;

var startPos = $("#scrollTOO").position();
var finishPos = $("#scrollTo");

var startPos2 = $("#point2").position();
var finishPos2 = $("#pint2");

Then, include another if statement for each point, replacing the start and end points accordingly,

if(currentPosition > startPos2.top && startPos2.top + 100 && canScroll == true ) {
            canScroll = false;

            $('html,body').animate({scrollTop: finishPos2.offset().top}, 2000);

Since it currently triggers only once, you'll have to create separate scroll variables for each point.

var canScroll = true;    
var canScroll2 = true;
var canScroll3 = true;
var canScroll4 = true;

Each respective if statement should refer to the corresponding scroll variable, for example, the second if statement would appear as follows:

if(currentPosition > startPos2.top && startPos2.top + 100 && canScroll2 == true ) {
canScroll2 = false;

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to access the width property within the style attribute of a span element with a specific class

https://i.sstatic.net/1YQdP.png Currently, I'm attempting to extract the content inside "width: 100%" and specifically the numerical part. My approach involves using beautifulsoup in Python, and you can see the snippet of my code below: rat ...

Make sure to keep Vue-Cookies intact even when closing the browser or tab

I have integrated vue-cookies into my Vue application. The code I'm using to store a cookie is as follows: $cookies.set('authUser', authUserObj); The object authUserObj contains the access_token. However, when I close and reopen the ta ...

Angular component equipped with knowledge of event emitter output

I have a custom button component: @Component({ selector: "custom-submit-button" template: ` <button (click)="submitClick.emit()" [disabled]="isDisabled"> <ng-content></ng-content> </butto ...

Toggle button visibility in AngularJS based on checkbox selection

I'm currently utilizing ng-table to construct my table. I have a button positioned at the top of the table that is initially disabled. My goal is to enable this button only when any of the checkboxes are selected. The button should automatically disab ...

Looking for assistance with removing hardcoding in HTML and jQuery?

Currently working on a biography page for my company's website that features a grid layout of the employees' profile pictures. Each picture should be clickable, causing the screen to fade to gray and display an overlay with the respective person& ...

Using jQuery and JavaScript to swap images depending on the option chosen in a dropdown menu

On my existing ecommerce website, I have a dropdown menu with the following code: <select data-optgroup="10201" class="prodoption detailprodoption" onchange="updateoptimage(0,0)" name="optn0" id="optn0x0" size="1"><option value="">Please Selec ...

Customize the default tab appearance in bootstrap version 5.2

Is there a way to customize the appearance of these tabs? I'm looking to change the color to match the primary color of Bootstrap. https://i.sstatic.net/6HaUO.png instead of https://i.sstatic.net/qHUZ9.png <!DOCTYPE html> <html> & ...

Retrieving URL parameters within an API route handler in Next.js

Within my client component called GetUserInfoButton, I initiate a GET request using the URL format of http://localhost:3000/test/users/[id]. The [id] in this URL is represented by an alphanumeric sequence similar to MongoDb. My intention within the file a ...

Error: FullCalendar does not display a header for the timeGridWeek view when the dates fall

Currently, I am integrating fullcalendar 5.5.0 with Angular 10. After migrating from fullcalendar v4 to v5, I noticed an annoying issue where the header for the date before the validRange start is no longer displayed: https://i.sstatic.net/kvVUW.png Thes ...

What is the best way to check for date equality in Node.js?

I am dealing with this code condition: stopped_at: { $lte: new Date(Date.now() - 86400 * 1000) } The above code successfully retrieves dates that are less than or equal to 24 hours ago. However, I am wondering if there is a simpler solution a ...

Refreshing content with Ajax when the back button is clicked

Hey everyone, I've been working on an ajax site and I'm having trouble getting the content to reload when the back button is clicked. I'm using Dynamic Drives ajax content script along with a script that changes the URL onclick and a popstat ...

What are some ways to implement AJAX with input from the user?

I'm currently working on a project to create a basic web page that will make use of AJAX for displaying results. Within main.py, I have a dictionary of words: words = { 'a': True, 'aah': True, 'aahed': True, ...

When transitioning an iOS Swift app to the background, a NodeJS error arises: 'Headers cannot be set after they have been sent to the client'

My app is built using Swift/SwiftUI. I utilize the ObservableObject and JSONDecoder to retrieve data from my Node.JS Express API and display it within the app: struct DevicesList: Decodable { var data: [DeviceInfo] } struct DeviceInfo: Decodable { ...

Ways to include a fresh value using an existing key in a document

Is there a way to keep track of multiple categories and their corresponding costs in a category object? For example, if I add the products: $50 category to the user in my code, it displays 'categories': { products: '50$' } in the consol ...

What is the best way to eliminate the border of an expansion panel in Material-UI?

Is there a way to eliminate the border surrounding the expansion panel in Material-UI? ...

Display a partial form in Rails using Ajax

There is a form displayed in the image below: Next, I aim to render this partial from an ajax call, specifically from .js.erb. However, I am unsure how to pass an object to f from the partial. Take a look at the image below for reference: Is there a way ...

"Encountering a problem with jQuery AJAX - receiving an error message despite the status code being

Attempting to make a jQuery Ajax request using the following code: $.ajax({ url: '<MY_URL>', type: 'POST', contentType: 'application/json;charset=UTF-8', data: JSON.stringify(data), dataType: 'a ...

There was a problem retrieving the product information from the API

I have been struggling to pinpoint the exact issue at hand. The foundation of HTML and CSS is pre-written, with JavaScript responsible for generating the core elements to populate the DOM. Within my script, I am attempting to retrieve product data in ord ...

Using PhantomJS webdriver in Python Selenium to disable CSS styling

There seems to be some uncertainty surrounding the ability to disable CSS while utilizing the PhantomJS webdriver for Selenium. It has been established that this is achievable with FireFox by adjusting the FireFox profile, but I am interested in doing so w ...

Executing a Knex RAW MySQL query to insert new records into a database table

As someone new to working with MySQL, I have previously used PSQL in a similar manner. However, the following code is generating an error. return await db .raw( `INSERT INTO users(firstName, lastName, email, ...