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

What is causing the colored SVG to appear lighter than the intended color after using a mask to recolor it?

I have a project using VueJS where I am trying to change the color of SVGs by looping through them and using mask and rect tags. However, I am noticing that as the icon index increases, the color of the icon becomes lighter. What could be causing this issu ...

What is the proper way to provide parameters in a GET request using Axios?

Recently, I have been attempting to include the api_key in the get request parameter using axios Below is the snippet of my code: const instance = axios.create({ baseURL: "https://api.themoviedb.org/3" }); export function crudify(path) { function get ...

Set the current time to ISO8601 format

I need assistance with creating a "time passed" counter for my website based on an API call that returns data in the following format: "created_at": "2018-05-16T14:00:00Z", What is the best approach to calculate and display the time that has passed since ...

Organize intricate JavaScript Arrays

Similar Question: How to sort an array of javascript objects? I'm in the process of transitioning some of my older ActionScript 2.0 code to JavaScript. While most things are running smoothly, I've hit a roadblock when trying to numerically s ...

Vim: Turn off autocomplete when using insert mode key bindings

I've set up a mapping in insert mode to automatically indent brackets: inoremap [;<CR> [<CR>];<Esc>O<Tab> When I use it, the result looks like this (the pipe character represents the cursor): const a = [ | ]; Now, I want ...

Strange occurrences within the realm of javascript animations

The slider works smoothly up until slide 20 and then it suddenly starts cycling through all the slides again before landing on the correct one. Any insights into why this is happening would be greatly appreciated. This issue is occurring with the wp-coda- ...

Steps to modify the CSS of a custom component in Angular 8

I have been attempting to override the css of a custom component selector, however, my attempts have been unsuccessful. I have tried using ":ng-deep" but it hasn't worked. How can I go about finding a solution for this issue? app.component.html: < ...

What is the method for retrieving the text from a span element nested within an anchor tag?

Just curious about how to extract the text from the span element inside the anchor tag. <a class="draw-ticket-wrap"> <span style="display: none;" class="TicketValue">1000</span> <span style="display: none;" class="TicketId">7&l ...

Determine the number of occurrences of specific values within a group of objects based on a

I have the following dataset: const data2 = [ { App: "testa.com", Name: "TEST A", Category: "HR", Employees: 7 }, { App: "testd.com", Name: "TEST D", Category: "DevOps", Employee ...

JavaScript: Modifying an Array of Matrices

Could anyone assist me with updating a matrix array? I have an initial matrix with preset values and need to update specific coordinates within it. Here is the base matrix: var myMatrix = [ ['-','-','-','-',&ap ...

When interacting with Chrome, the div gets automatically blurred upon being clicked

While working on the development of our website, we stumbled upon something peculiar. We have a set of divs displayed on the screen, resembling the layout of Pinterest. Upon clicking any of these divs, the content within that particular div is loaded into ...

Is it important to position elements based solely on the parent container?

My frustration with element positioning persists: <div id="container"> <div id="div1"></div> <div id="div2"></div> <div id="div3"></div> </div> #div1 { right:0; // I want its right border to be 0px from th ...

What is the method to remove an authentication code from a JSON file using JavaScript?

Is there a way to delete something from a JSON file? Here is an example: The file I am working with is named test.json Before I delete the authentication code: { "auth": [ { "test": 944037 }, { "tester& ...

Creating packaging for a node-webkit application

https://github.com/rogerwang/node-webkit/wiki/How-to-package-and-distribute-your-apps When I was packaging my node-webkit application for Windows using the instructions provided in the above link, I encountered a challenge. I could not figure out how to p ...

Using JQuery, retrieve all field values on click, excluding the value of the closest field in each row

I have a dynamic table where each row consists of an input field and a button. I am searching for a simpler way to select all input fields except the one in the current row when clicking the button in each row. All input fields have the same name and the r ...

Is Safari causing issues with the CSS slider animation?

Currently, I am working on implementing a CSS-only slider (no jQuery) in WordPress using the code from this source: http://codepen.io/dudleystorey/pen/kFoGw An issue I have encountered is that the slider transitions are not functioning correctly in Safari ...

Ways to display a default view in React

I am working on a React website that has three different routes. My goal is to have the first route, named Home, automatically displayed when a user lands on the site. Below is the code snippet from my App.js: <Router> <Navigation /> <Sw ...

How can you access the preloaded resolve value in AngularJS ui-router when the $stateChangeSuccess event is triggered?

$stateProvider.state('home', { url: '/', resolve: { person: function() { return 'good' } } Can you help me figure out how to access the value of 'person' in the $stateChangeSuccess callback f ...

Using Vue: Incorporating and extracting JSON data with JavaScript

I need to import the following JSON from a different component because it includes require and Math. I am having trouble saving it in JSON file format. let test = [ { name:"A", imgSrc: require('@/assets/img/A.png'), ...

Elements are failing to respond to the padding and margin adjustments in my CSS styling

I've been experimenting with creating a visually appealing div that serves as the centerpiece of a website. Imagine it resembling a standard "news" link. The width set at 80%, an image aligned to the left with a border, a headline detailing the lates ...