Trigger an event when the menu is outside the viewport and then lock the menu to the top of the viewport

I am trying to create a menu element that remains fixed at the top of the browser viewport as the user scrolls, ensuring it is always visible. In my webpage layout, the menu sits below some text in the header initially. Once the user scrolls past the header, I want the menu to become fixed to the top of the viewport, allowing it to remain visible. The menu should return to its original position when the user scrolls back up to reveal the header again.

Update: The design specifications require the menu to be positioned below the header to display an important message before the menu options. It should only become fixed at the top of the viewport after scrolling past the header.

I believe I may need JQuery to achieve this functionality. Can someone provide some examples or guidance on how to implement this?

<html>
<body>
<header id="header">Header text...
   <menu id="menu"><a href="/">Home</a> | <a href="/Help">Help</a></menu>
</header>
<section id="more">More text...</section>
</body>
</html> 

Answer №1

This serves as a demonstration of how jQuery can be utilized to achieve a specific effect. To further understand its functionality, consider adding 4 or 5 paragraphs beneath your header and observe how the script operates. For a visual representation, refer to the example on CodePen below.

HTML:

<header>
    <div class="logo">STICKY MENU ON SCROLL!</div>
    <div class="intro">Insert tagline here</div>
    <div class="menu">Menu content - home - links - etc.</div>
</header>

CSS:

.logo {font-size:40px; font-weight:bold;color:#00a; font-style:italic;}
.intro {color:#777; font-style:italic; margin:10px 0;}
.menu {background:#00a; color:#fff; height:40px; line-height:40px; letter-spacing:1px; width:100%;}

JS:

$('.menu').addClass('original').clone().insertAfter('.menu').addClass('cloned').css('position','fixed').css('top','0').css('margin-top','0').css('z-index','500').removeClass('original').hide();

scrollIntervalID = setInterval(stickIt, 10);

function stickIt() {

var orgElementPos = $('.original').offset();
orgElementTop = orgElementPos.top;

if ($(window).scrollTop() >= (orgElementTop)) {
// user has scrolled past the original position; show only the sticky cloned element now.

orgElement = $('.original');
coordsOrgElement = orgElement.offset();
leftOrgElement = coordsOrgElement.left;
widthOrgElement = orgElement.css('width');
$('.cloned').css('left', leftOrgElement+'px').css('top', 0).css('width', widthOrgElement).show();
$('.original').css('visibility','hidden');
} else {
// user has not yet scrolled past the menu; continue displaying the original menu.
$('.cloned').hide();
$('.original').css('visibility','visible');
}
}

VIEW THE DEMO HERE

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

Switch up the checkbox status using a hyperlink within the checkbox manipulation strategy

My coworker and I collaborated on a website that features a FAQ page. Each question is followed by an "Answer" spoiler button. By clicking the button, the answer is revealed below the current question and above the next one. Clicking the button again hides ...

Interacting with APIs in Svelte applications

I'm fairly new to utilizing Svelte and JavaScript. I've been attempting to construct a page that incorporates numerous API components from external websites, but I'm facing some challenges. I'm uncertain about where exactly to place the ...

Submitting a form using Ajax that was generated with the help of jQuery

Using a table with various rows, each row has an edit button. Upon clicking the edit button, a form is generated using ajax/json to populate the form data based on the selected row. An issue arises when setting up the ajax for this form. Although the met ...

Updating Select Options with Multiple Values using Javascript

My goal is to update the selected value of multiple select elements simultaneously using JavaScript. However, I am facing an issue where my script only updates one select element instead of all of them on the page. Unfortunately, I cannot modify the id att ...

Guide to hosting AngularJS Material documentation on a local server

After gathering the latest angularjs material, I noticed that the links in the document lead to absolute URLs at material.angularjs.org/.... I wish to have access to read the documentation and demonstration content locally. ...

Failure to retrieve data with ajax call in php script

I am a beginner in the world of JS and PHP. I am taking on the challenge of teaching myself. Following the guidance provided in this answer from Stack Overflow, I attempted to implement it in my project. Unfortunately, I am facing challenges and would gre ...

Using ajax with Django to optimize queries involving select_related() and many to many fields

Seeking help with a view that needs to handle both ajax and regular HTTP requests. Here's a simplified version of what I have: def tag_search(request, tag): items = Item.objects.filter(tags__tagname__exact=tag) if request.is_ajax(): ...

Organize arrays within arrays in Javascript

My array of data is structured for visualization as shown below: var Dataset1 = [ { "commentBy": "saurabh", "comment": "Testing", "datestamp": "07/07/2017", "weekcount": 1 }, { "commentBy": "raman", "comment": "Planning", ...

Unique form validation process: utilizing JSON

Attempting to validate JSON input using Angular's FormControl. The typical approach, such as validating an email address, would involve: <form name="form"> <textarea ng-model="data.email" type="email" name="email"></textarea> &l ...

Script tags that are included within the element Vue vm is bound to can result in a template error

Here is the Laravel layout template that I am currently working with: <html lang="en"> <head> <meta name="csrf-token" content="{{ csrf_token() }}"> <link href="{{ URL::asset('css/libs.css') }}" rel="stylesheet"> ...

State variable in Redux is not defined

While there have been numerous similar inquiries on this platform, I haven't been able to find a solution to my particular issue. Below is the React component in question: class MyTransitPage extends Component { componentDidMount() { this.pro ...

What is the process for verifying that a checkbox is unchecked through the use of Ajax and PHP?

I am working with a checkbox element in my form. Here is the code: <input type="checkbox" value="yes" id="checkBox"> This checkbox is part of my form, and I am sending the form data to a PHP file using Ajax: var check = $('#checkBox').v ...

Retrieve a specific object from a JSON array nested within an array of objects, by utilizing a PHP script

There are two JSON files that contain JSON objects, with one of the files containing an array of objects within another array of objects. The first file is orders.json: { "orders": [ { "address": null, ...

Bypassing 403 error in redux and react application

It appears that Redux or express is failing to handle an error scenario where a user updates their password using a reset password link token. An error message should be displayed as follows: if (this.props.error) { return ( <div> ...

Laravel ajax crud functionality hindered by malfunctioning back button

Attempting to navigate back to the previous page is not functioning properly. Instead, I am encountering an error message that states: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (Connection: mysql, SQ ...

Deleting content in a text area when specific text is entered

Is there a way to clear the textarea value if I type in <br>? The code I have right now is shown below. I understand that this may seem like an odd request, but I am experimenting with a typing effect. function eraseText() { document.getElemen ...

Aligning an element perfectly at the top within a column

I have two columns side by side. The column on the left contains HTML that I cannot control. On the right side, I need to display a comment box that should align with the text clicked on the left hand side. Is it possible to position an element absolutely ...

Show off beautiful text using a styled pre component in a React application

I've been attempting to highlight specific text within a React pre element, but unfortunately, it doesn't seem to be working as expected. Instead of displaying the highlighted text, it shows [object Object]. const Text = styled.pre ` col ...

What is Microsoft's equivalent to an embedded Java web applet?

Is there a Microsoft alternative to embedded Java web applets? Can you provide an example from the internet? Furthermore, why is ajax prevalent in dynamic web development compared to embedded applications? ...

Grunt is designed to generate a single file, instead of producing multiple files

I have a simple Gruntfile that is designed to read a plain text file line by line and create an html file of the same name for each line. However, it seems to only work with one line in the file at a time, not multiple lines. Here is the console output wh ...