Experiencing a problem with JQuery Offset when a fixed position is applied to a

My website has a page layout and style similar to the example provided in this JsFiddle.

When I use JQuery to click on a button, the content is displayed correctly as shown below:

https://i.sstatic.net/V89qa.jpg

However, if I scroll down the page first and then click the button, the content does not display properly as seen here:

https://i.sstatic.net/jJvHN.jpg

Could you please provide guidance on how to handle this situation?

I have implemented the following jQuery code for this purpose. However, it appears that either the offset or position properties are not functioning properly:

$('#btn').click(function(){
        var t = $(this).offset();
        console.log(t);
        $('.control-container').css('top', t.top + 20 + 'px');
        $('.control-container').css('display', 'block');
    });

    $(document).on('scroll', function(){
        $('.control-container').css('display', 'none');
    });
    

Answer №1

Instead of relying on using offset for this task, consider a different approach. If you want to maintain the CSS property as position:fixed, it may be necessary to change it dynamically in javascript to static.

The solution you seek could be as straightforward as utilizing display:table ...

$('#btn').click(function(){
  $('.control-container').css({'display': 'table','position': 'static'});
});

$(document).on('scroll', function(){
   $('.control-container').css({'display': 'none','position': 'fixed'});
});

Feel free to view this JSFiddle for reference.


If your requirement truly demands using position:fixed based on the position of a button, explore this alternative method:

$('#btn').click(function(){
    var button_fixed_position = $('#btn').get(0).getBoundingClientRect();
  $('.control-container').css({'display': 'block','left' : button_fixed_position.left, 'top' : button_fixed_position.bottom});
});

$(document).on('scroll', function(){
   $('.control-container').css({'display': 'none'});
});

Take a look at the second JSFiddle example here.

Answer №2

There is no requirement to explicitly state the position property in this context.

Additionally, remove the closing a tag and replace it with </button>

The current container is taking up the entire width, but it can also be customized.

$('#btn').click(function() {
  var t = $(this).offset();
  console.log(t);
  $('.control-container').css('top', t.top + 30 + 'px');
  $('.control-container').css('display', 'block');
});

$(document).on('scroll', function() {
  $('.control-container').css('display', 'none');
});
.header {
  background-color: maroon;
  color: #fafafa;
  height: 60px;
  position: fixed;
  width: 100%;
  text-align: center;
  line-height: 19px;
  font-size: 25px;
  z-index: 2;
  padding: 0px;
  margin: 0px;
  top: 0;
}

.content {
  background-color: #fff;
  border: 1px solid #999;
  padding: 5px;
  height: 100%;
  width: 100%;
  position: absolute;
  z-index: 1;
  top: 60px;
}

