Fixed Element Transitioning from Starting Position on Scroll

Check out the JSFiddle example here

I'm currently working on a website utilizing Bootstrap 3. I have an image that sticks to the page when scrolling by changing its position to fixed. While this functionality works, the image tends to shift slightly once it becomes fixed. I believe this issue is related to margins (I've experimented with pixel values and found that using percentages helps solve the problem, especially for responsive design). Ideally, I want the image to remain in its initial position without any shifting when it becomes fixed.

Here's the code snippet:

HTML

<div class="row">
            <div class="col-sm-5">
                <h2 class="white">Some Text</h2>
            </div>
            <div class="col-sm-7">
                <img class="img-responsive screen-phone" src="img/phone.png">
            </div>
</div><!--END ROW-->

CSS

.screen-phone{
    max-width:300px;
    margin-top:25px;
    margin-left:25%;
    z-index:999;
}

Javascript

$(document).ready(function(){

$(window).scroll(function () {
    if ($(this).scrollTop()>1120){
        $('.screen-phone').css('position','fixed').css('top','0');
    }else{$('.screen-phone').css('position','static');
    };
 });
});

Answer №1

Bootstrap can be quite finicky when it comes to messing with its margins. It follows a specific gutter system, and your margin adjustments seem a bit wild:P

If you remove those margin declarations, everything should function as desired, right?

Answer №2

After some experimentation, I have found the solution to this issue. To adjust the positioning of the image within the containing DIV, you need to create a separate class for the DIV and specify the left value in CSS. Remove the margin-left property from the image itself. If you are using Bootstrap, you may encounter margin conflicts, so you can create additional classes to address this problem. Here is an example:

.screen-phone{
 max-width:300px;
 margin-top:25px;
 /*Removed margin-left:25%*/
 z-index:999;

}

.sticker{
 left:25%
}

.zero-row{
 margin:0;
}

.no-margin{
 width:0;
}

HTML:

<div class="row zero-row">
        <div class="col-sm-5">
            <h2 class="white">Some Text</h2>
        </div>
        <div class="col-sm-7 no-margin sticker">
            <img class="img-responsive screen-phone" src="img/phone.png">
        </div>
</div><!--END ROW-->

Updated Fidde: https://jsfiddle.net/1chkghhq/1/

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

I keep encountering an issue with npm where it is unable to identify the executable to run whenever I launch VS Code and attempt to use Cypress

Whenever I open Visual Studio Code and try to run 'npx open cypress', I keep encountering this message in my terminal: npm ERR! could not determine executable to run Oddly enough, running 'npx cypress -v' provides version details, so ...

The hyperlink activation event is malfunctioning

There seems to be an issue with the "Goods" link not working after clicking on "Shops." <div class="i_find"> <div class="replaced_link">Goods</div> <div class="link_container"><a href="#" class="a_shops">Shops</a&g ...

What is the best way to link the width and height of a div with form fields?

I need to implement a feature where I can create multiple div elements that are draggable and resizable, and have their properties like width, height, etc. linked to corresponding objects in an array. For example, if I create six divs, there should be six ...

Attempting to eliminate the vertical scroll on my page that matches the height of the navigation bar

I am struggling with the alignment of a login page form that needs to be centered both horizontally and vertically, while allowing for slight scrolling down to accommodate the navigation bar height. I have attempted to adjust the classes and style height ...

What is the best way to retrieve the total number of nested objects within an object?

I'm trying to figure out how to get the number of nested objects in the object a. a = { firstNested: { name: 'George' } secondNested: { name: 'James' } } I thought about using .length, which is typ ...

Verify whether the input includes a specific value or a different one

Can someone help me with a simple task of checking if a textarea contains the value "12" OR "34"? I have tried the code below but it doesn't seem to work. Any suggestions? function check() { if (V1.value == ('12' || '34')) { ...

Learn the steps to merging all yarn files using gulp

After successfully setting up yarn and getting the hang of how it functions, I've also started to grasp the basics of gulp. I was relieved to find out how to install version 4 and avoid those deprecated errors that came with the default version. As o ...

What is the best way to enlarge text size with jquery?

I am attempting to: $('a[data-text="size-bigger"]').click(function () { a=$('span'); b=$('span').css('font-size'); a.css('font-size', b+1); } ); Initially, I ha ...

Laravel ajax crud functionality hindered by malfunctioning back button

Attempting to navigate back to the previous page is not functioning properly. Instead, I am encountering an error message that states: "SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'name' cannot be null (Connection: mysql, SQ ...

Performing AJAX requests within loops using Javascript can be a powerful tool

Utilizing jQuery to make an AJAX request and fetching data from a server. The retrieved data is then added to an element. The goal is for this process to occur 5 times, but it seems to happen randomly either 3, 4, or 5 times. Occasionally, the loop skips ...

What are the steps to create a hovering dropdown menu that changes the background window to transparent when hovered over?

Is there a way to create a dropdown menu that changes the background window to transparent when hovered over? Here is an example of what I am looking for: https://i.sstatic.net/FplLm.png The dropdown menu should look like this when hovered over: https: ...

Card with multiple links and tab-stopping

I'm trying to figure out the best way to navigate through a series of project information cards that include links to a live demo and Github Repo without overwhelming visually impaired users with excessive tab stops. I want the navigation to be seamle ...

Ways to apply distinct styles to various ids and common classes

When dealing with multiple IDs such as id1, id2, and id3 that share common classes like .selectize-input and .select-dropdown, it can become cumbersome to set styles individually for each ID. Instead of writing: #id1 .selectize-input, #id2 .selectize-inp ...

Choose the jQuery selector that can target all types of text input fields

Is there a simple method to target all various types of text input fields? For example, <input type= text or email or url or number /> I am not concerned with password fields or textareas. For instance, I currently have this script that selects al ...

Guide to transferring an ID received via JSON through Ajax to a PHP POST request

I am struggling with an AJAX function that displays an HTML table. The issue I'm facing is that I have a method in viewmap.php that shows the location based on the ID you click on the table. However, to make this work, I need to send the UID to viewma ...

Unable to alter the background color in a table row when a condition is verified

Within my 'work' array that is generated from an Excel file, I have values for employee_id (referred to as id), projects, and hours. Additionally, I have another array called 'employees' which contains all the employees in my database. ...

Using JavaScript to generate a <style> element and accessing the cssRules

After spending countless hours trying to solve this problem, I'm hoping that my question isn't too foolish. This is a continuation of a previous question about creating a style tag with JavaScript on Stack Overflow. The solutions provided by Tom ...

Styling Angular2 Material Dialog: the perfect fit

The Angular2 material team recently unveiled the MDDialog module at https://github.com/angular/material2/blob/master/src/lib/dialog/README.md I am interested in customizing the appearance of Angular2 material's dialog. Specifically, I want to adjust ...

Using jQuery to retrieve a List<> from an ASP.NET WebService

This is my WebService Method: [WebMethod] [ScriptMethod(ResponseFormat = ResponseFormat.Json)] public string retrieveImages() { DBservices DBS = new DBservices(); List<string> ImageUrls = new List<string>(); try { DBS.g ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...