Are we utilizing this JavaScript function properly for recycling it?

Two functions have been implemented successfully. One function adds the autoplay attribute to a video DOM element if the user is at a specific section on the page. The other function smoothly slides in elements with a transition effect.

The only limitation is that these functions currently work for only one element on the page, but I wish to extend their functionality to multiple elements.

Here is the first function, which plays the video when scrolled:

playOnScroll: function() {

    var player = $('.browser video');
    var hasReached = false;

    function isInView(elem){
        return $(elem).offset().top - $(window).scrollTop() < $(elem).height();
    }

    $(window).scroll(function() {

        var section = $('#user-experience');

        // If section exists
        if (section.length) {

            if (isInView(section) && !hasReached) {
                // console.log('play video');
                hasReached = true;
                player.get(0).play();
            }

        }

    });

}

Currently, this function only works if the section with the ID #user-experience is in view. It would be beneficial if it could be applied to other sections as well.

I am considering changing the target section to a class name so that any section with this class can trigger the function. Is there a better approach?

Now, looking at the second function responsible for animating elements upon scroll, I am unsure how to make it reusable for multiple selectors:

moduleShift: function() {

    var root = this;
    var el = $('.entry figure');
    var offset = 0.8;

    root.isVisible(el, offset);

    $(window).scroll(function() {

        var windowPos = $(this).scrollTop();

        setTimeout(function(){ 
            root.isVisible(el, offset); 
        }, 1000);

    });

}, 

isVisible: function(el, offset) {

    el.each(function() { 
        var elHeight = $(this).outerHeight();
        var offsetTop = $(this).offset().top;
        var offsetBottom = offsetTop + elHeight;

        if (offsetTop <= $(window).scrollTop() + $(window).height()*offset) {
            $(this).addClass('moduleShift');
        };

    });

}

A similar solution may be applicable to this function as well. However, like the first function, I am open to suggestions for a more efficient method of achieving this.

Answer №1

If you're looking for a simple way to achieve this, consider using jQuery Waypoints. By utilizing the functions isVisible and moduleShift as event handlers triggered when a user scrolls to a specific point, you can easily accomplish your goal. For instance:

var waypoint = new Waypoint({
  element: document.getElementById('placeOfYourVideoPlayer'),
  handler: moduleShift;
})

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

retrieving an element from a collection of objects

For a project utilizing the openweather api, I encountered fluctuating data based on the time of day it is viewed. My goal is to loop through the first 8 objects to identify a dt_txt value of 12:00:00. Once found, I intend to store this result in a variabl ...

How to transmit data using ajax through a hyperlink? (Without relying on ExtJS, jQuery, or any other similar libraries)

I have a link that says "follow me" and I want to send some basic data to the page without having it reload. Update: I just realized that using "onclick" will help me achieve what I need. Got it. Update 2: I mean, something like this: follow me ...

Function for testing global variable stub in JavaScript

Currently, I am in the process of writing Unit tests for a React application. Within the page header, the tracking library 'mixpanel' is inserted between <script> tags as outlined in their documentation: . The documentation states that "Th ...

Issues with removing options from Autocomplete persist in React MaterialUI

Currently navigating the world of ReactJS and experimenting with Material UI's Autocomplete component. The challenge lies in managing a complex data structure where options are dynamically generated based on user selections, but removing previously se ...

What is the best way to smoothly transition in an image that is dynamically set using Angular?

I am using Angular to set a background image for my page, but the current loading behavior is not visually appealing as the image loads from top to bottom. I would like to implement a fade-in effect or load the image from a blurry view to enhance the user ...

Implementing file change detection using view model in Angular

When using the input type file to open a file and trigger a function on change, you can do it like this: <input type="file" multiple="multiple" class="fileUpload" onchange="angular.element(this).scope().fileOpened(this)" /> The functi ...

What is the best way to dynamically set minDate for a datetime-local input field?

I need assistance with setting up two input fields: one for the start date and one for the end date. I want the end date to automatically populate with the same value as the start date when the start date is filled, and have the minimum value set to be the ...

What is the correct method for calculating the sum of one input field and multiple output fields?

I have a single input field and multiple calculated output fields using JavaScript :Click here to view the screenshot of the calculated problem You can see the live preview on this link: . When you visit this link, enter "Base on your annual bill amount: ...

How do I go about transferring data from an excel sheet to an external API with the help of JQuery/Node.js?

If I possess an excel document that needs to be delivered to an API endpoint which demands the following headers: Content-Type: multipart/form-data Content-Disposition: form-data; name="fileData"; filename="Form_SOMETHING(2).xlsx" Is it plausible for me ...

Express is throwing a TypeError because it is unable to access the property 'app', which is undefined

On my nodejs server running the express framework, I have been encountering a random error when making requests. The error occurs unpredictably, usually appearing on the first request and not on subsequent ones. It's challenging for me to identify the ...

Error: JavaScript object array failing to import properly

In my code, I have an array of objects named trace which is defined as follows: export const trace: IStackTrace[] = [ { ordered_globals: ["c"], stdout: "", func_name: "<module>", stack_to_render: [], globals: { c: ["REF" ...

Regular pattern with Kubernetes cluster endpoint utilizing either IP address or fully qualified domain name

In my Angular/typescript project, I am working on building a regex for a cluster endpoint that includes an IP address or hostname (FQDN) in a URL format. For instance: Example 1 - 10.210.163.246/k8s/clusters/c-m-vftt4j5q Example 2 - fg380g9-32-vip3-ocs.s ...

NodeJS - Bluebird: implementing a loop with a waiting mechanism for completion

Struggling with a seemingly simple task in my NodeJS and MongoDB project. I've included Bluebird for promises, but need some help. In my code, I have a basic for-loop that generates random names and pushes them into an array: const PlayerGenerator = ...

Styling text on a HTML webpage

Is there a way to center text in the caption and add a link on the far-right of the caption? Let me know if this is possible. The format for the caption should be: Centered Text Right-justified link ...

Issue with People Picker directive causing AngularJS validation to fail

I have implemented a SharePoint client-side people picker in my form using the directive from this GitHub repository. However, I am facing an issue where the validation of my form fails and the button remains disabled. When I remove the field, the validati ...

Should the refresh button be displayed once the animation finishes?

Can anyone provide guidance on how to write jQuery code that will reveal a hidden button after an animation is finished? The button should also be able to refresh the animation for the user to watch again. Check out this fiddle: http://jsfiddle.net/rabela ...

Error encountered in Three JS Drag Controls: Unable to assign value to property 'x' as it is undefined

I've been trying to drag the spheres around the scene using drag controls that should be activated when the "m" key is pressed. However, I keep running into an issue where the objects don't move and I receive an error message saying "Uncaught Typ ...

Slider Background Problem

I am attempting to incorporate this example into my project found at this link. This code was originally shared on StackOverflow: A way to fade in the background on load? <!DOCTYPE html> <html lang="en"> <!--To Do: --> <!-- list menu ...

`Monitoring and adjusting page view during window resizing in a dynamic website`

Situation: Imagine we are reading content on a responsive page and decide to resize the browser window. As the window narrows, the content above extends down, making the entire page longer. This results in whatever content we were previously viewing bein ...

How can I change the text of a single button by clicking on it without affecting the other buttons that share the same

Currently, I am implementing a posting system where posts can be added using a button. The posts have two additional buttons - one to show/hide content and the other to delete content. I am utilizing jQuery's slideToggle event to toggle the visibility ...