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

What is the best way to load a database URL asynchronously and establish a database connection prior to the initialization of an Express

My express.js app is set up to run on AWS lambda, with the database URL stored and encrypted in Amazon KMS. To access the URL, decryption using the AWS KMS service is required. // imports import mongoose from 'mongoose'; import serverless from & ...

What could be causing the lack of change in direction for the initial function call?

There appears to be an issue with image(0) and image(1) in this array that I can't quite understand. The console output shows: i=5; div class="five" id="slides" i=0; div class="one" id="slides" i=1; div class= ...

Pop-up windows, the modern day digital version of fortune cookies

Expressing my requirement might be a bit challenging, but I will do my best. My goal is to create a web application using ASP.Net with C#. This project calls for functionality similar to the Windows popup: When a user clicks on the favorite button in IE- ...

Customizing the default button in Ant Design Popconfirm to display "Cancel" instead

When the Ant Design Popconfirm modal is opened, the Confirm ("Yes") button is already preselected. https://i.stack.imgur.com/bs7W7.png The code for the modal is as follows: import { Popconfirm, message } from 'antd'; function confirm(e) { c ...

Enhance the aesthetic appeal of the imported React component with added style

I need assistance with applying different styles to an imported 'notification' component within my header component. The notification component has its own CSS style, but I want to display it in the header component with unique styling. How can I ...

JavaScript Processing Multiple Input Values to Produce an Output

Hello, I am working on creating a stamp script that will allow users to enter their name and address into three fields. Later, these fields will be displayed in the stamp edition. Currently, I have set up 3 input fields where users can input their data. He ...

Typing into the styled M-UI TextFields feels like a never-ending task when I use onChange to gather input field data in a React project

Having an issue where entering text into textfields is incredibly slow, taking around 2 seconds for each character to appear in the console. I attempted using React.memo and useCallback without success :/ Below is my code snippet: const [userData, setUserD ...

Altering the language code on LinkedIn

As a beginner in programming, I successfully added the linkedin share button to my test webpage. Now, I am hoping to make the button change language based on the user's language selection on the webpage. Linkedin uses a five character language code ( ...

Rendering in React by cycling through an array and displaying the content

I have been working on displaying two arrays. Whenever the button is clicked, a new user is generated and added to the array. My goal is to render the entire array instead of just the newest entries. I've attempted various methods but haven't had ...

The function is trying to access a property that has not been defined, resulting in

Here is a sample code that illustrates the concept I'm working on. Click here to run this code. An error occurred: "Cannot read property 'myValue' of undefined" class Foo { myValue = 'test123'; boo: Boo; constructor(b ...

Struggling to align my image in the center while applying a hover effect using CSS

Hey there, I'm having an issue centering my image when I add instructions for it to tilt on mouseover. If I take out the 'tilt pic' div, the image centers just fine. Can anyone help me identify what I might be doing wrong? Thanks in advance! ...

Is NextJS on-demand revalidation compatible with Next/link?

https://nextjs.org/docs/basic-features/data-fetching/incremental-static-regeneration#on-demand-revalidation According to the NextJS documentation, it appears that on-demand cache revalidation should function properly with regular <a> tags and when t ...

Having Trouble with Updating Variables in AngularJS Service

I am faced with a challenge involving a series of images displayed side by side. My goal is to determine which image has been clicked, retrieve the relevant information, and display it in a modal window. HTML Markup <section class="portfolio-grid ...

Having trouble toggling webcam video in React/NextJS using useRef?

I have created a Webcam component to be used in multiple areas of my codebase, but it only displays on load. I am trying to implement a toggle feature to turn it on and off, however, I am facing difficulties making it work. Below is the TypeScript impleme ...

Creating a seamless scrolling experience with a designated stopping point - here's how to achieve it!

I understand how to implement a scroll effect on an element with a specific class or ID. However, I am unsure of how to make the scrolling stop 20px above that element. I have seen examples using document.getElementById() to achieve this: function scr ...

What is the process to retrieve a function from a router javascript file using node.js?

Dealing with a web application that is not my own, I now have the task of sending out one hundred emails. Unfortunately, the code is poorly documented and written, which means I need to test it to figure out what I can and cannot do. However, I'm uns ...

What is the best way to start data in an Angular service?

I'm currently navigating my way through building my first Angular application. One of the services I am using needs to be initialized with a schema defined in its constant block, but the schema/configuration is not yet finalized. Therefore, I am perfo ...

Strangely odd actions from a JavaScript timepiece

After answering a question, I encountered a problem with my JavaScript clock that displays the day, time, and date on three lines. To make sure these lines have the same width, I used the BigText plugin, which works well except for one issue. tday=new A ...

Exploring the power of Vue3 with Shadow DOM in web components

I've been experimenting with web components using Vue3 and I'm curious about how the Shadow DOM works. I encountered an issue where a third party library was trying to access elements using getElementById() and it was throwing an error because th ...

Check the Full Calendar to see if any events are scheduled for today

I have a group of users who need to save their availability. Currently, I am utilizing Full Calendar and looking for a way to prevent them from adding the same event multiple times on a single day. My tech stack includes VueJs and all events are stored in ...