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

Choosing an option will display a specific div while hiding another using JQuery

My question involves a Select Option <select class="input_select" name="customer_type" id="central_company"> <option value="standard">Standard</option> <option value="central">Central Station</option> </select> ...

Unable to establish a connection with the endpoint

I'm encountering an issue while trying to connect to the endpoint on the server. Below is the code snippet: Register.jsx function Register() { const [registerUser, setRegisterUser] = useState({ username: "", email: "", password: "", ...

Leverage JavaScript to retrieve the formatting of an element from an external CSS stylesheet

Check out this HTML snippet: <html> <head> <link rel="stylesheet" type="text/css" media="all" href="style.css"> </head> <body> <div id="test">Testing</div> <script> ...

Ways to verify the presence of a key within an array of objects

I'm on a mission to determine whether a specified key exists in an array of objects. If the key value is present, I need to return true; otherwise, false. I enter the key into a text box as input and then attempt to check if it exists in the array of ...

Returning Props in Dynamic Components with Vue 3

Exploring the capabilities of Vue3's Dynamic Component <component>, I am currently working with this setup: Component 1: <template> <div> <h1> Name Input: </h2> <Input :model="props.name" /> ...

Is there a way to determine if a value exists within an array of objects?

Is it possible to determine if a specific value is present in an array of objects? I've tried a method, but it always returns false. What would be the most effective way to solve this issue? My approach: var dog_database = [ {"dog_name": "Joey" ...

Experiencing erratic outcomes with window.innerWidth in Mobile Safari

I am currently using JavaScript to determine the width of the browser: $(document).ready(function(){ var width = window.innerWidth; }); However, it seems that this method is producing inconsistent results. To showcase the issue, I have created a fun ...

What is the best way to utilize jQuery for selecting all child elements excluding a specified filter element?

I have a main div and I want to select all elements within the main div, excluding the start div and its children (as shown in the code with pink blocks). The .filter() method displays all children elements of the start div. Using .not() will show the st ...

What steps should I take to create a collapsible Bootstrap navbar?

I'm attempting to recreate the scrolling functionality seen here: It seems like they might be using a customized Bootstrap Navbar, so I've taken one from here: and tailored it to my needs. How can I achieve the effect where the navigation bar ...

What is the best way to retrieve an object instead of an array?

When attempting to retrieve a JSON Object, I unexpectedly received an array instead. My query is based on the primary key, so I anticipate only one result. This is my current method : router.get("/student_info/:id", (req, res, next) => { connecti ...

Ways to identify when a chemical reaction has taken place?

I have developed a Discord bot that interacts with an API related to a game server panel. The bot has tasks to start, restart, stop, and kill the server. I want to enable end users to trigger these tasks by reacting to a specific embed posted by the bot. ...

"Encountered an Unspecified Variable Error in executing document

Every time I open my Chrome console, it keeps showing an error message saying "toggleOnlyRelatedPosts is not defined". The script I'm working on doesn't seem to be functioning properly. I've added so many variables that I now feel lost and o ...

[.TextureUnitWarning] ALERT: Unit 1 is lacking a texture binding for rendering test.html:1

I've been attempting to incorporate texture into my project. var bumptexture = THREE.ImageUtils.loadTexture('grid.jpg'); var normaltexture = THREE.ImageUtils.loadTexture("normal.jpg"); var diffusetexture = THREE.ImageUtils.loadTexture ...

Is there a way to check if a file name input is valid using regular expressions?

I'm having trouble getting my code below to work properly. I'm not sure if the problem lies in the match function syntax or the regex itself. Any assistance would be greatly appreciated. $scope.fileSelected = function (file) { var valid = "/ ...

Error encountered in loop for concatenating html elements: identifier unexpectedly found (jquery + html + php)

I am attempting to concatenate HTML inside a variable within a loop and then return it populated. However, I am encountering an error: Uncaught SyntaxError: Unexpected token += in my code. <a style="cursor: pointer" id="addmore">More Entree ?</ ...

Troubleshoot: Node Express experiencing issues reconnecting to ajax

Here is the initial question that needs to be addressed. I am currently developing an API that links a front-end application (built using node, express, and Ajax) with a Python swagger API. The issue I am facing is that although I can successfully send da ...

Edit images prior to uploading to the server by adjusting the size or dimensions as raw binary data (format should be either png or jpeg

In my quest to crop images in the browser and upload them directly to a server as raw image binary data (either in "image/jpeg" or "image/png" format), I have tried various client-side methods for cropping and uploading. These methods typically utilize the ...

Winning opportunities created by using credits in the slot machine

**Greetings, I have created a slot machine using JavaScript, but I am looking to enhance the player's chances based on their credits. Can anyone guide me on how to achieve this? Essentially, I want the player's odds to increase proportionally wit ...

HTML and Python synchronize perfectly when handling date formatting

Here is a code snippet I am working with: {% for x in fixtures %} <TR style="display:block" onclick="team_visibility('match{{ forloop.counter }}');"> <TD> {{ x.fixturedate }}</TD> ...

The Javascript document refuses to load

I am currently working on a website with the main file named index.html: <!DOCTYPE html> <html lang="en" xmlns="http://www.w3.org/1999/xhtml"> <head> <meta charset="utf-8" /> <title>Title</title> </head> ...