Utilizing jQuery to accentuate a specific div element when it is positioned directly in the center of the browser window

I have multiple divs with id="scroll_1", "scroll_2", "scroll_3", and so on. I am trying to implement a feature where when any of these divs is in the center of the window, I want to change the background color using jQuery highlight. Currently, I am able to change the background color when the div is in the center of the screen, but I am facing difficulties reverting it back to the original color once it moves out of the center (i.e., the user scrolls up or down to another scroll_x id).

Edit The only CSS code relevant to this issue that I currently have is:

[id^=scroll_] {
    background-color: white;
}

Thank you for your help!

<script>
$(document).ready(function() {      
    var window_height = $(window).height();
var obj_height = $('#scroll_1').height(); // Height of the object we are scrolling past
var top = $('#replyer').offset().top + (obj_height / 2); // Position on the screen to start highlighting #scroll_x

    $(window).scroll(function() {
    var scrollMiddle = $(window).scrollTop() + ((window_height/2) - (obj_height /2));

    if (scrollMiddle >= top) {
        var scrollPosition = $(document).scrollTop()+ ((window_height/2) - (obj_height /2)),
                currentPosition = 0;
    $('div[id^="scroll_"]').each(function() {// Iterate over #scroll_x and only change the background until another #scroll_x is in the middle of the screen
            currentPosition = $(this).offset().top;
            if (currentPosition >= scrollPosition) {
            $(this).prev(function(){
                $(this).css('background-color',"#aaa"); // Change previous #scroll_x back to the original background color - Not working currently
            });

                return false; // Break the loop
                }

                $(this).css('background-color',"#ccc"); // Currently changes the background of #scroll_x once in the middle of the screen but stays highlighted when scrolling up/down to previous/next iteration of #scroll_x
            });
        }
    });
});
</script>

Html:

<div id="replyer">
    Top line before repeating divs
</div>
<div id="scroll_1">
    First object to scroll over.
</div>
<div id="scroll_2">
    Want to highlight the div currently in the middle of the screen
</div>
<div id="scroll_3">
    Only the div in the middle of the screen should be highlighted (background change)
</div>

Answer №1

If you're looking to change the object overlapping the center of the browser to green, check out this demo.

Check out the Fiddle here: http://jsfiddle.net/j2ULW/1/

Here's the full source code:

<html>
<head>
  <title>Scroll test</title>
</head>
<style type="text/css>
  body {
    background: #000;
  }
  [id^=scroll_]{
    background-color:#aaa;
    height: 600px;
  }
  #replyer {
    height: 400px;
    background: white;
  }
</style>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<body>
  <div id="replyer">
    Top line before repeating divs
  </div>
  <div id="scroll_1">
      First object to scroll over.
  </div>
  <div id="scroll_2">
      Want to highlight div currently in the middle of screen
  </div>
  <div id="scroll_3">
      Only div in middle of screen should be highlighted (background change)
  </div>
<script>
$(document).ready(function() {      
  var window_height = $(window).height();
  $(window).scroll(function() {
    var scrollMiddle = $(window).scrollTop() + (window_height/2);
    $('div[id^="scroll_"]').each(function() {
      elTop = $(this).offset().top;
      elBtm = elTop + $(this).height();
      if (elTop < scrollMiddle && elBtm > scrollMiddle) {
        $(this).css('background-color',"#00ff00");
      } else {
        $(this).css('background-color',"#aaa");
      }
    });
  });
});
</script>
</body>
</html>

Answer №2

To start, make sure your container div has the following CSS properties:

div.container { overflow:auto; height:auto; }

If you want to restrict the container to a size of 470*180px, you can use this CSS:

div.container-closed { overflow:hidden; width:470px; height:180px; }

Then, by clicking on an element, you can toggle the .container-closed class to remove the overflow restriction:

Here's the jQuery code snippet:

// Start by restricting the size with JavaScript
$("#div").addClass("container-closed");
// Click event to toggle the class
$("#trigger").click( function() {
      $("#div").toggleClass("container-closed");
});

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

Sneak beneath another element with a div's sliding movement

I'm attempting to make an absolutely positioned div element (#slideout) slide underneath another div element .menu using CSS, if possible. Check out my code here. Currently, when the red tab is clicked, #slideout covers .menu, but I want it to hide ...

JavaScript accordions failing to open

I've encountered an issue with my website that includes JS accordions. Strangely, they are not opening on the live site, but they function properly on Codepen. I checked the console in Chrome and found no error messages, however, when I looked at the ...

Creating separation between a dropdown menu and its corresponding button

