How can we initiate a script once the scroll has reached the designated block using jQuery?

I am using a unique jQuery script that I created myself, and I want it to activate when the scroll reaches the tab block (the blue and grey block at the end of the page).

Check out the live version

This is my HTML:

<section id="Block" class="container-fluid block">
    <div class="row accordeon">
        <div class="blue">
            ... 
              <li><a href="#evaluer">5 - Evaluez le prestataire sur Codeur.com</a></li>
          </ul>
        </div>
        <div class="gray">
           ...
               </div>
            </div>
        </div>
    </div>
</section>

This is my scrolling script:

<!-- Show animation on Scroll -->
<script>
$(document).ready(function() {
/* Every time the window is scrolled ... */
      $(window).scroll( function(){
          /* Check the location of each desired element */
          $('.ShowMe').each( function(i){
              ...
                  $(this).animate({'opacity':'1'},500);
              }
          });
      });
  });
  </script>

This is my tab animation script:

<!-- Tabs -->
<script>
    var tabChange = function () {
      ...
      // Start the cycle again in a predefined amount of time
      setTimeout(function () {
      //tabCycle = setInterval(tabChange, 5000);
      }, 15000);
  });
</script>

Answer №1

To start, it's important to first check if the object is visible on your screen after scrolling. Once you have reached the object, use an if statement to determine its visibility before executing your code.

Take a look at this DEMO to see the complete JS function.

JS

$(window).scroll(function() {
    if (checkVisible($('#tester'))) {
        alert("Object is Visible! Insert your code within this if statement!");        
    } else {
        // do nothing
    }
});

In your particular scenario, it would look something like this:

$(window).scroll(function() {
    if (checkVisible($('#tester'))) {
        var tabChange = function () {
          var tabs = $('.nav-tabs > li');
          var active = tabs.filter('.active');
          var next = active.next('li').length ? active.next('li').find('a') : tabs.filter(':first-child').find('a');
          
          next.tab('show');
        };
        
        var tabCycle = setInterval(tabChange, 5000);

        $('a').on('click', function (e) {
          e.preventDefault();
          clearInterval(tabCycle);
          $(this).tab('show');
          setTimeout(function () {
          }, 15000);
      });        
    } else {
        // do nothing
    }
});

Hope this explanation helps!

---EDIT:

If the function is being called multiple times, you can solve it by unbinding the scroll event.

Include this in your code: $(window).off('scroll');

$(window).on('scroll', function() {
        if (checkVisible($('#Block'))) {
            $(window).off('scroll'); # add this
            var tabChange = function () {

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

Error occurs when a handlebar helper is nested too deeply

I have set up two handlebar helpers with the names 'outer' and 'inner'. In my template, I am using them as shown below: {{#outer (inner data)}} {{/outer}} However, I am encountering an error in the console related to the inner helper, ...

What exactly does the combination of {on, attrs} create within Vue/Vuetify?

Although this question may have been asked before, I am still struggling to grasp its meaning. Can you help me understand it better? <v-dialog v-model="dialog" width="500" > <template v-slot:activator=&quo ...

How do I design a table containing 10 elements and include buttons for navigating to the first, previous, next, and last elements?

I am currently working on creating a table that includes columns for ID, firstName, and lastName. My goal is to display only 10 elements per page and also incorporate buttons for navigating to the first, previous, next, and last pages. Is there a way to m ...

Separate your buttons with style using the Bootstrap button groups with

Is there a way to add border line separators between buttons in Bootstrap button groups? <div class="btn-group" role="group" aria-label="Button group with nested dropdown"> <button type="button" class=&quo ...

Sharing JSON data with public/javascripts/X.js in Node/Express: A beginner's guide

Currently facing a challenge with my Express project. Take a look at https://github.com/MoreeZ/help1 and examine ./public/javascripts/budget.js. My goal is to swap the incomeData object to read data from ./incomedata.json I attempted passing it through th ...

What is the best way to implement a CSS transition for styles that are dynamically created by React?

I have a situation where I am using a button component that is styled based on a theme provided by a context: The code in Button.js looks like: () => { const theme = useContext(themeContext); // { primaryColor: "blue" } return <button className ...

Is there a better approach to accomplishing this task using jQuery?

http://jsfiddle.net/bGDME/ My goal is to display only the selected content within the scope and hide the rest. The method I used feels a bit cumbersome. I'm open to suggestions on how to improve this. Any guidance would be greatly appreciated. Tha ...

Using session variables in HTML allows developers to store and retrieve

My index.html file includes a login form that submits to login.php. Once the user is verified, they are redirected back to index.html and the verified username is stored in a session variable called username. I am looking for a way to display this username ...

How to efficiently use nested $.each() in DataTables with jQuery

After receiving Json data from the server, I utilize DataTables to display the information accordingly. The json contains multidimensional arrays with rows consisting of columns that may have more than one value. Here's an excerpt: { "info_table ...

Animating Object3D to move closer to the camera in a Three.js environment - currently functional, just requires adjustment of screen position

I have some code that animates an object towards the camera and resizes it to fit half of the screen var vFOV = camera.fov * Math.PI / 180; var ratio = 2 * Math.tan( vFOV / 2 ); var screen = ratio * (window.innerWidth * 0.6 / window.innerHeig ...

Using CSS files from node modules within a meteor application

Incorporating the froala editor into my Meteor and React project has presented a unique challenge. The editor mandates the importation of CSS files, as outlined in the documentation here: . However, upon importing a specific CSS file using the command belo ...

Assign the value of "td" to the variable "val"

I am trying to set the value of my td element from my JavaScript JSON, but for some reason it doesn't seem to be working when I inspect the element. The HTML is functioning fine, it's just the value that isn't updating. I've tried chang ...

When I navigate to the URL using a router-link, the v-for in my Vue.js component renders properly. However, if I manually type the URL or refresh the page, the v-for fails to render

Whenever I navigate to a specific URL that showcases icons of characters from a game, everything functions as expected and the icons are displayed. However, upon refreshing the page, the icons vanish. If I manually enter www.example.com/champions, the ico ...

use ajax to selectively update specific element

Seeking assistance with updating the cart page using ajax when adjusting the quantity of products. The view logic seems to be functioning correctly. The issue arises when targeting the class "ajax_updater". Upon clicking the quantity buttons, ajax succes ...

The ng-model feature is unable to properly save data within a nested ng-repeat function for a 2-dimensional array

I'm currently working with a nested ng-repeat on a 2d array and have added ng-model to the third ng-repeat. However, I am encountering an issue where my ng-model is not properly storing the data within the object. JavaScript Code emrService .getDat ...

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 ...

Find the string "s" within a div element aligned vertically, using Popper

Currently utilizing Popper from Material-UI <Popper id={"simplePopper"} open={true} style={{backgroundColor: 'red',opacity:'0.5',width:'100%',height:'100%'}}> <div style={{height:"100%", ...

`A mistake occurred while building in the package.json file`

While attempting to run all build processes by using the command npm run build:css, I encountered an error indicated below. Even after running npm cache clean --force, the issue remains unresolved. https://i.sstatic.net/4edDo.png npm ERR! code ELIFECYCLE ...

Why does Array Object sorting fail to handle large amounts of data in Javascript?

Encountered an issue today, not sure if it's a coding problem or a bug in Javascript. Attempting to sort an object array structured like this: const array = [{ text: 'one', count: 5 }, { text: 'two', count: 5 }, { text: 'thre ...

The Less compiler (lessc) encounters an issue on a fresh operating system. ([TypeError: undefined is not a function])

After setting up my new development environment on Windows 10, I encountered an issue with less. Following the instructions on lesscss.org, I installed less using: npm install -g less The installation process completed without any errors. However, when ...