Achieving a Sticky Scrolling Element on the Same Side with Bootstrap 4

Seeking assistance with creating a fixed category bar for blogs on scroll, which should always remain on the right side of the screen. The issue I'm facing is that the current setup causes the bar to switch sides and shrink in size when scrolling past the first article. My styles are based on Bootstrap version 4, so it's likely related to the grid system.

I came across a thread online that mentions JSS as a possible solution, but I'm struggling to implement it effectively due to poor documentation. More information can be found at this GitHub link: https://github.com/dvtng/jss.

var prevWidth = $(window).width();

if ($(window).width() > 767) {
  $('ul.nav li.dropdown').hover(function() {
    "use strict";
    $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeIn(500);
  }, function() {
    "use strict";
    $(this).find('.dropdown-menu').stop(true, true).delay(200).fadeOut(500);
  });

  $('.navbar .dropdown > a').click(function() {
    "use strict";
    location.href = this.href;
  });
}


var $window = $(window),
  $stickydiv = $('#cat-div'),
  $divTop = $stickydiv.offset().top,
  $pos = $stickydiv.position(),
  $posleft = $pos.left;
/*jss.set('.sticky', {
    'left': $posleft
});*/

$window.scroll(function() {
  $stickydiv.toggleClass('sticky', $window.scrollTop() > $divTop);
});

window.onresize = function() {
  "use strict";

  if ($(window).width() < 767 && prevWidth > 767) {
    location.reload();
    setNewHeight();
  } else if ($(window).width() > 767 && prevWidth < 767) {
    location.reload();
    setNewHeight();
  }
  /* $pos = $stickydiv.position();
   $posleft = $pos.left;
   jss.set('.sticky', {
       'left': $posleft
   });*/
};

function setNewHeight() {
  "use strict";
  prevWidth = $(window).width();
}
@charset "utf-8";

/* CSS Document */

.title {
  font-family: vatican;
}

.soph {
  font-family: Sophisto;
}

.of-auto {
  overflow: auto;
}

#cat-div.sticky {
  position: fixed;
  top: 63px;
}

div.splat {
  background-color: rgba(0, 0, 0, 0.3);
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <h2 class="title">Explore The Blog</h2>
  <div class="row">
    <div class="col-md-10">
      <div class="well of-auto">
        <h3 class="title">Some Title <small>February 2, 2018</small></h3>
        <p class="soph">Lorem ipsum dolor sit amet, consectetuer adipiscing elit... (truncated for brevity)

Answer №1

Let's address the main issue you'll need to resolve here: the category bar on your page changes size and position when scrolling down due to a change in CSS properties from being a child element of a flex parent to having a fixed position.

To tackle this problem, you have two options:

  1. Set the category bar's position to fixed from the beginning to maintain its appearance regardless of scrolling. Or,
  2. Adjust the styles of the fixed position to mimic the initial layout.

Mimicking the position can be achieved with additional CSS rules. For example, ensuring the width remains the same by specifying it as 190px if it is set to be 16.666666% wide based on the .col-md-2 class for desktop screens.

Calculating the distance from the right side of the page helps maintain consistency in the layout. By determining the remaining space on either side of the document after considering the container's width (1140px), you can set the right position of the sidebar accordingly.

The CSS code snippet would look like this:

#cat-div.sticky {
  position: fixed;
  top: 63px;
  right: calc(calc(100% - 1140px) / 2); 
  width: 190px;
}

By implementing these adjustments, your category bar will remain in place even while scrolling. You may also want to consider setting a fixed height for the sidebar to prevent it from appearing shorter or taller than expected during scrolling.

Lastly, fine-tuning the behavior of the sticky feature can provide a better user experience. Adjusting the 'top' value in the CSS and updating the JavaScript logic to activate the sticking effect immediately upon scrolling will enhance the performance of the category bar.

Integrating all these elements effectively will ensure a seamless scrolling experience on your webpage.

Answer №2

Take a look at the menu on your website:

<div class="col-md-2 well splat" id="cat-div">
  <nav class="nav flex-column">
    <a href="#" class="nav-link">Category</a>
    <a href="#" class="nav-link">Category</a>
    <a href="#" class="nav-link">Category</a>
    <a href="#" class="nav-link disabled">Category</a>
  </nav>
</div>

If you want to make this navigation section sticky on the right side of the screen, simply add right: 0; in your CSS.

Consider restructuring your page layout for better results.

var prevWidth = $(window).width();

if ($(window).width() > 767) {
  // JavaScript code
}

var $window = $(window),
  $stickydiv = $('#cat-div'),
  $divTop = $stickydiv.offset().top,
  $pos = $stickydiv.position(),
  $posleft = $pos.left;

$window.scroll(function() {
  $stickydiv.toggleClass('sticky', $window.scrollTop() > $divTop);
});

// More JavaScript code

function setNewHeight() {
  // Function definition
}
@charset "utf-8";
/* Custom CSS styles */
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <h2 class="title">Explore The Blog</h2>
  <div class="row">
    <div class="col-md-10">
      <div class="well of-auto">
        <h3 class="title">Some Title <small>February 2, 2018</small></h3>
        <p class="soph">Lorem ipsum dolor sit amet...</p>
      </div>
    </div>
    <div class="col-md-2 well splat" id="cat-div">
      // Navigation menu
    </div>
  </div>
  // More HTML content

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

