Attach a 20% image to the top that remains visible while scrolling

I am working with a Bootstrap Modal Window that includes:

  1. An image and a scrollable list of comments related to the image (scrollable with overflow:auto).
  2. The Modal window also contains an Add comment Textarea at the bottom.

I am looking to implement the following functionality: I want to make it so that when the comment section is scrolled up, the bottom 20% of the image sticks to the top and then the comments can be scrolled below.

For more information, please check out the Fiddle: http://jsfiddle.net/9u9mztqs/1/

Images for reference

https://i.sstatic.net/rBccH.png

https://i.sstatic.net/113e9.png


Answer №1

After creating a fiddle that performs the task, there is still room for improvement in terms of aesthetics...that's where you come in ;)

Check out the fiddle here

I believe this solution will help resolve your issue.

if (windowpos == 0) {
               s.removeClass('stick_in');
               s.addClass('stick_out');}
        }

The image will resize when scrolling to the top. Feel free to specify any value you prefer.

Answer №2

If you're looking for a starting point for the desired feature, here's a simple basis that may help. The code should be fairly self-explanatory, but feel free to ask if you have any questions about its implementation.

It's important to be mindful of throttling the scroll event handling to prevent potential performance issues in your application.

For more information on throttling events, check out this resource. Additionally, you can read about the potential problems that may arise if throttling is not implemented.

Here is an updated version of your original fiddle with the solution implemented: link. Below is an overview of the content in the fiddle.

Script

$(document).ready(function() {
  var imageHeight, scrollTopThreshold;
  var heading = $("#heading"),
    body = $("body"),
    img = $("#heading img");

  img.on("load", function() {
    imageHeight = $(this).height();
    // actually sticks (100 - 70)% of picture
    // if you really want 20%, then change 70 with 80.
    scrollTopThreshold = Math.ceil(imageHeight * 70 / 100);
  });

  $(window).on("scroll", function(e) {
    if (body.scrollTop() >= scrollTopThreshold) {
      heading.css({
        position: "fixed",
        top: -scrollTopThreshold + "px"
      });
    } else {
      heading.css({
        position: "inherit",
        top: 0
      });
    }
  });
});

Style

#heading,
#heading img {
  width: 100%;
}
#comment-form textarea {
  width: 100%;
  height: 90px;
  resize: none;
}

Markup

<div id="heading">
  <img src="http://www.rtacpa.com/wp-content/themes/thesis_18/custom/rotator/sample-1.jpg" alt="" />
</div>
<ol class="main">
  <li>I didn't think it was that bad</li>
  <li>So bad that you ate it all</li>
  (repeated li elements truncated for brevity)
</ol>
<form name="comment-form" id="comment-form" action="" method="post">
  <textarea name="comment" id="comment" style="" class="form-control pull-left" placeholder="Say something..." maxlength="250"></textarea>
  <button type="button">Post</button>
</form>

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

Enhance Your NextJs Website with Interactive Tooltips using @tippyjs/react

<Link href="/company/add" > <a title="My New Title" data-toggle='tooltip' className="btn btn-primary">My Link</a> </Link> Trying to integrate a Tippy tooltip component with a Nextjs Link do ...

An Easy Method for Managing Files in a Node.js Directory: Editing and Deleting Made Simple

Greetings! I am currently in the process of developing a basic blog using express.js. To manage the creation, updating, and deletion of posts based on their unique id, I rely on a data.json file. For each action performed, I utilize fs.writeFile to generat ...

What is the process for turning off deep imports in Tslint or tsconfig?

