简体   繁体   中英

Creating a sticky sidebar with javascript or jquery

I am new to front end web development, so please forgive me if this is a novice question
I would like to create a sticky sidebar that appears when the parent div is inside the viewport, and disappears when it is out. Have a look at CSS tricks (how they create sticky ads on the right side which appear once there is space)
Image here

I cannot use position:sticky or position:fixed in css as I need browser compatibility, IE etc AND the div should not be fixed on the screen at all times, just until the end of its parent.

Clarification: When the div enters the viewport, the sidebar should appear. I don't want the sidebar to be fixed for the whole page.

My layout is something like this:

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

Thanks in advance:)

I cannot use CSS as I need browser compatibility.

You can and you should. position: fixed is well supported across all the browsers .

There is a basic example below:

<div class="side-bar">You content</div>
.side-bar {
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  width: 200px;
  max-width: 100vw; /* don't let your blow be wider that screen */
}

First you should give a hidden class to that div element to make it disappear. Add this code to your CSS file:

.hidden {
    display: none;
}

And the HTML file would look like this:

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

After that you need to use an API called IntersectionObserver in your script(javascript) file like this:

const div1 = document.querySelector('.div1');   // The top div in the HTML file

const div2 = document.querySelector('.div2');   // The bottom div in the HTML file

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);

These codes will point to the two divs:

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

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

And this code will create an IntersectionObserver that will observe for div1 element:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM