Once you address a block using jQuery

$(function(){   
        $(window).scroll(function () {
            var scrollVal = $(this).scrollTop();
            var adscrtop =$(".header").offset().top
        // 在 RWD 767以下不作動
            if(window.screen.width>767){
            if(scrollVal> adscrtop){
                $(".banner").css({"position":"fixed","top":"60px"});
            }else{
                $(".banner").css({"position": "static"});
            }
            }
        });
     });
.header{
  max-width:768px;
  margin: 0 auto;
}
.nav{
    position: sticky;
    top:0px;
    width: 100%;
    height: 60px;
    background-color: #f55c47;
    z-index:99;
  }
  .container{
    display: flex;
    justify-content:space-between;
}
.main{
      position: sticky;
      top:60px;
      flex:2;
      background-color: #9fe6a0;
      padding:10px;
}

.banner{
      flex:1;
      width: 200px;
      height: 100px;
      background-color: #564a4a;
}
 .img{
        width: 100%;
      }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
  <div class="nav"></div>
  <div class="container">
    <div class="main">
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quidem quae maiores, quibusdam doloribus eum excepturi ab fugit dolor vel, est molestiae magni tenetur nihil, non architecto aperiam. Consectetur tempore atque doloribus exercitationem veniam. Quibusdam, odio nisi at similique magnam nobis, voluptates non iste laudantium in quo harum soluta voluptatibus vitae labore modi ullam minima enim placeat nesciunt assumenda perspiciatis cumque! A modi delectus assumenda totam, pariatur harum! Odio adipisci maxime expedita beatae hic vero natus necessitatibus! Error earum at natus nemo! Quae aliquid minima quasi exercitationem eum, iure rerum consequatur ipsa. Optio repellendus quibusdam quia incidunt accusamus beatae ex? Accusantium nam, enim esse fugit repellendus dignissimos amet reiciendis nulla porro quo quis facere unde nesciunt culpa molestias sunt a beatae non ad. Voluptatibus...
    </div>
    <div class="banner">
      <img class"photo"src="https://images.unsplash.com/photo-1620706857370-e1b9770e8bb1?ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=800&q=80" alt="">
    </div>
  </div>
</div>

Tonight try using jQuery to fix the brown block under the red block. When scrolling up, only the green block will go up!

The brown area is fixed below the red area, but there are some problems As I scroll up, the brown block goes to the left and goes behind the red block Would you like to help me see which side of my code I have written wrong? Which side did I get wrong? Thank you for watching my question.

PS. My English is not very good, please let me know if there is something wrong with my expression. Thank you. Below is my code`

Answer №1

There seems to be a minor error in this section.

Within the scroll listener function, you have set

"position": "fixed"
. However, it should actually be
"position": "sticky"
.

$(".banner").css({
    "position": "sticky",
    "top": "60px"
});

The use of

"position": "sticky"
will make the element stick at a specified position while scrolling automatically.

To learn more about CSS Positioning, feel free to visit this link.

Please review the updated code snippet

$(function() {
  $(window).scroll(function() {
    var scrollVal = $(this).scrollTop();
    var adscrtop = $(".header").offset().top
    // Will not trigger for RWD under 767
    if (window.screen.width > 767) {
      if (scrollVal > adscrtop) {
        $(".banner").css({
          "position": "sticky",
          "top": "60px"
        });
      } else {
        $(".banner").css({
          "position": "static"
        });
      }
    }
  });
});
.header {
  max-width: 768px;
  margin: 0 auto;
}

.nav {
  position: sticky;
  top: 0px;
  width: 100%;
  height: 60px;
  background-color: #f55c47;
  z-index: 99;
}

.container {
  display: flex;
  justify-content: space-between;
}

.main {
  position: sticky;
  top: 60px;
  flex: 2;
  background-color: #9fe6a0;
  padding: 10px;
}

.banner {
  flex: 1;
  width: 200px;
  height: 100px;
  background-color: #564a4a;
}

.img {
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
  <div class="nav"></div>
  <div class="container">
    <div class="main">
      Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quidem quae maiores, quibusdam doloribus eum excepturi ab fugit dolor vel, est molestiae magni tenetur nihil, non architecto aperiam. Consectetur tempore atque doloribus exercitationem veniam.
      Quibusdam...
      ...eos tempora magni repellendus praesentium? Ad quae vel labore quisquam quidem aliquam, molestias
      dolorum pariatur minus cupiditate odio, velit mollitia, deleniti corrupti eius nam, optio ullam impedit amet ducimus dolores architecto, id, quaerat ratione sed quas. Qui eius labore quia maiores adipisci, quos quod omnis veritatis modi f...</div>
    ...
</div>

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

When a React page is re-rendered using useEffect, it automatically scrolls back to the

Every time I utilize the <Tabs> component, the onChange method triggers the handleTabChange function. This leads to the component being called again and after repainting, the useEffect is triggered causing the page to scroll back to the top. How can ...

React - updates to server values do not display in DOM right away

When I work from the client side, I have a modal in my HomeComponent that allows me to select an element. My goal is to then display that selected element within the same HomeComponent (in the productosEnVenta function). The element chosen in the modal is ...

Analyzing length of strings by dividing content within div tags using their unique ids

Here's my issue: I'm using AJAX to fetch a price, but the source from where it is fetched doesn't add a zero at the end of the price if it ends in zero. For example, if the price is 0.40 cents, it comes back as 0.4. Now, my objective is to t ...

Is it possible to write a text file in UTF-16 using Javascript?

I need to create a UTF-16 text file from a string. For instance: var s = "aosjdfkzlzkdoaslckjznx"; var file = "data:text/plain;base64," + btoa(s); The above code generates a UTF-8 encoding text file. How can I modify it to produce a UTF-16 text file usin ...

Angular 2: The window.crypto.subtle.importKey function functions properly on 'localhost' but encounters issues on an 'ip' address

As a newcomer to Angular 2, I am working on creating a login form that encrypts and sends the user's emailid and password to the server. I have successfully implemented AES-ECB using AES-CTR from the following link: https://github.com/diafygi/webcry ...

"Encountering a puzzling issue with Django Rest Framework where the path setup is functioning for one link but not for

I'm currently attempting to connect to my MySQL database using the Django REST backend. On my frontend, I'm using Vue with Axios. Specifically, I have a junction table called TeacherSubjectJunction, and I want to access it through the following p ...

The functionality of React setState seems to be malfunctioning when activated

Having encountered an unusual issue with react's setState() method. Currently, I am utilizing Azure DevOps extensions components and have a panel with an onClick event that is intended to change the state of IsUserAddedOrUpdated and trigger the addOr ...

Implement using a variable as a key for an object in a reducer function

I am facing an issue with constructing an object. The string, named "SKU" in this scenario is being passed through action as action.name. Although I have all the necessary data in the reducer function, I need to dynamically replace the hardcoded SKU with ...

Hide all elements in jQuery that do not have a class assigned

I've implemented a straightforward jQuery script that toggles the "active" class on an li element when it is clicked: $('li').click(function() { $(this).toggleClass('active'); }); My goal is to hide all other li elements in t ...

String iteration with Stylus

Is there a way to remove the brackets and the quotation marks when putting media queries into an object and looping over them? The code works well, but the stylus is causing the output to have unwanted characters. Here's my code: $maxBreakpoints = { ...

Accessing cell values within a table using JavaScript

I am having some trouble with extracting unique IDs from the input text areas in the first column of an HTML table. These IDs are dynamically assigned using JavaScript. Can someone help me with this issue? Below is the HTML code for my table: <table id ...

Modifying Stroke color in HTML5 Canvas

I am attempting to create a unique visual effect by drawing a circle resembling a clock using canvas 2d context. The idea is to initially draw the circle in black starting at point p1, and then when I complete a full circle tour it should erase as the colo ...

What is the best way to implement an alert box in MVC without triggering a page redirection?

I have a specific requirement to display a custom alert box in order to confirm the user's intention to delete an item. Once the item is deleted, another alert box should appear confirming that the deletion was successful, prompting the user to click ...

Updating a dropdown select in jQuery using AJAX and returning an empty string when it changes

Could someone please help me figure out what I am doing wrong here? When I use console.log(), it is returning an empty string instead of an array. I am trying to update the second select box when the onChange event is triggered on the first select box, bu ...

jQuery News Ticker - Twitter-esque vibes!

I am searching for a news ticker similar to the one found on Twitter that scrolls horizontally. The key features I need: Continuous scrolling - Elements should be removed when they are no longer visible and placed at the end of the list. No Pausing ...

The links located beneath the iframe/span element are unclickable

My latest creation is a static advert ticker positioned at the bottom of the window. It's contained within an <iframe> for easy placement on other websites. I added a <span> around the <iframe> to keep it fixed at the bottom of the s ...

Limit access to all pages, with the exception of the home page, in Django

During the development of my Django application, I organized the functionality into sub-functions and implemented them in individual apps. To display results on the homepage instead of redirecting to a sub-function app page, I utilized ajax and JavaScript. ...

Implementing file uploads with Bootstrap, jQuery, and Laravel

Looking to incorporate the blueimp jquery file upload feature into my Laravel app. Check it out here: https://github.com/blueimp/jQuery-File-Upload The form is set up and working properly with the plugin, but facing issues with creating server-side script ...

Tips for resizing an image to fit within a col-sm-12 column in Bootstrap

I have a dilemma with two columns - I want to place my image in the first column so that the second column can move down. see image here Here is my HTML code: <div class="container-fluid"> <div class="row"> ...

What is the best way to align this content in a specific area?

How can I center the content in each section of my webpage? Here is an image for reference: https://i.stack.imgur.com/PHEXb.png I want Section 1 and Section 2 to be 100vh with the content centered on the page. .content { height: 100vh; } <!do ...