.control-container {
  width: auto;
  background-color: red;
  #position: fixed;
  color: #fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="header">
    Header
  </div>
  <div style="clear:both">

  </div>
  <div class="content">
    <br/>
    <br/>
    <br/>
    <br/>
    <br/>
    <button id="btn">Click Me</button>
    <div class="control-container" style="display:none;">
      Keep me exactly underneath 'Click Me' when Page is scrolled.
    </div>
  </div>
</div>

Answer №3

The CSS fixed positioning property places an element in relation to the viewport's or body's dimensions.

If you can make changes to the CSS code, simply delete the line position: fixed; from the .control-container section.

If you do not have permission to modify the CSS directly, you can use a script to add the position: static !important rule to the .control-container.

$('.control-container').css('cssText', 'position: static !important');

See the updated version on JSFiddle

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

Enhancing User Experience with JQuery Autocomplete in Symfony

I am attempting to incorporate an autocompletion feature into my Symfony app using AJAX. When I access the route to retrieve the list of users, it works perfectly: ["user1","user2","user3","user4","user5"] However, it does not populate the #form_comname ...

Something went wrong with the API: an error occurred where headers were sent to the client before they could be set

Recently, I've encountered an issue where users are facing errors during registration or login. The error message pops up occasionally and here is a screenshot of it: https://i.sstatic.net/zum1u.png Below is the code snippet that I'm using: htt ...

Tips for making a Scroll Button

I am in the process of designing a horizontal website and I would like to incorporate two buttons, one on the left and one on the right, that allow users to scroll to the left and right, respectively. You can check out the site I am currently working on h ...

jQuery - Incorrect folder path for image replacement

I have a specific request to change the image paths in multiple .html pages, redirecting them from the default folder to another folder. After implementing code from an external javascript file successfully, I am encountering an error where the HTML sou ...

Update an existing JSON document

Looking for a solution to update the json file while retaining specific strings and values? const fs = require('fs'); var logPath = 'log.json' var logRead = fs.readFileSync(logPath) var logFile = JSON.parse(logRead) LogChannel = &apo ...

Having difficulty utilizing the express.session module in conjunction with HTTPS

I need to implement authentication and session creation on a HTTPS static website using expressjs. Here is the code snippet: app.js: // Set up the https server var express = require('express'); var https = require('https'); var http ...

What is the method for including word boundaries in a regex constructor?

export enum TOKENS { CLASS = 1, METHOD, FUNCTION, CONSTRUCTOR, INT, BOOLEAN, CHAR, VOID, VAR, STATIC, FIELD, LET, DO, IF, ELSE, WHILE, RETURN, TRUE, FALSE, NULL, THIS } setTokenPatterns() { let tokenString: s ...

Tic Tac Toe is not functioning properly

Hey there! Can someone please help me figure out what's going on? I'm trying to create a Tic Tac Toe game, but instead of using "O" and "X" to mark the fields, I want to use different colors. Specifically, one player should be able to mark with b ...

place an image next to a div element

Currently, I have a table-like structure with two columns that I am struggling to make mobile responsive. Take a look at the code snippet below: setTimeout(function() { odometer.innerHTML = '1925' }) .fiftyFiftySection { back ...

The variables $invalid and $valid in my AngularJS form have not been assigned any values

I came across a post on StackOverflow discussing the issue of both "myForm.$valid" and "myForm.$invalid" being undefined on an Angular form. However, my problem is slightly different. I have defined a form like this: <form name="EntityForm" role="form ...

Tips on ensuring the first column of an HTML table remains fixed in responsive design

I am trying to create a responsive HTML table where the first column remains fixed. I have a select box on my PHP page and I am using AJAX to display data from a database in the HTML table. However, when selecting a value in the select box in a responsiv ...

Utilizing a Dependency Injection container effectively

I am venturing into the world of creating a Node.js backend for the first time after previously working with ASP.NET Core. I am interested in utilizing a DI Container and incorporating controllers into my project. In ASP.NET Core, a new instance of the c ...

Next.js horizontal scrollbar appearing unexpectedly

As I work on my Next.js project, I've noticed an issue with unwanted horizontal scrollbars appearing on every subpage. These scrollbars allow scrolling about 30px horizontally, but only appear when the content extends beyond the viewport. I attempted ...

Guide to setting up collapsible sections within a parent collapsible

I came across this animated collapsible code that I'm using: https://www.w3schools.com/howto/howto_js_collapsible.asp Here is the HTML: <button type="button" class="collapsible">Open Collapsible</button> <div class="content"> &l ...

Searching for partial nodes

I came across a helpful tutorial that explains how to perform a partial search. My goal is to have it so that when someone enters the text geor, it can locate a user named george. db.stores.find({storeName : {$regex : /Geor/}}).pretty() However, I am str ...

Diverse behaviors exhibited by an array of promises

I've developed a function that generates an array of promises: async addDefect(payload) { this.newDefect.setNote(payload.note); this.newDefect.setPriority(payload.priority); const name = await this.storage.get(StorageKeys.NAME); ...

Why is it that this specific ASP.NET + jQuery + JavaScript custom MVC setup isn't displaying any content?

After attempting to incorporate this JavaScript MVC example from into an ASP.NET page, I am facing issues as a beginner with jQuery. Nothing seems to show up on the page, and I'm unsure why. Update: I have included the missing HTML listbox, but now ...

Why am I unable to make a selection in the dropdown menu?

Can anyone help me figure out why I am unable to select an option from the material ui library and display it in the state? Has anyone else encountered this issue? For a detailed code example, check here import React from "react"; import ReactDOM from " ...

Enclosing Material UI's DataGrid GridActionsCellItem within a custom wrapper component triggers a visual glitch if showInMenu is enabled

Here is how my MUI DataGrid columns are structured: const columns = [ { field: "name", type: "string" }, { field: "actions", type: "actions", width: 80, getActions: (params) => [ ...

Spring Boot - delivering unadulterated HTML and static materials

After spending countless hours working on this, I am still unable to figure out how to serve pure .html pages. The project I am referring to can be found at: https://github.com/robson021/Invoice-Writer Although the Thymeleaf engine works perfectly, I enco ...