I'm not skilled in programming, so I'm not sure what the problem is with the code

While working on my Blogger blog, I encountered the need to add a fixed sidebar ad widget that would float along the screen. After trying multiple codes, I finally found one that worked. However, using the template's built-in variable functions led to other malfunctions. The current code works fine, but there is a slight issue - users can't scroll down to the bottom of the screen on desktop and mobile.

I attempted various methods to solve this problem, but only this particular code snippet worked. Unfortunately, it prevents scrolling to the bottom of the screen. My goal is to have a sticky sidebar fixed ad that stays visible regardless of scrolling direction. Debugging the code was challenging for me as I am not well-versed in programming.

Here is the code snippet:

/*<![CDATA[*/
// Sticky Plugin
// =============
// Author: abc
(function($) {
var defaults = {
        topSpacing: 0,
        bottomSpacing: 0,
        className: 'is-sticky',
        center: false
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    scroller = function() {
        var scrollTop = $window.scrollTop(),
            documentHeight = $document.height(),
            dwh = documentHeight - windowHeight,
            extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
        for (var i = 0; i < sticked.length; i++) {
            var s = sticked[i],
                elementTop = s.stickyWrapper.offset().top,
                etse = elementTop - s.topSpacing - extra;
            if (scrollTop <= etse) {
                if (s.currentTop !== null) {
                    s.stickyElement.css('position', '').css('top', '').removeClass(s.className);
                    s.currentTop = null;
                }
            }
            else {
                var newTop = documentHeight - s.elementHeight - s.topSpacing - s.bottomSpacing -     scrollTop - extra;
                if (newTop < 0) {
                    newTop = newTop + s.topSpacing;
                } else {
                    newTop = s.topSpacing;
                }
                if (s.currentTop != newTop) {
                    s.stickyElement.css('position', 'fixed').css('top', newTop).addClass(s.className);
                    s.currentTop = newTop;
                }
            }
        }
    },
    resizer = function() {
        windowHeight = $window.height();
    };
// should be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
if (window.addEventListener) {
    window.addEventListener('scroll', scroller, false);
    window.addEventListener('resize', resizer, false);
} else if (window.attachEvent) {
    window.attachEvent('onscroll', scroller);
    window.attachEvent('onresize', resizer);
}
$.fn.sticky = function(options) {
    var o = $.extend(defaults, options);
    return this.each(function() {
        var stickyElement = $(this);
        if (o.center)
            var centerElement = "margin-left:auto;margin-right:auto;";
        stickyId = stickyElement.attr('id');
        stickyElement
            .wrapAll('<div id="' + stickyId + 'StickyWrapper" style="' + centerElement + '"></div>')
            .css('width', stickyElement.width());
        var elementHeight = stickyElement.outerHeight(),
            stickyWrapper = stickyElement.parent();
        stickyWrapper
            .css('width', stickyElement.outerWidth())
            .css('height', elementHeight)
            .css('clear', stickyElement.css('clear'));
        sticked.push({
            topSpacing: o.topSpacing,
            bottomSpacing: o.bottomSpacing,
            stickyElement: stickyElement,
            currentTop: null,
            stickyWrapper: stickyWrapper,
            elementHeight: elementHeight,
            className: o.className
        });
    });
};
})(jQuery);
/*]]>*/
</script>
<script type='text/javascript'>
$(document).ready(function(){
$("#mblfloater").sticky({topSpacing:0});
});

Answer №1

HTML and CSS play a crucial role in determining the functionality of the provided code. Below is an illustrative example:

// Sticky Plugin
// =============
// Author: abc
(function($) {
  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      center: false
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    // The rest of the script remains unchanged...</answer1>
<exanswer1><div class="answer" i="77845699" l="4.0" c="1705652687" v="1" a="bXBsdW5namFu" ai="295783">
<p>The effectiveness of the code depends greatly on the HTML structure and CSS styling. For better understanding, see the below representation:</p>
<p><div>
<div>
<pre class="lang-js"><code>// Sticky Plugin
// =============
// Author: abc
(function($) {
  var defaults = {
      topSpacing: 0,
      bottomSpacing: 0,
      className: 'is-sticky',
      center: false
    },
    $window = $(window),
    $document = $(document),
    sticked = [],
    windowHeight = $window.height(),
    scroller = function() {
      var scrollTop = $window.scrollTop(),
        documentHeight = $document.height(),
        dwh = documentHeight - windowHeight,
        extra = (scrollTop > dwh) ? dwh - scrollTop : 0;
      for (var i = 0; i < sticked.length; i++) {
        var s = sticked[i],
          elementTop = s.stickyWrapper.offset().top,
          etse = elementTop - s.topSpacing - extra;
        if (scrollTop <= etse) {
          if (s.currentTop !== null) {
            s.stickyElement.css('position', '').css('top', '').removeClass(s.className);
            s.currentTop = null;
          }
        } else {
          var newTop = documentHeight - s.elementHeight - s.topSpacing - s.bottomSpacing - scrollTop - extra;
          if (newTop < 0) {
            newTop = newTop + s.topSpacing;
          } else {
            newTop = s.topSpacing;
          }
          if (s.currentTop != newTop) {
            s.stickyElement.css('position', 'fixed').css('top', newTop).addClass(s.className);
            s.currentTop = newTop;
          }
        }
      }
    },
    resizer = function() {
      windowHeight = $window.height();
    };
  // This method is expected to be more efficient than using $window.scroll(scroller) and $window.resize(resizer):
  if (window.addEventListener) {
    window.addEventListener('scroll', scroller, false);
    window.addEventListener('resize', resizer, false);
  } else if (window.attachEvent) {
    window.attachEvent('onscroll', scroller);
    window.attachEvent('onresize', resizer);
  }
  $.fn.sticky = function(options) {
    var o = $.extend(defaults, options);
    return this.each(function() {
      var stickyElement = $(this);
      if (o.center)
        var centerElement = "margin-left:auto;margin-right:auto;";
      stickyId = stickyElement.attr('id');
      stickyElement
        .wrapAll('<div id="' + stickyId + 'StickyWrapper" style="' + centerElement + '"></div>')
        .css('width', stickyElement.width());
      var elementHeight = stickyElement.outerHeight(),
        stickyWrapper = stickyElement.parent();
      stickyWrapper
        .css('width', stickyElement.outerWidth())
        .css('height', elementHeight)
        .css('clear', stickyElement.css('clear'));
      sticked.push({
        topSpacing: o.topSpacing,
        bottomSpacing: o.bottomSpacing,
        stickyElement: stickyElement,
        currentTop: null,
        stickyWrapper: stickyWrapper,
        elementHeight: elementHeight,
        className: o.className
      });
    });
  };
})(jQuery);

$(document).ready(function() {
  $("#mblfloater").sticky({
    topSpacing: 0
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div id="mblfloater" style="width:40px">Hello</div>
<div style="height:5000px; position: relative; margin-left:40px"> <!-- Parent with relative position -->
  Some text
  <div style="position: absolute; bottom: 0; width: 100%;"> <!-- Child with absolute position -->
    bottom of div
  </div>
</div>
<div style="position: fixed; bottom: 0;">Footer</div>

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

Deleting the stylesheet exclusively within the confines of the React application window

Here is an image that will help illustrate the issue: https://i.stack.imgur.com/VA7fw.png If you want to check out the code sandbox for this problem, you can visit: https://codesandbox.io/s/annoying-stylesheet-2gpejc?file=/public/index.html I am current ...

Generating an interactive Datepicker using Jquery

How can I design a dynamic date picker similar to the image provided below? I have attempted to create one, but I am looking for a more interactive date picker. Is there a way to achieve the design shown in the image? The current date picker does not meet ...

Guide on retrieving a nested JSON array to extract a comprehensive list of values from every parameter within every object

A JSON file with various data points is available: { "success": true, "dataPoints": [{ "count_id": 4, "avg_temperature": 2817, "startTime": "00:00:00", "endTime": "00:19:59.999" }, ... I am trying to extract all the values of & ...

Encountering challenges with implementing debouncing functionality in React programming

import React,{useState} from 'react'; const app = () => { const [inputValue, setInputValue] = useState(); const handleChange = (e) => { setInputValue(e.target.value); console.log(inputValue); } const d ...

What is the best way to attach an event again in jQuery?

My JavaScript/jQuery code initiates a listener to highlight DOM elements when a button is clicked. By clicking the button, the listener event starts (e.g. highlight : function()). If I click on any part of the webpage, the listener stops. However, if I ...

Unable to establish connection with nodejs server from external devices

Currently, I am leveraging a React client along with a Node.js server (MERN Stack). The server operates smoothly on my computer; however, I encounter difficulties when attempting to connect from my mobile phone to the IPv4 of my PC using the correct port ...

saving the hash key in a separate array

Currently, I have a collection of key-value pairs that need to be stored in another array. However, I am facing difficulties with the logic as I am unable to keep track of which keys-values have already been assigned while iterating over the list of object ...

I am attempting to access an Angular variable using JavaScript, but unfortunately, I am encountering some issues

I'm currently implementing the following code: window.onload=function(){ var dom_el2 = document.querySelector('[ng-controller="myCtrl"]'); var ng_el2 = angular.element(dom_el2); var ng_el_scope2 = ng_el2.scope(); console.log ...

Move buttons from one group to another group

I have a task to update a group of buttons with different buttons depending on the initial button chosen. Button1: when clicked, both buttons will be replaced by Button1a and Button1b Button2: when clicked, both buttons will be replaced by Button2a ...

Utilizing Ajax in conjunction with Ruby on Rails

I have a question that may be quite basic (I am new to Rails 3). I am looking to implement Ajax functionality where once a user clicks on a link, it triggers a $.post call and initiates some server-side changes. Within the _share partial file, I currently ...

The data I am trying to obtain is not being returned by my hook as expected

I am trying to create a hook that fetches all properties from a database. The function I have is asynchronous, and when I call the hook in another function, it returns an empty array []. I understand that fetching data from the database is an asynchronous ...

Unique name for the transition animation on SSR-Nuxt page transitions

Attempting to implement a dynamic transition name for Nuxt page transitions as shown below: export default{ data() { return { prevHeight: 0, transitionName: 'page' }; }, transition: { na ...

``Troubleshooting Problem with Tailwind's Flex Box Responsive Grid and Card Elements

Starting point: Preview https://i.sstatic.net/zfzBU.jpg Code : <div class="container my-12 mx-auto"> <div className="flex flex-wrap "> {error ? <p>{error.message}</p> : null} {!isLoading ...

Retrieve the initial occurrence that meets the conditions across three columns in MySQL

I am currently utilizing a NodeJS REST API that connects to a MySQL database. Within this database, there is a specific table we will refer to as Table_01: | C_0| C_1| C_2| C_3| | 1 | A1 | B1 | 1 | | 2 | A1 | B2 | 0 | | 3 | B1 | A1 | 0 | | 4 | A2 | ...

What is the process for using Discriminators, the Mongo DB API, and Mongoose to insert data into Cosmos DB?

Issue Overview I am currently facing a challenge in writing documents to my Cosmos DB using the Mongo DB API and Mongoose for Object Modeling. To optimize costs, I aim to store all documents in a single collection by utilizing Discriminators. The project ...

problem when trying to establish the minimum height for a div element prior to the website being fully loaded, considering the

Having trouble with a CSS issue that seems simple but I can't find a solution for. I have a main div with a min-height set to a certain value, specified in %. Since there is no outer div, the min-height won't display if it's given in px. I ...

Is this method an effective way to create global states across React components?

After delving deep into props-drilling while coding a full-fledged web application with React, I've decided to explore using React 'contexts'. Following the guidelines in the React documentation, I am implementing an approach to make my stat ...

Text box is not automatically filling up when selecting from dropdown menu

I am currently facing an issue with a dropdown box that offers three different selections. I want the Group ID associated with the selected group to automatically populate in the textbox below. How can I achieve this functionality? Whenever I make a selec ...

Problems with Bootstrap affix scrolling in Internet Explorer and Firefox

I'm encountering an issue with the sidebar on my website. I've implemented Bootstrap affix to keep it fixed until the end of the page, where it should move up along with the rest of the content at a specific point... Everything seems to be worki ...

Tips for altering the visibility of a different class on hover using jss

Exploring the features of material ui react Below is my scss code snippet (when hovering over .content, the .replyBtn becomes visible): .content { &:hover { .replyBtn { visibility: visible } } } .replyBtn { visibility: hidden; } ...