Finding the location of the page screen or an element with Jquery/Javascript

How can I determine the position of a DIV relative to the body or html tag?

For example:

  • If I have an element moving up the screen.
  • When the page is scrolled vertically, and the DIV reaches a certain height on the screen, it changes color.
  • Once the DIV goes off the screen, it reverts back to its original color.

I've achieved a similar effect using Next/Previous buttons:

<html>
<head>
    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>

    var number = 0;
    var goSign = "";

    function goToByScroll(id){              
            $('html,body').animate({scrollTop: $("#"+id).offset().top-100},'slow','swing', function()
            {
                $('#'+id).css('background', '#8b00cb');
                $('#'+(id-1)).css('background', 'none');
                $('#'+(id+1)).css('background', 'none');    
            });             


    }

    function iterate(goSign)
    {                               
        if(goSign == "next")
        {           

            if(number < 12 && number >= 0)
            {
                goToByScroll(++number);
            }
            //alert(number);
        }
        else if(goSign == "previous")
        {
            if(number <= 12 && number >= 1)
            {
                goToByScroll(--number);
            }               
            //alert(number);
        }
    }

    </script>


</head>
<body>

<div style = "position:fixed; top:90px;right:200px;width:200px;height:50px">
    <a href="javascript:void(0)" onClick="iterate('next')">Next</a><br/>
    <a href="javascript:void(0)" onClick="iterate('previous')">Previous</a>
</div>


<div style="width:600px">
    [< Repeat HTML content with multiple div blocks here for demonstration purposes >]
</div>
</body>

This solution requires manual interaction with the Next/Previous buttons. Is there a way to achieve this automatically without the need for user clicks?

I'm considering utilizing jQuery's .position() method: http://api.jquery.com/position/

Answer №1

.position() provides the position of an element relative to its offset parent (if nested inside an absolutely positioned element, coordinates may not be based on the document element).

Consider using .offset() instead:

Retrieve the current coordinates of the first element within the set of selected elements, with respect to the document.

Source: http://api.jquery.com/offset

Check out this demo: http://jsfiddle.net/PNCbK/ (Note: If JSFiddle is down, you can view the same code on JSBin here: http://jsbin.com/ezobux/edit#javascript,html,live)

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

Android textView is populated with randomly generated alphanumeric text after parsing file

I have a parse file coming from parse.com as a string message, and I need to display it in a textView. ParseFile file = message.getParseFile(ParseConstants.KEY_FILE); String filePath = file.getDataInBackground().toString(); if (messageTy ...

Utilize JavaScript on the browser to send a post request to the Google API

I'm encountering a 404 error when making a $.ajax request to the Google API. Below are the codes I've been using: var asyncLoad = require('react-async-loader'); var CLIENT_ID = '<SOME_ID>'; var DISCOVERY_DOCS = ["https: ...

The title of the Electron application remains consistent

My application is being packaged using electron-packager, but it's not changing its name and still displays "Electron." It's supposed to use the productName in my package.json file, but for some reason, it doesn't change. Even after creati ...

Double-click to toggle with jQuery

Here is the code for my toggle menu: $(function () { $('#menu li').click(function () { $('#menu li').removeClass("active"); $(this).toggleClass("active"); }); }) It works perfectly, but there is one issue. When ...

Displaying different page sections according to scrolling position

I am in the process of developing a single-page website and I am interested in having each section load only when the window scrolls to that specific section. While I am aware that images can be lazy-loaded, I am looking to lazy load the entire section. On ...

The Javascript navigation bar is not displaying properly on mobile devices as it should

After customizing the responsive navbar tutorial from W3Schools using CSS and JS, I encountered an issue. I wanted to include a logo and a web page title before the navbar, which worked perfectly when the webpage was maximized. However, when I resized the ...

Automatically populate a jQuery dropdown box with MySQL data

I have a scenario where I need to create 2 dropdown boxes. The first dropdown box will display all the tables from a database, and when a table is selected, the second dropdown box should be populated with fields from that specific table. Dropdown Box 1: ...

Issues with local storage ternary expression in React are causing unexpected behavior

I am attempting to accomplish this task. const userToken = localStorage.getItem('token') {userToken.length ? null : <div className='registerLogin'> Register... </div> } The ternary operator is not working ...

Assign multiple EventListeners to an element and remove specific ones individually

I have a specific element, in this case the $(window) in the code example. I want to attach multiple EventListeners to this element, specifically the "scroll" event twice. These two EventListeners have distinct functionalities that I prefer not to combine, ...

Having trouble with looping through subarrays using Javascript and JSON

I am attempting to iterate through a JSON object using Javascript (jQuery). Within the main JSON object, each object in the array contains embedded arrays of tags. My goal is to loop through all the files in the main object and simultaneously iterate thro ...

Only the initial external CSS ID is functional, while the second one is inactive

I am facing an issue with my table where I have applied an external CSS that uses alternating shaded rows. My aim is to have specific table cells with different background and font colors - one cell with a green background and red font, and another with a ...

What could be causing the issue with my hour parameter in node-cron?

Having difficulty setting up a cron job to run with node-cron every Monday at 8:30. I've tried using "30 8 * * Mon" and even "30 08 * * Mon", but it doesn't seem to work. Interestingly, "30 * * * Mon" does work and runs every hour on the 30th min ...

The latest version of Material UI, v4, does not currently support React 18

Looking to incorporate MUI (Material UI) into my website design. Encountering difficulties with installing this library, receiving the error message below: -npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While ...

Refresh the vue-chart component in a nuxt.js application

I'm currently working on a nuxt project and I need to incorporate some charts into it. I'm using vue-chartjs as a plugin for this purpose. However, the issue I'm facing is that the chart data is fetched after the chart has already been drawn ...

Switching the angularjs variable from html; a definitive guide

How can I update a variable in an AngularJS controller using JavaScript when a specific HTML element is clicked? For instance: angular.module('app',[]) .controller('appController', function($scope, $http){ $scope.on ...

`Back and forward function of pushState in history`

After successfully implementing ajax loading on all pages of my website, I encountered a challenge with the browser's back and forward buttons. Implementing the back button was straightforward: $(window).on('popstate', function(e) { get ...

Converting JavaScript code from Jade into EJS framework

I am currently working on converting code from Jade to EJS and could use some assistance. I have started the translation process, but I'm not entirely confident in my approach. Additionally, I find the syntax used in EJS to be confusing compared to tr ...

Which is better: specifying Node.js version with nvmrc or in package.json engines

Ensuring that other developers working on my JavaScript project use specific versions of node and npm is important to me. I recently added the following code snippet to my package.json file: "engineStrict" : true, "engines": { "node" : "10.10.0", ...

JavaScript object created by splitting a string

I was presented with the following string: result:tie,player:paper,computer:paper One way to handle this could be splitting it into arrays, creating an object, and parsing it. However, this approach may not be ideal. Is there a better method to convert t ...

SweetAlert will only render if it is not hidden

One of the components in my codebase utilizes SweetAlert from "react-bootstrap-sweetalert". The issue I am facing is that even when the "show" property is set to false, SweetAlert is still being rendered and the function inside it gets called regardless o ...