When a user scrolls over an element with a data-attribute,

Looking to create a dynamic header effect on scroll? I have two headers, menu1 by default and menu2 hidden with display:none.

In specific sections of my website, I've added a special attribute (data-ix="change-header") to trigger the header change. The desired effect is that as users scroll through the site and reach a section with data-ix="change-header", the headers should switch - hiding menu1 and showing menu2.

I currently have some code in place, but I'm struggling with implementing the scroll functionality. Any suggestions?

if ($(this).attr("data-ix") == "change-header"){
    $("‪#‎menu1‬").css("display","none");
    $("‪#‎menu2‬").css("display","block");
} else {
    $("#menu1").css("display","block");
    $("#menu2").css("display","none");
}

Here's an example of my HTML structure:

<header id="menu1"></header>
<header id="menu2"></header>
<div class="test" data-ix="change-header"></div>
<div class="test"></div>
<div class="test" data-ix="change-header"></div>
<div class="test" data-ix="change-header"></div>
<div class="test" data-ix="change-header"></div>
<div class="test"></div>
<footer></footer>

Any assistance would be greatly appreciated!

Answer №1

Interested in adding some cool scroll-based animations to your website? Check out this awesome tool:

This lightweight library is only 6KB when compressed, and it allows you to easily animate elements or change CSS classes as users scroll through your page :)

Answer №2

If you want to determine the threshold values for changing headers, you can use the following approach:

var thresholds = [];
$('.test').each(function(index, element) {
  // Determine whether to change the header based on the data-ix attribute
  thresholds.push([element.offsetTop, $(element).data('ix') === 'change-header']);
});

After defining the thresholds, you can check them during each scroll event:

// Cache menu elements
var $menu1 = $('#menu1'), $menu2 = $('#menu2');

// Update header once and listen for scroll events
update();
$(window).on('scroll', update);

function update() {
  // Get the current vertical scroll position
  var scrollTop = $(this).scrollTop(), thresh;
  for (var i = 0, len = thresholds.length; i < len; ++i) {
    thresh = thresholds[i];
    if (thresh[0] >= scrollTop) break;
  }

  // Update the header depending on the threshold values
  if (thresh[1]) {
    $menu1.hide();
    $menu2.show();
  } else {
    $menu2.hide();
    $menu1.show();
  }
}

You can view a working example on Plunker.

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

JavaScript - Utilizing jQuery to dynamically add and remove input fields

I have a form where input fields (groups) are added dynamically. Here's a glimpse of the complex form: FIDDLE The error on the console reads: Error: uncaught exception: query function not defined for Select2 s2id_autogen1 With existing fields in t ...

Using JavaScript, aim for a specific element by its anchor headline

I'm looking to make some changes to my navigation menu, specifically hiding the home menu item unless the mobile navigation menu is toggled. Is there a way for me to target the "home" anchor title and apply the active class to it when toggled, similar ...

Showing no background color until the user lifts their finger

I am currently in the process of developing a website. The navigation on the website starts off as transparent (background: transparent) when opened, but as soon as you start scrolling, it should transition to a colorful state with shades like grey, midnig ...

Looking to implement a jQuery ajax request for footable v3 specifically for a webservice. How can I achieve this?

After reviewing the footable documentation, I noticed that they only provide a method for fetching data from a file, and not from a webservice. Despite trying various combinations to retrieve JSON-formatted data into the footable instance, I have had no su ...

How to Create a Hover Drop Down Menu that Disappears When Not Hovered Over

When I hover over the drop down menus on my Navbar, they display perfectly. However, it's impossible to click on the items in the menu because as soon as I move the cursor away from the main nav, it disappears. I've tried adding display:block and ...

Move a <div> using a handle (without using JQuery)

I devised a plan to create a moveable div with a handle and came up with this code snippet: var mydragg = function() { return { move: function(divid, xpos, ypos) { divid.style.left = xpos + 'px'; divid.style.top = ypos + &apo ...

I encountered an issue while operating my next.js application which utilizes solidity smart contracts. The error message "Cannot read properties of undefined" was displayed during the process

While working on my next.js app and attempting to fetch user data, I encountered the "cannot read properties of undefined" error. https://i.stack.imgur.com/SBPBf.png I also received the following error in the console https://i.stack.imgur.com/JBtbO.png ...

Is it feasible to directly load image objects into jQuery colorbox?

Currently, I am working with the "colorbox" jQuery plugin and I have a specific requirement to dynamically load a set of preloaded image objects into colorbox. The challenge lies in the fact that I have three different image sizes - thumbnail, display, an ...

Obtain unique identifiers for the purpose of sorting the items

While utilizing Nuxt.js, I am fetching random images from URLs structured like this: http://www.randomimage.com?ID=myId To display 2 pictures, I use the following methods: getRandomArbitrary(min, max) { return this.numb = Math.floor(Math.random() * ...

Are there any lodash functions available for removing an array that matches another array from the main array?

I currently have two arrays named available and selected, each containing certain values. I also have another array called finalAvailable where I want to include all items from the available array except those that are already present in the selected array ...

Error being thrown in Express/Mongoose not being caught and handled

While using Postman to test my APIs, I'm encountering an issue with mongoose. It seems that when I use throw new Error() within the userSchema, the error does not get caught by the route.post. How can I ensure that errors thrown using throw new Er ...

Modify components in a web application based on the content of a JavaScript variable

I'm in the process of developing a webapp that needs to interact with an Arduino for its inputs in order to dynamically change the contents of the webpage. Currently, I am experimenting with variables that I have created and assigned random numbers t ...

What is the best way to fully eliminate the Pixi renderer, stage, and all associated assets

I am currently faced with a challenge of mounting and unmounting a Pixi stage using React without relying on react-pixi. Upon re-mounting the component, I encounter the following error: Uncaught Error: Resource with name "cupCake.png" already exists i.ad ...

The issue of passing state in React Router v4 Redirect unresolved

I have a specific private route, /something, that I only want to be accessible when logged in. I've used Redirect with the state parameter set, however, when I try to access it at the destination, location.state is showing as undefined. Here is how I ...

Implementing a button callback function using Aurelia binding

Is there a way to pass an array of custom button objects to a specific element? Here's an example: <my-component header="My Title" buttons.bind="[{icon: 'fa-plus', display: 'New', action: onNew}]"> </my-component> ...

Is there a way to fetch JSON data for a JQUERY datatable?

Is there a way to create JSON data for binding JQUERY data table? In my ASP.net web service (.asmx) code, I have the following snippet: <WebMethod()> _ Public Function Getcdata() As String Dim dt As New DataTable() Using con As New SqlConne ...

Unable to observe modifications in json file within java project (jsp)

I am currently using IntelliJ IDEA to develop a web project with JSP. I retrieve data from a file called "customer.json", and when I click on a button, I update this file in the backend. However, after trying to fetch the updated data again, it still reads ...

Arrangement of multiple boxes in a single row using HTML code

Struggling to solve this supposedly simple problem, I'm reaching out for help. I need assistance in arranging multiple inputs with corresponding labels, all stacked horizontally on a single line as shown in the image. ...

Refresh the Datatable with the click of a button

Despite my efforts and multiple attempts at different solutions, I am unable to get this particular issue resolved. It seems that my lack of experience with javascript/UI is hindering me from achieving the desired outcome. The background function in quest ...

Using ReactJS and Redux to dispatch notifications

I have a query regarding displaying notifications for successful or failed user registration actions. Utilizing Redux, I've implemented the following action page: export function registerUserFail(error){ return { type:REGISTER_USER_FAIL, ...