I'm dealing with a situation where I have a button that reveals a hidden droplist upon hover. The problem is that there is no space between the button and the droplist, causing interference with the functionality. My attempt to create some distance b ...

What are effective methods for testing HTML5 websites?

I'm currently working on a project to create a dynamic website using HTML5. The first page will prompt the user for specific inputs, and the following page will adjust accordingly based on these inputs. My main concern now is how to effectively test ...

ASP.NET Core MVC: Issue with Passing C# Razor Variable to HTML Tag

GitHub Repo: https://github.com/shadowwolf123987/Gun-Identification-App I'm currently facing an issue in passing the values of two C# variables from the code block defined in my view to the corresponding html tags within the same view. Unfortunately, ...

Guide on connecting MySQL 'id' to an HTML element

I need assistance with setting up a functionality on my website. I have a database containing rows of data, and each row has an 'ID' field in MySQL. I want to connect each ID to a button so that when the button is clicked, a PHP script will run t ...

Unfortunately, the header and footer are not lining up correctly with the main body on our mobile site

I've been tasked with creating a fully responsive website, but I'm encountering difficulties with the mobile design. Specifically, when I switch to mobile dimensions like an iPhone 12, the header and footer don't line up properly with the ma ...

Is there a way to customize the timepicker pop-up so that it extends the entire width of the parent form control

<FormControl fullWidth> <LocalizationProvider dateAdapter={AdapterDayjs}> <TimePicker views={["hours", "minutes", "seconds"]} label={t("StrategyManager.Select_Time")} value={timer} ...

Issues arising from the arrangement of the menu bar

I created a navigation bar using an unordered list (ul) with list items (li). However, I encountered an issue where the items were displaying in reverse order until I applied the following CSS: .nav-bar .btn{ float: left; } .nav-bar u ...

Tips for getting rid of the excess space surrounding an image within a div tag

Placing images inside bootstrap card divs within col divs is my current challenge <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" rel="stylesheet" /> <div class="container"> <div class="row"& ...

Can CSS be used to create curved dashed lines?

Is it possible to achieve dashed lines similar to the ones highlighted in the images below using only CSS? I have a responsive web page built with Bootstrap, and I need the dashed lines to adjust accordingly when the window width changes. ...

Get the large data file in sections

I ran a test script that looks like this: async function testDownload() { try{ var urls = ['https://localhost:54373/analyzer/test1','https://localhost:54373/analyzer/test2'] var fullFile = new Blob(); for (le ...

Create a dynamic calendar by integrating dates with Javascript and an HTML table

Recently, I decided to delve into web design again and embark on a challenging project for my father's baseball business. The main task at hand is creating a detailed calendar using HTML tables. After spending a considerable amount of time perfecting ...

How can you utilize CSS to automatically generate section numbers, specifically for multiple sections?

Is it possible to automatically generate section numbering in CSS only when there are multiple sections present? I discovered that using CSS, one can create automatic numbering for sections. body { counter-reset: section } h2 { counter-reset: sub-section ...

Create a scrollable Bootstrap table without impacting the layout grid system

Is there a way to create a scrollable table without impacting the grid system layout? How do I make a table scrollable while keeping the col-xs tag intact? <table class="col-xs-12"> <thead> <th class="c ...

What is the best method for extracting individual JSON objects from a response object and presenting them in a table using Angular?

After receiving a JSON Array as a response Object from my Java application, I aim to extract each object and display it on the corresponding HTML page using TypeScript in Angular. list-user.component.ts import { HttpClient } from '@angular/common/h ...

A Comprehensive Guide on Creating an Expansive HTML Textbox Covering the Entire

<form method="post" class="mobile-login-form _5spm" id="u_0_0" novalidate="1" data-autoid="autoid_1"> <input type="hidden" name="lsd" value="AVpe_Wp1" autocomplete="off"> <input type="hidden" name="charset_test" value="€,´,€,´, ...

Tips for displaying form data in a boostrap modal

One issue I am facing involves a form that collects a user's first and last name, along with a button that activates a bootstrap modal. When the button is clicked, the goal is to display the inputted data from the form within the modal window. The use ...

Exploring the Intersection of HTML5 File API and AJAX Chunked Uploads

Recently, I created a drag and drop multiple file upload feature with individual progresses, which has been working well. However, there is one issue that I have encountered. During the uploading of larger files, sometimes the browser freezes until the upl ...

Slicknav is failing to appear on the screen, although it is being

After spending hours trying to implement a slicknav menu into my school project, I'm stuck and seeking guidance. Despite having some coding experience, I can't seem to find the solution to my problem. Any help, insight, or tips on fixing or impro ...