Is there a way to trigger this floating menu to appear only when certain #divs are in view?

I was looking to create a floating menu and came across a helpful script on here

/* Script by: www.jtricks.com
 * Version: 1.12 (20120823)
 * Latest version: www.jtricks.com/javascript/navigation/floating.html
 *
 * License:
 * GNU/GPL v2 or later http://www.gnu.org/licenses/gpl-2.0.html
 */
var floatingMenu =
{
    hasInner: typeof(window.innerWidth) == 'number',
    hasElement: typeof(document.documentElement) == 'object'
        && typeof(document.documentElement.clientWidth) == 'number'};

var floatingArray =
[
];

floatingMenu.add = function(obj, options)
{
    var name;
    var menu;

    if (typeof(obj) === "string")
        name = obj;
    else
        menu = obj;


    if (options == undefined)
    {
        floatingArray.push( 
            {
                id: name,
                menu: menu,

                targetLeft: 0,
                targetTop: 0,

                distance: .07,
                snap: true,
                updateParentHeight: false
            });
    }
    else
    {
        floatingArray.push( 
            {
                id: name,
                menu: menu,

                targetLeft: options.targetLeft,
                targetRight: options.targetRight,
                targetTop: options.targetTop,
                targetBottom: options.targetBottom,

                centerX: options.centerX,
                centerY: options.centerY,

                prohibitXMovement: options.prohibitXMovement,
                prohibitYMovement: options.prohibitYMovement,

                distance: options.distance != undefined ? options.distance : .07,
                snap: options.snap,
                ignoreParentDimensions: options.ignoreParentDimensions,
                updateParentHeight:
                    options.updateParentHeight == undefined
                    ? false
                    : options.updateParentHeight,

                scrollContainer: options.scrollContainer,
                scrollContainerId: options.scrollContainerId,

                confinementArea: options.confinementArea,

                confinementAreaId:
                    options.confinementArea != undefined
                    && options.confinementArea.substring(0, 1) == '#'
                    ? options.confinementArea.substring(1)
                    : undefined,

                confinementAreaClassRegexp:
                    options.confinementArea != undefined
                    && options.confinementArea.substring(0, 1) == '.'
                    ? new RegExp("(^|\\s)" + options.confinementArea.substring(1) + "(\\s|$)")
                    : undefined
            });
    }
};

// Remaining code retains its original logic

floatingMenu.insertEvent(window, 'load', floatingMenu.init);

if (typeof(jQuery) !== 'undefined')
{
    (function ($)
    {
        $.fn.addFloating = function(options)
        {
            return this.each(function()
            {
                floatingMenu.add(this, options);
            });
        };
    }) (jQuery);
}

The script requires the menu to have #floatdiv id. I created my div, #floatdiv, and added the following line of javascript to the head to make the action start working:

<script type="text/javascript">  
    floatingMenu.add('floatdiv',  
        {  
             targetLeft: 250,                

            targetTop: 290,                

            snap: true  
        });  
</script>

The CSS for #floatdiv is as follows,

#floatdiv{
    height:45px;
    width:830px;
    z-index:2;
}

The script is functioning properly. However, I am now seeking a way to trigger the floating menu only when specific divs are entered, rather than float continuously while scrolling. Any suggestions?

Answer №1

Does this resemble what you're looking for?

HTML

<div id="header">HEADER</div>
<div id="content">
    <div id="left">LEFT</div>
    <div id="right">RIGHT</div>
</div>
<div id="footer">FOOTER</div>

JavaScript

$(function() {
    var $sidebar = $("#right"), 
        $window = $(window),
        rightOffset = $sidebar.offset(),
        rightDelta = $("#footer").offset().top - $("#header").offset().top - $("#header").outerHeight() - $("#right").outerHeight(),
        topPadding = 15;

    $window.scroll(function() {
            $sidebar.stop().animate({
                marginTop: Math.max(Math.min($window.scrollTop() - rightOffset.top + topPadding, rightDelta), 0)
            });
    });

});

View the demo here.

I hope this provides the assistance you need.

Answer №2

The script mentioned in the question was authored by me.

This highly adaptable script allows for a div to float within a designated area, such as another container div. For instructions on implementing this functionality, please refer to:

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

Center Items in Flexbox, Implementing React Material with React

In my React App, I am utilizing flexbox and React Material to align the searchbar and clear button on the same line with space between them. Here is the link for reference: CLICK HERE <div className={classes.searchBarSection}> <Paper com ...

The power of Three.js comes alive when utilizing appendChild and returning elements

I recently encountered an interesting issue that I managed to resolve, but out of sheer curiosity, I would love for someone to shed some light on why this problem occurred. Below is the snippet of my HTML code: <!DOCTYPE html> <html> < ...