Is there a way to prevent deep imports in tsconfig? I am looking to limit imports beyond the library path: import { * } from '@geo/map-lib'; Despite my attempts, imports like @geo/map-lib/src/... are still allowed. { "extends": &q ...

The issue of Jquery AJAX failing to parse JSON data from the PHP file

Lately, I've been attempting to retrieve data from the server using the jQuery .ajax function. Strangely enough, it seems to be failing whenever I specify the dataType as JSON. Oddly enough, everything works perfectly fine when I omit defining the da ...

What is the process for transforming a key-value object from JavaScript to TypeScript?

I am currently facing a challenge in converting a JavaScript object into a TypeScript version as part of our code refactoring process :( I am struggling to figure out how to properly migrate a JS JSON object into a correct TS format. For instance, consider ...

What is the best way to align this alert in the center of the screen

Hey there, I'm facing an issue with aligning an alert horizontally when a user clicks a button. I've been trying different methods but can't seem to get it right. The goal is to keep the alert within #main. You can check out this fiddle for ...

Is there a way to set a cookie in order to remember an open tab? The tabs in question are generated using Coldfusion and Javascript

Trying to figure this out, but currently stuck. I have tabbed sections generated in Coldfusion. The selected section is marked by a class named "tab_selected (+ the UUID created in coldfusion)", while unselected tabs have class names with "tab_unselected ( ...

Creating dynamic div elements using jQuery

I used a foreach loop in jQuery to create some divs. Everything seems to be working fine, but for some reason, my divs are missing SOME class properties. Here is the code snippet I am using: $("#item-container").append("<div class=\"panel col-md-2 ...

Tips for inserting text within HTML tags using Python WebDriver

What's the best way to insert text within an HTML tag using Python WebDriver? <!--html cod--> <span class="py"></span> <!--I need to add text between span tags using Python WebDriver, similar to this example--> <span clas ...

Handling file uploads via AJAX is a common task when working with jQuery and AngularJS

Can anyone definitively answer whether it's actually feasible to upload files using AJAX? I've come across conflicting information online claiming that file upload via AJAX is not achievable! If it can be done, could someone please share a func ...

Duplicate a div using JQuery and place it underneath the previous one

Can someone explain why the cloned div is always inserted after the first div instead of after the last added (cloned) div? I've tried various simple JavaScript variations without any success. Here is an example: document.getElementById("add-div") ...

Delete items from several arrays on a click event in React

I'm working with an array of objects that contain multiple arrays. My goal is to remove the item when a button is clicked, but I keep getting undefined as a result. JSON Data [ { "services": [ { "id": "1b9 ...

Creating environment-agnostic builds with the Vue webpack template

When building my Vue projects using a build server, I rely on the npm run build command provided by the Vue 2 template. This template allows me to access environment-specific data configured in files within the config directory, such as prod.env.js. The ac ...

Problem with Sending POST Requests in ExpressJS

Having trouble with a POST request in Postman resulting in a long loading time followed by a Could not get any response error message? No errors are showing up in the terminal. Could there be an issue with how I am saving the POST data, especially in my /b ...

Issues persist with jQuery ajax request attempting to retrieve data from database

I attempted to retrieve data from my database using jQuery AJAX. Below is the code snippet I used: <script> $(document).ready(function(){ function fetch_data(){ $.ajax({ type:"POST", url:"http://localhost:88/phpPoint/select.php", success:function(re ...

Adjusting the width of columns in an HTML/CSS table

Struggling to format a table based on specific requirements with no success: Some columns need to adjust width to fit content. Other columns should share remaining available width equally. Table width must not exceed parent width but still fill it. I tr ...

Communicating between modules in Angular Js using Factories

I am currently working on a straightforward Angular application. In an effort to simplify the code, I am trying to create a globally accessible injectable library. Here is a basic overview of what I have: My app.module.js file looks like this: angular.mo ...

In what ways can the accessibility of a website be impacted by using CSS

After reading numerous articles on Google and Stack Overflow, I have decided to ask my question straightforwardly in the hopes of receiving a clear and direct answer. Adding another layer to the discussion about whether Does opacity:0 have exactly the sam ...

What is the mechanism behind the clipping function in the three.js frustum?

Currently, I am exploring the frustum feature of three.js by making changes to the example provided in the Scene Graph section here. function main() { const canvas = document.querySelector('#c'); const renderer = new THREE.WebGLRenderer({c ...

Looking for a way to manipulate the items in my cart by adding, removing, increasing quantity, and adjusting prices accordingly. Created by Telmo

I am currently working on enhancing telmo sampiao's shopping cart series code by adding functionality for removing items and implementing increment/decrement buttons, all while incorporating local storage to store the data. function displayCart(){ ...