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

Styling in Next.js with conditions

I am attempting to create a scenario where a link becomes active if the pathname matches its href value. function Component() { const pathname = usePathname(); return ( <div className="links"> <Link href="/"> ...

Enhance the display in Angular2

Just started working with Angular 2 and I've encountered a problem. I have an API that loads a JavaScript file in my project. The issue is, I need to use this JS file and cannot modify it. Essentially, this JS file has some methods that make AJAX call ...

Transform CSS filters into SVG filters

Implementing CSS filters on the <img /> elements has been successful for me. For example: filter: brightness(1) contrast(67%) saturate(250%) grayscale(0%) invert(0%) hue-rotate(330deg) sepia(40%) blur(0px); Now, I am trying to apply the same filte ...

Styling in Svelte/TS does not change when applied through a foreach loop

I've been experimenting with creating a unique "bubble" effect on one of my websites, but I'm facing difficulty changing the styling in a foreach loop. Despite no errors showing up in the console, I'm at a loss as to how to effectively debu ...

What is the reason behind the decision to have the writable section of the form begin in the center?

Hey everyone, I recently attempted to create a form for the first time but ran into an issue with the writable area not starting at the beginning. I suspect it has something to do with the padding, but being new to this environment, I'm having trouble ...

What causes the excess spacing in flexbox containers?

Is there a way to remove the padding around the container and between the two columns? I attempted setting margin and padding to 0, but it was not successful. body, html { width: 100%; height: 100%; } main { display: flex; flex-flow: row wrap; ...

Modifying td background color according to values in a PHP array

Trying to update the background color of a td element with the code below. However, it seems that the code needs some adjustment as the color is not being applied. Any assistance or alternative solutions would be greatly appreciated. Snippet of PHP code: ...

React Scroll and Material-UI button active link not functioning correctly

Whenever the link goes to the correct page, I want to add a special background effect or change the font color. Despite trying to use CSS for this purpose, it didn't work as intended. If you want to take a look at my code on codesandbox, follow this ...

Enhancing the visual appeal of Struts 2 with property tag styling

Utilizing the Struts2 property tag to fetch the user's name, my code looks like this. <div class="MyStyle"> <p> Hi! <s:property value="#session.firstName"/></p> </div> However, I am facing an issue wh ...

Warning: Attempting to modify a property that is not defined - 'action'

My code includes a datatable and an alert that pops out. The datatable functions properly with or without the alert, but the alert does not work well when combined with the datatable. Could this be causing a conflict in the code? An error message indicates ...

What could be the reason for the meta viewport not functioning properly on Android devices with Cordova 5.1.1?

Ever since upgrading my app to cordova 5.1.1, I've noticed that the meta viewport no longer functions properly on Android devices. The app is not displaying correctly as a result. Despite trying various solutions, I am still facing this issue. Is ther ...

Creating a vertical scrollable container that spans the full height of the PDF document

I am currently working on embedding a PDF file into my website. I'm trying to hide the status bar, including download buttons and page numbers, through some clever techniques so that I can control them externally. My goal is to be able to redirect use ...

Using the input method in JavaScript cannot extract an object property

Recently, I have been working with this JavaScript code provided below. It is essential for me to retrieve the votecount for a game based on user input. function Game(gamename,votes) { this.gamename = gamename; this.votes = votes; }; var lol = ne ...

Attempting to unveil concealed download URLs

Trying to extract download links from a website, but the format is as follows: <form action="" method="post" name="addondownload" id="addondownload" > <input type="hidden" name="addonid" id="addonid" value="2109" /> <input class="re ...

How to adjust the timezone settings in PHPMyAdmin on a shared server platform

I'm having trouble changing my timezone to India on my shared server database. I've tried everything but can't seem to get it to work. My website is built using PHP Codeigniter The contact us page on my site saves all inquiry details to my ...

Can an AJAX request generate an error if it receives a success response header but no response body?

Checking Server Connectivity Using AJAX I am attempting to use an AJAX post request from the client side to verify server connectivity before proceeding with other functionalities. The goal is to simply check if the server is up without sending any data. ...

Changing the Values of Variables in an npm Package within SvelteKit

I have been working on a SvelteKit component library where I define variables for components like background-color and font-family in a CSS file. Inside the ./dist/index.js file of my library, I export the CSS using `import './main.css'`. When in ...

Invoke the parent method within the child application

I have a checkbox on the child app controller. When the user clicks it, I need to call a method from the parent controller: Parent app controller: <div ng-controller="ParentCntr as parentCntr"> <child-app></child-app> </div> C ...

Changing the border color of material ui Rating stars: A guide

I am struggling to change the border color of stars in Material UI Rating because my background color is black, making it difficult to see when the star is empty! Here's the code snippet: import Rating from '@material-ui/lab/Rating'; import ...

What is the best way to make an exit pop up disappear when clicking on any area?

I'm new to programming in JavaScript and jQuery and I wanted to implement an exit pop-up feature. While I came across a helpful tutorial online, I encountered an issue where users could only exit by clicking on the "X" button. I want them to be able t ...