The fade effect on an element cannot be achieved using setTimeout

I'm trying to call a tooltip and hide it after 9 seconds, but for some reason, it's not working as expected. The issue I'm facing is that the "tooltip" only hides after it initially loads. It doesn't respond when I click on the "Touch ...

Enhancing the SVG font size through custom CSS styling

Working with an SVG element and utilizing CSS to adjust the font-size of the text within the SVG. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1280 720"> <rect class="vBoxRect" width="1280" height="720" fill="none" stroke="red"& ...

Conceal/reveal specific sections of a table cell using jQuery

Here is a table I have: A header Another header First (some-text-initially-hidden) click row Upon clicking, it changes to: A header Another header First (some-text-should-be visible now) click row However, the text "some-text-initially-hi ...

Is there a way to display a secondary header once the page is scrolled down 60 pixels?

.nav-header2{ background: purple; display: flex; justify-content: center; align-items: center; } .header2-container{ width: 68vw; height: 60px; padding: 0 2vh; border: 1px solid red; ...

Only when the tab is refreshed will React Query be shown

I'm facing a tricky situation and can't seem to find a solution through Google search. My current challenge involves using the React Query library with TSX to display fetched data in a simple list. However, the data is only fetched and displayed ...

Sending a large number of values unrestrictedly via ajax

I'm currently working on implementing a filter for the Google Maps API on our website. This filter will allow users to display information related to specific locations that they select by checking corresponding checkboxes. As I am still relatively ne ...

After zooming in on the canvas and panning, I encountered a problem where I was unable to drag objects within the canvas. Instead, the canvas continued to pan as I tried to move the objects

1) I have the ability to pan the canvas and drag images without scaling or zooming. 2) When scaling or zooming, I can still drag images within the canvas. 3) However, if I try to pan the canvas after zooming and then attempt to drag images, only the canv ...

Establish height and width parameters for creating a dynamic and adaptable bar chart with recharts

I am currently facing an issue with recharts while trying to implement a BarChart. The setting width={600} and height={300} is causing the Barchart to be fixed in size, rather than responsive. How can I make the BarChart responsive? I attempted using per ...

"Can anyone provide insights on how to retrieve the URL within the .success function of the $http.get function in Angular

Here is the code snippet of my controller: var app = angular.module('callapp', []); app.controller('eController', function($scope, $http, $log) { $scope.urlString = []; //these values are populated for( var i=0; i<3; ++i) ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

Is there a way to automatically load Moment.JS within Compound.JS?

Is it possible to make Moment accessible worldwide using the Compound framework with its module auto-loading feature? How can "moment" be included in the autoload array and used within the application? ...

Is there a way to efficiently center an image within an HTML document using HtmlAgilityPack?

I recently created a basic HTML document using the HtmlAgilityPack, which includes an embedded image in base64 format. Dim myDocument As New HtmlDocument() Dim pageContent As String = "<!DOCTYPE html> <html> <body> <img src=""data:im ...

table with flexible cell width and fixed table width

I've been troubleshooting this issue for days, but I just can't seem to find a solution! The problem lies within a table used on a webpage. If I don't specify table-layout, I can make one cell width dynamic, but I lose the ability to set &a ...

Tips for Styling "Opened" Elements within the <Summary><Details> Web Design in HTML using CSS? (a color coding challenge)

I've dedicated a significant amount of time crafting my ultimate HTML FAQ with detailed summaries styled in CSS. There's one aspect that continues to elude me - achieving the perfect orange background color for expanded topics: My goal is for a ...

"Implementing a fixed header and footer with a scrolling content area within a parent div that has a fixed position for

I'm seeking assistance with some CSS tasks. Specifically, I need to maintain the same functionality in responsive view when utilizing a fixed position in the parent div (Bootstrap 5 is in use). (the main focus of this project is on fullscreen view of ...

send document through ajax

Having some trouble with this task. Here is what I've managed to put together so far: <input id="newFile" type="file"/> <span style="background-color:orange;" onClick="newImage()">HEYTRY</span> I know it's not much progress. ...

Dragging the entire ForceDirected Graph in D3.js is not functioning

tag, I am currently working on implementing a D3 force directed graph using D3 v6 and React. The graph includes features such as zoom functionality and draggable nodes. However, as the graph can become quite complex and large due to dynamic data, I aim to ...

Vue.js Issue: Image not properly redirected to backend server

Having an issue with my Vue app connecting to the backend using express. When I attempt to include an image in the request, it doesn't reach the backend properly. Strangely though, if I bypass express and connect directly from the Vue app, everything ...