Utilizing prototype JS to create a dynamic floating widget or banner

I recently developed a custom script based on the original jQuery code found at this link:

However, I encountered issues when attempting to implement it with prototype JS. Specifically, there seems to be accuracy problems with calculating the upper and lower height.

Any insights or suggestions would be greatly appreciated. I have included my code below and a link to see the live version of the script in action.

Website experiencing issues:

Prototype:

document.observe('dom:loaded', function() {
    Element.addMethods({
        floatingWidget: function(el, classes) {
            var $this       = $(el),
            $parent         = $this.getOffsetParent(),
            $window         = $(window),
            top             = $this.positionedOffset().top - parseFloat($this.getStyle('marginTop').replace(/auto/, 0)),
            bottom          = $parent.positionedOffset().top + $parent.getHeight() - $this.getHeight();

            if ($parent.getHeight() > $this.getHeight()) {
                Event.observe($window, 'scroll', function (e) {
                    var y = document.viewport.getScrollOffsets().top;
                    if (y > top) {
                        $this.addClassName(classes.floatingClass);
                        if (y > bottom) {
                            $this.removeClassName(classes.floatingClass).addClassName(classes.pinnedBottomClass);
                        } else {
                            $this.removeClassName(classes.pinnedBottomClass);
                        }
                    } else {
                        $this.removeClassName(classes.floatingClass);
                    }
                });
            }
            return el;
        }
    });

    $('floating-widget').floatingWidget({
        floatingClass: 'floating',
        pinnedBottomClass: 'pinned-bottom'
    });
});

Answer №1

When working with Prototypejs instead of jQuery, the function equivalent to offset() is cumulativeOffset(). Similarly, for outerHeight() you would use measure('margin-box-height') (which can be improved by using the Element.Layout object). Therefore, your script should appear as follows:

floatingWidget: function(el, classes) {
    var $this        = $(el),
        $parent      = $this.getOffsetParent(),
        $window      = $(window),
        top          = $this.cumulativeOffset().top - $this.measure('margin-top'),
        bottom       = $parent.cumulativeOffset().top + $parent.getHeight() - $this.measure('margin-box-height');

if ($parent.getHeight() > $this.measure('margin-box-height')) {
...

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

I am looking to build an array that can store five numbers inputted by the user. Following that, I want to utilize a for loop to display the contents of the array. How can I accomplish this task?

Looking for help to store 5 unknown numbers in an array and then display them after the user has entered all 5 numbers. Can anyone assist me in creating an array of size 5 and using a for loop to show the numbers? Here is the code I currently have: ...

If you don't get the correct response from the $.ajax success function

I am utilizing the $.ajax function to retrieve content, however I am encountering an issue when attempting to display special tags from it. The data appears to be missing! This is how I am currently handling it: $(document).ready(function(){ $("button") ...

Searching for a table element and clicking it based on its text with Protractor

<tr id="item" ng-repeat="item in itemList> <td id="code" ng-repeat="column in columns">Different Text</td> </tr> I have encountered some similar issues before, but I am still struggling to find a solution. Here is what I have at ...

Is there a way to ensure a Javascript alert appears just one time and never again?

I struggle with Javascript, but I have a specific task that needs to be completed. I am participating in a school competition and need an alert to appear only once throughout the entire project, not just once per browsing session. The alert will inform ...

Tips for creating a concise summary of written content

I am interested in creating an AI-powered summary generator for text input within a textarea element. Below is the HTML code snippet I have been working with: <textarea id="summary">Enter your text here</textarea> If you hav ...

HTML/PHP/JS - Submit Form and Upload File Simultaneously

I need to create a form with a Photo Upload Input that allows users to upload pictures before submitting the form for faster processing. The form should also support uploading multiple files, display a progress bar, and provide a preview of the uploaded im ...

Attempting to insert an element after the .load event has been triggered

I have been attempting to update the contents of ".myShop" after it's loaded from an external XML file, but without success. I believe my timing is correct, but I suspect that a loaded element may not be part of the DOM? Here's what I'm exp ...

Limit users to entering either numbers or letters in the input field

How can I enforce a specific sequence for user input, restricting the first two characters to alphabets, the next two to numbers, the following two to characters, and the last four to numbers? I need to maintain the correct format of an Indian vehicle regi ...

Is it necessary to implement the useCallback hook along with React.memo for rendering optimization in React components?

As I delved into understanding how useCallback and useMemo function in React to optimize app performance, I decided to create a simple app for experimentation. What I observed was that the callback function (OnBlurHandler) passed to my child component trig ...

Is there a way to include a button at the top of the Notiflix.Loading() overlay for closing or stopping it?

I've integrated the "notiflix" library into my project, and I'm currently using notiflix.loading.pulse() for a lengthy process. While this works perfectly fine, I would like to add a button (for closing/stopping the process) on top of the loading ...

I have a desire to use Javascript to control CSS styles

Within the CSS code below, I am seeking to vary the size of a square randomly. This can be achieved using the Math.random() property in Javascript, but I am uncertain how to apply it to define the size in CSS. #square { width: 100px; height: ...

Parsing Problem---Is there a Parsing Error?

My code includes a function that calculates the total of cells and then displays it in a textbox: function UpdateTotal() { var total = parseFloat('0.0'); $("#<%= gvParts.ClientID %>").find("tr").not(".tblResultsHeader").each(funct ...

Avoid the rendering of child elements in React

How can I skip rendering children in React? I want to enclose existing DOM nodes on a page within a React component. I need to render the frame only, excluding the static content which already exists as pre-existing DOM nodes. Is there a way to achieve t ...

Baffled by the data visualization produced by Google Chart using information from

Perhaps I'm being a bit ambitious, but I managed to create a basic Chart using GoogleCharts. The problem is that I have to input the values manually, but I want to retrieve them from the Database. I know JSON can accomplish this, but I've spent f ...

Shift the sideways movement of the triangle symbol

I currently have a main menu in the header with links, accompanied by a moving triangle that changes position as the user hovers from one page to another. While I want to maintain the dynamic movement, I am seeking a smoother transition effect similar to w ...

What is the best method for users to add a div element and its contents?

As someone new to the world of web development, I am currently learning and working on a project. I have encountered an issue with creating a custom div that includes a link and user-defined text. I want the div to be generated automatically when the use ...

Tips for accomplishing multiple event triggers and event recollection (benefits that combine features of events and promises)

What I Need Seeking an event system that meets my requirements due to the asynchronous nature of my applications. Specifically, I need the events to have the ability to fire multiple times and for listeners to immediately respond if an event has already b ...

Extracting data from a MySQL result array

I've encountered an issue with extracting a value from an array containing JSON data. Below is the JSON data I received (printed using console.log(rows[0])): [ { User_ID: 28, Email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email ...

AngularJS: Showcase HTML code within ng-view along with its corresponding output displayed in a navigation format such as Html, Css, JS, and Result

Currently, I am working on a web application. One of the screens, screen-1, consists of a series of buttons labeled 'Code'. When a user clicks on any of these buttons, it loads a different HTML page, screen-2, in the ng-view using $location.path( ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...