How to make a sticky sidebar using JavaScript or jQuery

Hello everyone! I am just starting out in front end web development, so please bear with me if my question seems basic. I am trying to figure out how to create a sticky sidebar that only appears when the parent div is in view, and disappears when it's not. If you've seen how CSS Tricks implements sticky ads on the right side, that's the effect I'm going for. Check out the image below for reference: Image here

The catch is that I can't use position:sticky or position:fixed in css due to browser compatibility issues, particularly with Internet Explorer. Additionally, I don't want the sidebar to be fixed on the screen at all times, just until the end of its parent.

To clarify, I want the sidebar to only appear when the div enters the viewport, rather than being fixed throughout the entire page.

Here is the layout structure I am working with:

<div class="section">
  <div class="sidebar left">
    Sidebar
  </div>
  <div class="content">
    Text here
  </div>
</div>
Further content here...

Thank you in advance for your help! :)

Answer №1

I can't rely on CSS for browser compatibility.

You absolutely can and should. position: fixed is widely supported by all major browsers. Check out the details here.

Here's a simple example below:

<div class="side-bar">Your content</div>
.side-bar {
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  max-width: 100vw; /* ensure it stays within screen width */
}

Answer №2

To start, assign a hidden class to the div element in order to hide it. Insert this snippet into your CSS stylesheet:

.hidden {
    display: none;
}

Your HTML file should resemble the following structure:

<div class="div1">Some content</div>
<div class="div2 hidden">Some other content</div>    

Next, utilize the IntersectionObserver API within your javascript script as shown below:

const div1 = document.querySelector('.div1');   // Reference to the top div

const div2 = document.querySelector('.div2');   // Reference to the bottom div

const observerCallback = function (entries) {
   if (!entries[0].isIntersecting) div2.classList.remove('hidden');
   else div2.classList.add('hidden');
}

const observerOptions = { root: null, threshold: 0};

const observer = new IntersectionObserver(observerCallback, observerOptions);
observer.observe(div1);

The above codes are used to target the two div elements:

const div1 = document.querySelector('.div1');

const div2 = document.querySelector('.div2');

Lastly, set up an IntersectionObserver to monitor changes on the div1 element:

const observer = new IntersectionObserver(observerCallback, observerOptions);
observer.observe(div1);

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

Issue with Bootstrap's pull-right class causing elements to overlap

I need help positioning a single button above a list, with the button to the right. Whenever I try using the pull-right class on the button (or its containing div), the button ends up being covered by the list. <div> <div class="pull-right"& ...

creating a custom website layout

Currently, I am in the process of developing a website and I am absolutely obsessed with the page design. For instance: I have a page that can be divided into two sections - the left side and the right side. The left side consists of various menus, while ...

Ensuring the correct width for a .png image in an email newsletter for Outlook 2013

After creating an email newsletter that works perfectly on all email clients except Outlook 2013, I realized that the image I included is not adhering to the table width specified. Instead, it is defaulting to its own width of 658px. View image here Below ...

When floating a heading 4 (h4) and two divs to the left, and a single div to the right,

When floating a h4 and 2 divs to the left, and another div to the right, how can I place a block inside the remaining space that perfectly fills it? The background color of this space should not spread outside. [h4][div][div][remaining space][div] Thank ...

Using Jquery for a Second Timer

I have a jQuery function that looks like the one below. The result is displayed in a span, but when the page is reloaded, this span briefly disappears and then reappears. Is there a way to prevent this from happening? I need it to stay visible at all tim ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Having trouble with Vue.js 2.5+ and Webpack 4+ not loading CSS files?

I am currently in the process of setting up a Vue project with webpack 4 enabled using the Microsoft SPA templates dotnet core as the base. Everything seems to be working fine, except for the fact that external CSS files are not loading into the project. I ...

Attempting to route a selector, yet on the second attempt, the entity is successfully transferred

I am currently working on developing a function that will switch the image every half second for 10 iterations. During the final iteration, the image src will be set to the actual value. Everything seems to work fine for the first loop, however, when the s ...

The background image is not displaying correctly in the tag td

I'm struggling to display a background image inside a table data cell using CSS. <td class='details-control'></td> When I use the following CSS rules, the image is not displayed: td.details-control { background: url(http:// ...

Chrome reports a Javascript error: indicating that it is not recognizing the function

When working with a js file and html, I encountered an issue where one function works fine but another prompts an error in Chrome: Uncaught TypeError: specification_existing is not a function I'm puzzled as to why one function works while the othe ...

Angular navigation bar dropdown menu is not displaying properly

Check out this Bootstrap Navbar I recently added the same code to my Angular project, but I'm having trouble getting the dropdown to display properly. Take a look at the Stackblitz Demo I need help with two things: Getting the dropdown to show c ...

React array fails to update upon modification

Hey there! I've created a component that takes an array of strings, combines them, and then renders a typing animation by wrapping each character in a span tag with toggling opacity from 0 to 1. I noticed an issue when switching the order of displaye ...

Three.js is failing to render within a specified div

My current project involves utilizing three.js to create a cube rendering. Despite the cube appearing on the screen, I am facing issues with getting it to display within the specified div element and in the desired style. HTML: <div id="render"> & ...

What are the steps for designing a flexbox structure?

I am looking to design a flexbox layout that includes a title, detail, and other content within one div. Additionally, I want another div with content placed closely next to the first div, all centered within the main box (referred to as container). What ...

What is the best way to send back the response from my Node controller to my application using AJAX?

This is the code for my controller: module.exports.key_i = function(req, res, next) { // console.log("We are here in webserver key_i"); var k = req.body.KEY; // console.log(k); var requestOptions = { url: 'http://localhost:3000/api/key_i ...

Tips on how to connect with ngFor

I have been working on an application to display various events, but I am encountering an issue. Whenever I load the webpage, it appears empty and the console throws an error saying 'Can't bind to 'ngForEvent' since it isn't a know ...

The custom bullet points are not appearing correctly

I've been attempting to design a custom bullet list, but it doesn't look quite right as I had hoped. The issue is that the spacing appears too close, you can see an example HERE Any suggestions would be greatly appreciated. Thank you ...

Exploring JavaScript capabilities with Google - managing and updating object names with numbers

After importing JSON data into Google Scripts, I am able to access various objects using the code snippet below: var doc = Utilities.jsonParse(txt); For most objects, I can easily retrieve specific properties like this... var date = doc.data1.dateTime; ...

Is it possible to utilize a hyphen in the link_to attribute?

I'm encountering a dilemma in my Rails app where I need to assign a value to a custom data-* attribute for an anchor tag. The issue is that hashes can't contain hyphens, leading to difficulties with this code: <%= link_to 'Example', ...

The download functionality in HTML5 is not functioning properly, so users are forced to rename files when downloading

For weeks, I've been struggling to change the name of the downloaded file. Despite my efforts, instead of being named Chrysanthemum.jpg, it ends up as a hash of the file like 241693260.jpg In my backend setup, I utilize Node.js and Express.js for man ...