Tips for manipulating fixed elements while navigating through the window's content

I am currently working with Materialize CSS (link) and I'm trying to figure out how to move select content while scrolling the page or when the window is scrolling. However, the example code I've implemented doesn't seem to be working. Is there any way to achieve this?

You can find the code I'm using here: http://jsfiddle.net/uj6p7o3a/

$(document).ready(function(){
    $('select').formSelect();
});


 $(document).on('click','.select-wrapper .select-dropdown.dropdown-trigger',function(){
     var this_c = this.getAttribute('data-target');
     var lastScrollTop = 0;
     var count_scroll = 1;
     $(window).scroll(function (event) {
        var pos_s_c = parseInt($('#'+this_c).css("top").replace('px',''));
        var pos_s = $('select').position();
        var st = $(this).scrollTop();
        if (st > lastScrollTop){
       count_scroll++;
       st++;
      } else if (st < lastScrollTop){
       count_scroll--;
       st--;
       }
      lastScrollTop = st;
      var scroll_data = count_scroll;

      $('.select-wrapper .dropdown-content.select-dropdown').css({'argin-top':(lastScrollTop-st-scroll_data)-pos_s.top+pos_s_c+'px'});

    });   

   });

Answer №1

A mistake was found in your script file.

$('.select-wrapper .dropdown-content.select-dropdown').css({'margin-top':(lastScrollTop-st-scroll_data)-pos_s.top+pos_s_c+'px'});

The error was using argin-top instead of margin-top

See the corrected code snippet below. The content now moves properly when scrolling.

$(document).ready(function() {
  $('select').formSelect();
});


$(document).on('click', '.select-wrapper .select-dropdown.dropdown-trigger', function() {
  var this_c = this.getAttribute('data-target');
  var lastScrollTop = 0;
  var count_scroll = 1;
  $(window).scroll(function(event) {
    var pos_s_c = parseInt($('#' + this_c).css("top").replace('px', ''));
    var pos_s = $('select').position();
    var st = $(this).scrollTop();
    if (st > lastScrollTop) {
      count_scroll++;
      st++;
    } else if (st < lastScrollTop) {
      count_scroll--;
      st--;
    }
    lastScrollTop = st;
    var scroll_data = count_scroll;

    $('.select-wrapper .dropdown-content.select-dropdown').css({
      'margin-top': (lastScrollTop - st - scroll_data) - pos_s.top + pos_s_c + 'px'
    });

  });

});
#div {
  height: 2000px;
  background-color: #fff;
  padding: 20px
}

.select-wrapper .dropdown-content.select-dropdown {
  position: fixed;
}
<html>

<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
  <link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css" rel="stylesheet" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
</head>

