Adjust the height of a div based on the designated start and end coordinates

My goal is to create a single vertical line that starts at a defined point (using CSS) and ends at a point that I have not yet specified.

The concept is for the line to remain sticky or increase in height as the user scrolls, until it reaches the end point.

However, I am unsure about the logic I should implement to achieve this.

Here is an example of what currently does not work: https://jsfiddle.net/uzegqn7f/

The objective is for the line to extend, for instance, to the top of the second image following the user's scrolling position.

<div class="vertical-line line-1"></div>

<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-start">

<div class="content"></div>

<img src="https://dummyimage.com/900x300/000000/fff.jpg" alt="" class="line-1-end">

.content {
    height:1000px;
}

img {
    max-width:100%;
    height:auto;
}

.vertical-line {
    display: block;
    position: absolute;
    background: #ee403d;
    width: 4px;
    height: 10px;
    z-index: 999;
}

.line-1 {
    margin-left:10%;
    margin-top:100px;
}

var distance = $('.line-1-end').offset().top - $('.line-1-start').offset().top;

function line_animation(element,distance) {
    $(window).scroll(function(){
        element.css("height", distance+"px");
    });
}

$(document).on('load resize', function() {
    var line1 = $(".line-1");
    line_animation(line1,distance);
});

PLEASE NOTE:

  • The spacing between elements may vary and is not consistently the same, especially in responsive layouts.

Answer №1

Below is a suggestion with comments in code:

var start = $('.line-1-start').offset().top,  // determining where the line begins
    end = $('.line-1-end').offset().top,      // finding where the line ends
    line = $('#line');

drawLine($(window).scrollTop()); // drawing the initial line

$(window).scroll(function(){
    drawLine($(this).scrollTop());  // updating line position while scrolling
});

$(document).on('resize', function() {      // adjusting top and bottom points of the line on window resize
  start = $('.line-1-start').offset().top;
  end = $('.line-1-end').offset().top;
    drawLine($(window).scrollTop());
});

function drawLine(currentPosition) {
  if (currentPosition >= start && currentPosition <= end) {
    var distance = currentPosition - start;
    line.css("height", distance+"px");
  } else {
    line.css("height", 0);
  }
}

Access the updated fiddle here

Answer №2

Unfortunately, I wasn't able to complete it entirely, but it's very close to completion. It has the capability to dynamically calculate the height and start/end positions. With a little more work, you should be able to wrap it up. The only issue is that it's not accurately calculating the end position. A few adjustments and it should be good to go. You can take a look at the JSfiddle below for reference;

https://jsfiddle.net/ytxbU8n1/5/

$(document).ready(function() {

    $(window).scroll(function(){
    handleVerticalLine();
  });

  function handleVerticalLine() {

    $('.vertical-line-container').each(function() {

      var $startElement = $( $( this ).data( 'line-start-selector' ) );
      var $endElement = $( $( this ).data( 'line-end-selector' ) );
      var $verticalLine = $( this ).find('.vertical-line');

      if( $startElement.length && $endElement.length && $verticalLine.length ) {


        var startElementTopOffset = $startElement.offset().top;
        var endElementTopOffset = $endElement.offset().top + $endElement.height();
        var startElementVerticalLineBegin = startElementTopOffset;
        var endElementVerticalLineBegin = endElementTopOffset;

        $verticalLine.css('top', startElementTopOffset + $startElement.height());

        var verticalLinePercentage = (startElementVerticalLineBegin / endElementVerticalLineBegin) * 100;

        verticalLinePercentage += $(window).scrollTop();

        $verticalLine.css('height', verticalLinePercentage);

      }

    });

  }

});

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

Angular filtering arrays of data

$scope.currentEvent = Object { item_id: "10535", name: "johnny", user_type: "1",category_id: "5"}, Object { item_id: "10534", name: "smith", user_type: "1",category_id: "6"}, Object { item_id: "10536", name: "Greg", user_type: "1",category_id: "7"}; $sco ...

What is the best method to replace the `click` event of an element selected using jQuery?