Nextjs introduces an innovative "OnThisDay" functionality, leveraging getServerSideProps and Date.now() to provide real-time information

I am currently working on adding an "OnThisDay" feature in my Nextjs project, inspired by Wikipedia's style of displaying events that happened on a specific date. To achieve this, I have implemented a function structured like the following code snippe ...

The animation in ThreeJs encounters context issues within Angular 2

I am trying to incorporate ThreeJs into my Angular 2 project. I have successfully rendered a scene with a simple cube, but I ran into an issue when using the animate() function. Here is the code snippet: import { OnInit, Component } from '@angular/co ...

What is the best way in Vue.js to preload images upon the route being loaded without immediately showing them?

Looking to implement a smooth transition effect when switching between different scenarios in a web application. The issue arises when fetching images takes time, resulting in abrupt appearance instead of a gradual transition. Seeking a solution to preload ...

How can Vue.js leverage dynamic templates within a component?

const CustomComponent = { props: ['index'], template: `<span>I am a custom component: {{ index }}</span>` }; const UserInputResult = { components: { CustomComponent }, props: ['templateString'], template: `& ...

Steps to verify the timepicker for accuracy and consistency throughout different time periods

I am currently working on validating a time picker for a project. I found a helpful example for date validation at http://jqueryui.com/resources/demos/datepicker/date-range.html but I need to adapt it for a time picker. Specifically, I need to ensure tha ...

My content is unselectable due to grid overlap and z-index conflict

I'm currently working on coding a portfolio and need some assistance with creating a nav bar within my grid layout. The main challenge I'm facing is trying to have two main sections - a nav bar and the main content, where the content scrolls vert ...

Using jqGrid with the jQuery.get() method

Struggling to populate a jqGrid from a jQuery.get() response and facing some challenges. The table is set up simply, and I have successfully called my servlet and returned the XML using this setup: $("#table_1").jqGrid({ datatype : 'xml', ...

Reorganizing the layout of grid items

Currently, I am working on a task involving GRID CSS. The main objective of the task is to utilize GRID specifically, rather than other methods like flex. I have successfully set up two columns in my GRID, each with its own divs. However, what I am struggl ...

AngularJS facing difficulty in resolving the returned promise

I am facing an issue with two cascading drop-downs where the JSON data being returned to the second drop-down is not rendering properly due to a promise resolution problem <div class="row" style="padding-bottom:50px;width:85%;"> <select data ...

Removing a specific item from a panel using JavaScript

Here is the code I have created that functions in a specific way. When a user selects a checkbox, it adds the selected item's name and price to calculate the subtotal based on the quantity inputted by the user. Now, when a user deselects a checkbox, ...

"Apologies, we are currently experiencing difficulties in showcasing the

Could someone help me figure out what I'm doing wrong here? The response from the API is showing in the console but not displaying on the h3 element. I'm really stumped and not sure where the issue lies. export default function Overview(){ ...

Under what circumstances is it possible to iterate through an empty array?

When defining arrays in JavaScript using Array(n), it creates an empty array. If I write the following code: Array(2).map((val) => console.log(val)) Nothing happens when running this code, but if I spread out the elements of the array into another a ...

Effective File Matching: How to Target Specific File Extensions While Excluding Others

Incorporated into the grunt-aws-s3 task, I created the code snippet below. var weekCache = 'css|js'; var yearCache = 'jpg|jpeg|png|gif|ico|eot|otf|ttf|woff|woff2'; var prodFiles = [ {expand: true, cwd: 'public', src: [&a ...

Understanding how to use the 'this' variable in Vue components is essential for efficiently modifying DOM elements. Let's dive into a clarification on the usage of 'this'

Within my vue component, the structure is as follows: export default{ name: '', data: function () { return { var1 :{}, var2 : {}, ... } }, created: function () { this.methodName1() }, methods: { me ...

What is the best way to adjust a 5-row bootstrap grid to fill the entire window space?

Trying to achieve a layout in my bootstrap project with 5 rows that span the full width has been challenging. I'm struggling to grasp how to accomplish this... Here is the initial code snippet: <div class="row car-list btn-group" style="border: 1 ...

Challenges with intercepting objects in THREE.js using Raycaster

Hey there! I'm currently working on generating rays from vertex to vertex and checking if they intersect with a plane geometry. If the intersection occurs, I'm capturing the point of interception and adding it to an array of vertices. However, I ...

Triggering a form submission in JavaScript when a selection is changed

Welcome to my WordPress site! If you would like to check it out, visit this link. Currently, I have a form located next to the text "Filter By Location:". My goal is to have the form submitted automatically when one of the options is selected (onChange). ...

Loading JSON data in AngularJS before parsing and loading HTML content from it

Greetings, I am new to Angular and seeking some guidance. My goal is to limit a list of notifications to three using limitTo, and then load the rest when a button is clicked. Currently, I am unsure about the following: How to set up the "view" and appl ...

Is the alert still displayed during a frozen UI, even when it is within a synchronous ajax call?

Here is the code snippet for implementing global AJAX functionality. jQuery(function (){ $(document).ajaxStop(function() { alert("stop"); }); $(document).ajaxStart(function() { al ...

How to generate a dropdown menu using a deeply nested JSON array

I'm looking to create a series of drop-down lists based on the JSON array provided below. There will be five drop-down lists, and when I select an option in one list, the other four should populate accordingly. For example, if I choose "Hindi" in the ...