<body>
  <div id="div" class="col s10">
    Contrarytopopularbelief,LoremIpsumisnotsimplyrandomtext.It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the
    more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum"
    (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.
    The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions
    from the 1914 translation by H. Rackham. The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact
    original form, accompanied by English versions from the 1914 translation by H. Rackham.
    <select>
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
      <option value="8">8</option>
      <option value="9">9</option>
      <option value="10" selected="selected">10</option>
    </select>
  </div>
</body>

</html>

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

Ensure that a string contains only one instance of a specific substring

I need a function that removes all instances of a specific substring from a string, except for the first one. For example: function keepFirst(str, substr) { ... } keepFirst("This $ is some text $.", "$"); The expected result should be: This $ is some tex ...

Tips for ensuring math formulas display correctly in CKEditor

I'm currently struggling to properly display the correct format of a math formula in ckeditor. I have made numerous attempts to find a solution, but so far, none have been successful. Here is an excerpt of my code: <html> <head> <scr ...

Why is the Material Ui code functioning flawlessly in Codepen but not in VSCODE?

In my ReactJS project, I am using Material-UI to create "Material Tabs". The code works fine in SANDBOX but not in my VS CODE. What could be the issue? I have checked that Node is installed and all dependencies versions from NPM are up to date. I also tri ...

Issue with displaying ChartJS on Django HTML page

I am attempting to create a horizontal bar chart in HTML, but unfortunately, it is not displaying correctly. I have sent 2 variables from views.py, which are {{top5StockCode}} and {{top5TotalSales}}. The values of {{top5StockCode}} that were sent from vi ...

What steps should I take to eliminate the white gap between the paragraph and the footer on my webpage?

If you're new to html and css, feel free to check out the url [file:///Users/CatherineDu/百度云同步盘/practice/about.html]. I'm currently working on building a simple website and facing an issue - there are unwanted white spaces between the ...

Choose a particular text node from the element that has been selected

Can anyone provide guidance on how to extract the text "Items Description" from the following HTML snippet using jQuery? <div class="items"> "Items Description" <ul> <li>1. One</li> <li>2. Two</li&g ...

Tap and hold with Zepto

I've been on the hunt for a Zepto plugin that can handle a longClick event. While Zepto already supports longTap, which is perfect for mobile devices, I need something specifically for desktop browsers when a user clicks and holds. It's also impo ...

"Send the response in ExpressJS before making a request to loop through the

I am currently working with a postgres database that contains records with a column format in JSON, which refers to other similar records. The challenge I am facing is retrieving linked records through asynchronous methods due to the nested structure and ...

A cautionary alert is triggered by vsCode when analyzing seemingly correct code sourced from vue.js documentation

While using Visual Studio Code version 1.13.1V and referring to the vue.js guide on lazy loading, I encountered an issue when writing the following code snippet: import Vue from 'vue' import Router from 'vue-router' const Health = () = ...

Tips on fetching and displaying information by utilizing the .click(function()

I have a single textfield and a show button. After entering some text into the textfield and clicking the button, I want to display all information from the database. What code do I need to achieve this? $(document).ready(function(){ var oTable; $("#show ...

JavaScript constructor functions may trigger ReSharper warnings for naming convention

When it comes to JavaScript coding, I personally prefer using PascalCase for constructor functions and camelCase for other functions. It seems like my ReSharper settings are aligned with this convention. However, when I write code like the following: func ...

Tips for locating and substituting a string in Javascript

Is there a way to locate a particular word within a string and substitute it using JavaScript? For instance Here is a lengthy sentence I want to locate the word "sentence" and modify it to "phrase", resulting in: Here is a lengthy phrase ...

What is the best way to handle a JavaScript POST request in an ASP.NET WebForm?

Although it may seem like a basic question, I am a bit rusty when it comes to webforms. This is my first time using Stripe.js and I would like to utilize it alongside stripe.net for client-side processing. Below is the client code: <%@ Page Title="" La ...

Using jQuery to create an interactive form with PHP integration

I've set up a PHP form to post to a database successfully. However, after including it in a jQuery web page, the form is no longer posting to the database. Check out the code for both the webpage and the PHP file below. Interestingly, the form works f ...

What is the method for setting and comparing collectionsjs equality?

I'm interested in utilizing the data structure. Within the factory method, you have the opportunity to specify equals and compare parameters: SortedMap(entries, equals, compare). Can anyone provide insight into what the expected formats for these pa ...

"Enhance your website with a backspace button using jquery - here's

Recently, I delved into the world of jQuery and decided to test my skills by creating a jQuery calculator. Everything worked perfectly except for the backspace button. This is what I tried: if (value === backspace) { $(input).val($(input).val().substring ...

Utilizing Node, ObjectionJS, and Knex, we can establish a one-to-many relationship and retrieve the first associated row from the many

To simplify, I use two tables for a chatbox: Conversation and Message Conversations ID Status 1 open 2 open Messages Conversation ID Text Date 1 'ffff' (random date) 1 'asdf' (random date) 1 '3123123123&ap ...

What is the best way to name a force-directed Graph using d3?

I'm struggling to label the nodes in my force-directed graph created with d3.js. Despite trying various solutions from StackOverflow and online tutorials, I believe my issues stem from a lack of fundamental understanding of JavaScript. I've expe ...

Run a series of functions with arguments to be executed sequentially upon the successful completion of an ajax request

I am currently working on implementing a couple of jQuery functions to assist me in testing some api endpoints that I am developing in php. While I have limited experience with Javascript and jQuery, I am struggling to figure out what additional knowledge ...

Annoying AngularJS Scrolling Problem

I am facing an issue with a Container that loads multiple views <md-content flex id="content"> <div ng-view></div> </md-content> One of the loaded views has the following structure: <div layout="column" id="selection-whit ...