Alter the webpage's background color using setInterval while also implementing automatic scrolling based on active records

I've created a row of blinking div elements with a time interval, ensuring that only one div blinks at any given moment.

To see it in action, please view the demo below:

var arr = $(".boxes");
  var current = 0;

  function bgChange() {
    if (arr.length > 0) {
      arr.removeClass("active");
      arr.eq(current).addClass("active");
      current = (current + 1) % arr.length;
    }
  }
  setInterval(bgChange, 200);
.active {
    background-color: red;
  }
Test

The issue arises when the active class moves beyond the visible part of the page, making the active record not visible in the viewport. To address this, I would like to automatically scroll the page to show the active div element.

Alternatively, a paging system could be implemented where the active class is added to each div element sequentially. Once the active class reaches the last div visible on the page, the page should transition to the next one and continue the process.

Answer №1

offset() function can be used to fetch the coordinates of the current element, and then utilize .scrollTop( value ) for scrolling in the window.

    var elem = arr.eq(current);
    elem .addClass("active");   
    //If element is not within view port
    if (elementInViewport2(elem.get(0)) == false) {
       $(window).scrollTop(elem.offset().top);   
    }        

var arr = $(".boxes");   
var current = 0;   

function bgChange() {
  if (arr.length > 0) {
    arr.removeClass("active");     
    var elem = arr.eq(current);
    elem.addClass("active");    
    if (elementInViewport2(elem.get(0)) == false) {
      $(window).scrollTop(elem.offset().top);   
    }
    current = (current + 1) % arr.length;
  }   
}   

function elementInViewport2(el) {
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  return (
    top < (window.pageYOffset + window.innerHeight) &&
    left < (window.pageXOffset + window.innerWidth) &&
    (top + height) > window.pageYOffset &&
    (left + width) > window.pageXOffset
  );
}

setInterval(bgChange, 200);
.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
...
<div class="boxes">Test</div>

Referencing Prestaul's response on Determining DOM element visibility in viewport?

Answer №2

To determine if the element currently in focus is not within the viewport and adjust the scrollTop value accordingly, you can use code similar to the following:

if (arr.eq(current).offset().top > viewportBottom)
  $window.scrollTop(viewportBottom);
if (arr.eq(current).offset().top < $window.scrollTop())
  $window.scrollTop(viewportTop);

Take a look at the demonstration below:

var arr = $(".boxes");
var $window = $(window);
var viewportTop = $window.scrollTop();
var viewportBottom = viewportTop + $window.height();   
var current = 0;   