As I work on my program, I am attempting to alter the click event of a jQuery element. However, rather than modifying it as expected, it seems to be adding a new event each time. $myelem = $('.nav-item'); $myelem.click(function(){ console.lo ...

From traditional relational databases to MongoDB/Mongoose database design

Recently, I ventured into using mongoDB and mongoose for a new node.js application. Coming from a background of relational databases, I find it challenging to adjust to the mongoDB/noSQL approach, particularly concerning denormalization and the absence of ...

Import data from a file into a JavaScript 2D array

Looking for a way to load an array from a text file in JavaScript? Here's what I have: var linePoints = [[0, 3], [4, 8], [8, 5], [12, 13]]; But rather than defining it in the code, I'd like to read it from a text file. The file looks like this: ...

Experience the full functionality of Google Maps API without the need for jQuery or PHP with PanTo

I'm not a developer and I find myself stuck in the panTo() function. All I want is to execute this function with an if-else statement without having to reload the Google Map or using jQuery. <body> <div id="map"></div> <d ...

Utilizing Puppeteer to interact with dropdown menu options through selection and clicking

To log out, I am trying to use Puppeteer to select and click on a dropdown menu item. This particular menu requires hovering over it with a mouse in order to reveal its options, as opposed to clicking directly. When attempting to copy the selector for th ...

Is it possible to retrieve the complete file path in a form?

My goal is to retrieve a file using an input element of type "file". This element is located within a partial view, and I need to send it to the controller or request it there using "Request.Form["inputFile"];". However, this method only provides me with t ...

Retrieving the value from a vuetify v-text-field to use in another text field

Looking to suggest a username based on the user's first and last name. The concept is that after the user fills out the first name and last name fields, the value in the username field will be a combination of their first and last names. firstName = B ...

What is the most effective method in Vue.js for transitioning elements without the need to use v-for and v-if at the

Utilizing v-for to generate multiple <p> elements, each one animating in within a Vue <transition> component if the v-if condition is met. Below is the code snippet: <transition name="fade"> <p v-for="(quote, idx) in game.quot ...

Console error caused by uncontrolled input in React Hooks

A cautionary message: Changing an uncontrolled text input to a controlled one is not recommended. Stick to using either controlled or uncontrolled input elements throughout the component's lifecycle. import React, { useEffect, useState } ...

How to Use Jquery to Choose Parent Elements Beyond the Immediate Parent in the Hierarchy

Is there a quicker way to select the parent element of a child using jQuery rather than going through multiple .parent() calls? For example: <div> <div> <div class="child"> </div> </div ...

Modifying an HTML attribute dynamically in D3 by evaluating its existing value

I'm facing a seemingly simple task, but I can't quite crack it. My web page showcases multiple bar graphs, and I'm aiming to create a button that reveals or conceals certain bars. Specifically, when toggled, I want half of the bars to vanish ...

Splitting the package.json file to separate the front-end and back-end components while utilizing shared

Currently, I am working on a project that involves a separate frontend (webpack) and backend (express/mongodb). My goal is to separate the dependencies in the package.json file while still being able to share certain logic/utility code between them. How ca ...

The submission of the form proceeds even with the warning displayed

I am facing an issue with a form that consists of one text field and a submit button. The user is required to input a 3-digit number, and if the number is greater than 200, a warning should be displayed. If the user clicks OK, the form should be submitted. ...

Loop through the JSON array and append every value to the list within AngularJS

I'm just starting to learn about Angular JS and I have a question. I receive a JSON array as an AJAX response from a PHP page. I want to iterate through this JSON array and push each value into a list like this: angular.forEach($scope.companies.area, ...

Display data as a JSON object using Highcharts

Looking to populate a highchart in Jade using JSON data sent from Node.js. Currently, I have successfully added static data as shown in the code snippet below: var series = [ { name: 'Tokyo', data: [7.0] } ]; Now, I am attempti ...

Efficiently delivering static files and managing routes with Express

Currently utilizing express js The root path is /xyz/ If the path is xyz/api/ I aim to provide JSON, for any other path I want to serve a static file. For example, xyz/abc or xyz/def/bjk etc. My existing configuration is shown below app.use('/xyz/: ...

Appending the desired URL to the existing URL using an Ajax callback

Ever since I started working on a Drupal 7 project, I have been facing an issue with making an ajax call back. The problem arises when the URL I intend to use for the callback gets appended to the current page the user is viewing. It's quite puzzling ...

Can a new EJS file be generated using the existing file as a template?

I am in the process of building a website navbar and I am curious about how to automatically inject code from one ejs file into another ejs file. In Python's Flask framework, this is accomplished using the principle of {% block title%} and in another ...

Is it possible to trigger AJAX using an element's ID without any event listener?

If I have the following code: if(cond1Satisfied){ <div id="checkA"> </div>} if(cond2Satisfied){ <div id="checkB"> </div>} Can I make an AJAX call like this? $.ajax({ url: 'example.php', type: & ...