function bgChange() {
  if (arr.length > 0) {
    arr.removeClass("active");      
    arr.eq(current).addClass("active");            
    current = (current + 1) % arr.length;
    if (arr.eq(current).offset().top > viewportBottom)
      $window.scrollTop(viewportBottom);
    if (arr.eq(current).offset().top < $window.scrollTop())
      $window.scrollTop(viewportTop);
  }   
}   
setInterval(bgChange, 200);
.active {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>
<div class="boxes">Test</div>

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

Exploring the power of $j in JavaScript

Could someone please explain what the $J signifies in this snippet of javascript code? if ($J('.searchView.federatedView.hidden').attr('style') === 'display: block;' || $J('.searchView.federatedView.shown').length ...

Show a notification when utilizing AJAX requests

I consist of two separate files: one written in PHP and the other one in JavaScript and HTML. PHP file : <?php session_start(); //start session $_SESSION['data'] = "The content should be displayed as alert in the JS file"; JS/HTML File: & ...

Setting a value programmatically in a Material-UI Autocomplete TextField

In my React application, I am using material-ui Autocomplete and TextField components to allow users to select values from a dropdown list. However, I am looking for a way to programmatically set the input value by clicking a button, without having to choo ...

What is the functioning process of the angular method decorator?

The tutorial on creating custom decorators in Angular introduces a throttle decorator that utilizes the lodash throttle function. The implementation of this decorator can be seen below: import t from 'lodash.throttle'; export function throttle( ...

Why does the text in a div display in Safari 8.2 and Chrome 39, but not in Firefox 34?

In my HTML document, I have a div tag located within the body like so: <div id="content_text"></div>​ Using javascript, I later set the contents of the div like this: var content_text = document.getElementById("content_text") c ...

Upon reviewing the webpage using an IPAD and AngularJS

I recently completed a web application using AngularJS and PHP. It functions smoothly on Chrome and Firefox, but it encounters loading issues on IE due to the number of JS files. To solve this problem, I will need to reduce the amount of JS files for it to ...

Compare the key of one array against the value of another array using jQuery and retrieve any matches

Utilizing $.getJSON to retrieve data from an external .json file containing the following information. { "title_12345":"<span class=\"header-class\">Header</span>", "p_12345":"<span class=\"description-class\"& ...

Prevent the loading of multiple jQuery versions

Currently on Yii 2.0.9, I am encountering an issue with conflicting jquery versions. The framework loads jquery 2.2.4 without any issues, but the krajee extensions are introducing jquery 1.7.2 which I do not prefer. Is there a way to modify my AppAssets ...

What is the best way to create a fixed contact form on specific pages?

There is a Contact Form 7 on the webpage that I want to make fixed to the right side. Initially, the form is hidden and only the form button (open) is visible. When clicked, the form should open. ...

"Discover the magic of creating a navigation menu with jQuery toggle - let me show

Recently, I managed to create a side navigation using the target function in CSS3. However, I am curious about how I can achieve the same result using jQuery without disrupting the layout. Any assistance would be greatly appreciated. Here is the code sni ...

Having trouble getting datatables.net to function properly with JavaScript

I've been experimenting with datatables from http://datatables.net/ Attempting to make it work using javascript, but I'm facing issues. Even when following the example provided on the website, it still shows a blank page. Does anyone have any su ...

Why does `window.location.reload()` only refresh the home page and not the other pages when using Angular?

After transitioning from the home page to the menu page, I expect the menu page to refresh automatically once. However, when implementing the code below, the home page is refreshed first before navigating to the menu page without an auto-refresh. 1)Initia ...

How can you effectively retrieve values in Chakra Core without encountering any memory complications?

I have been studying this example in an effort to develop a basic JavaScript engine that can execute scripts like the zxcvbn library. I thought I had it all figured out, but there are certain parts of the code that still puzzle me. Particularly, I am strug ...

Issue creating a JWT using jsonwebtoken module in Node.js

Could someone help me troubleshoot an issue I'm having while trying to generate a JWT token? The error message "TypeError: Right-hand side of 'instanceof' is not an object" keeps appearing even though the syntax seems correct. const jsonwebt ...

Troubleshooting: Issue with fixed positioning in React (Next.js) causing problems with modal window functionality

I'm currently working on implementing a modal window in React, but I've encountered an issue where setting position: fixed results in the modal window's position being relative to the page rather than the browser window. For privacy reasons, ...

What is the process for incorporating attribute values when constructing XML with fast-xml-parser?

Latest fast-xml-parser update: version 4.3.6 Description I'm trying to incorporate an xml attribute (tokenized="true") in this format : <custom-tag tokenized="true">test test &gt; 14</custom-tag> Input Code var def ...

Adding a delay to your JQuery wiggle effect

Is there a way to achieve an effect similar to the JQuery wiggle plugin? Check out this demo: <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.js" type="text/javascript"></script> <script src="http://static.manpoints.u ...

Unable to locate the MoreVert icon in Material UI interface

I am trying to incorporate the MoreVert icon into my application's header to display signout and settings options. I have added the MoreVert icon as shown below, and although the popup appears when clicking on the supposed location of the icon, I am u ...

How can I display base64 image data in a new window without triggering a block?

Currently experiencing challenges with Javascript. Utilizing html2canvas to convert a div to a canvas and then using .toDataURL to convert the canvas to a base64 data stream. Attempting to open base64 image data in a new window, but facing blocks from va ...

What is the syntax for creating a zip function in TypeScript?

If I am looking to create a zip function: function zip(arrays){ // assume more than 1 array is given and all arrays // share the same length const len = arrays[0].length; const toReturn = new Array(len); for (let i = 0; i < len; i+ ...