Challenges arise when trying to maintain a div aligned to the far right of the browser window as the dimensions of the browser change, especially after applying an

I have a main container div that holds two smaller divs side by side. When one of these smaller divs is clicked, it moves to the far left or right side of the browser window depending on which one was clicked. This functionality works perfectly as intended.

However, I encounter an issue when I attempt to resize the browser window manually by dragging the bottom right corner to adjust its dimensions. The div that moved to the far right initially does not follow along with the resizing and ends up falling out of view. It is crucial for me that this div remains anchored to the far right no matter how the browser window changes in size.

Even though I have set the CSS property of the div to 'right: 0', it seems that the JavaScript animation effect is not taking this into account and keeps the div in its original position on the far right based on the initial dimensions of the browser window.

Below is a simplified version of my current code structure:

HTML:

<span id='one'>&nbsp;    
    <span id='two'>&nbsp;</span>
    <span id='three'>&nbsp;</span>
</span>

CSS:

#one {
    height:100px;
    width:210px;
    background-color:red;
    position:absolute;
    left:0;
}
#two {
    height:100px;
    width:100px;
    background-color:blue;
    float:left;
}
#three {
    height:100px;
    width:100px;
    background-color:green;
    float:right;
}

JavaScript:

$(document).ready(function(){
    $('#two').click(function(){
        window_width = $(document).width();
        element_width = $('#one').width();
        edge = window_width - element_width;
        $('#one').animate({right:edge, left:0}, 100).delay(0);
        console.log($('#one').css('left'));   
    });
});
$(document).ready(function(){
    $('#three').click(function(){
        window_width = $(document).width();
        element_width = $('#one').width();
        edge = window_width - element_width;
        $('#one').animate({left:edge, right:0}, 100).delay(0);
        console.log($('#one').css('left'));
    });
    console.log($('#one').css('left'));
});

I would greatly appreciate any assistance with this issue as I've been searching through various resources without finding a suitable solution. Thank you in advance to anyone who can help.

Answer №1

To ensure your web page looks consistent across various screen resolutions, consider setting sizes in percentages within your CSS file. This way, elements will resize accordingly when viewed on monitors with lower resolutions. Media queries can also be helpful for maintaining a uniform appearance across different devices.

Answer №2

One approach could be to create a variable that stores the position of the divs and then utilize JQuery's .resize() event handler. Here is an example:

var isLeft = true;

$(window).resize(function() {
    if (!isLeft) {
        window_width = $(document).width();
        element_width = $('#one').width();
        edge = window_width - element_width;
        $('#one').animate({right:edge, left:0}, 100).delay(0);
        console.log($('#one').css('left'));
    }
});

A similar process can be applied to the other div. You can toggle the variables isLeft or isRight within the click events.

Answer №3

VIEW DEMO

var _pos;

$('#two').click(function () {
    window_width = $(window).width();
    element_width = $('#one').width();
    edge = window_width - element_width;
    $('#one').animate({
        right: edge,
        left: 0
    }, 100).delay(0);
    console.log($('#one').css('left'));
    _pos="left";
});

$('#three').click(function () {
    window_width = $(window).width();
    element_width = $('#one').width();
    edge = window_width - element_width;
    $('#one').animate({
        left: (edge > window_width)?window_width:edge,
        right: 0
    }, 100).delay(0);
    console.log($('#one').css('left'));
    _pos="right"
});

$(window).resize(function(){
   if (_pos=="left") $("#two").click();
   if (_pos=="right") $('#three').click();
});

An essential adjustment is replacing $(document).width() with $(window).width() to ensure the div adapts when the screen size decreases, not just when it increases.

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

Utilizing GroupBy in RxJs for an Observable of Objects数组

I am working with entries of type Observable<Event[]>, and they are structured as follows: [{ "_id": 1, "_title": "Test Event 1", "_startDate": "2019-05-29T07:20:00.000Z", "_endDate": "2019-05-29T08:00:00.000Z", "_isAllDay": false }, ...

How can you make a Unity Web GL html container adjust its width to match the size of the browser window?

Looking to create a Unity WebGL build that allows for specifying width and height in the HTML template. How can I dynamically set the width of div id="gameContainer" based on the browser window width to ensure it always fills the space? .webgl-content ...

Guide on incorporating an HTML element within a binding in Nuxt or Vue

I'm struggling with adding an HTML element <br /> inside a data bind. I want to modify the text "I like playing games" to include a line break, making it read as "I like playing <br /> games", but I can't seem to get it right within t ...

Using jQuery to enhance an HTML form

Currently, I am in the process of creating an HTML form for user sign up which includes typical fields such as username, password, and email. My intention is to transfer the entire HTML form to another .php file using the POST method. The second .php file ...

Problem with the transparency of CSS, div, and asp:Image

I am facing an issue with a div that has its opacity set to 60. Within this div, there is an asp:Image element. It seems like the opacity of the div is also affecting the image inside it. I attempted to create a separate class for the image and adjust th ...

Arrange the array based on the key values

I am currently working with a function that sorts by name and an array containing value/key pairs. I am trying to figure out how I can dynamically pass the key on which the sort is being performed, so that I can call the same function each time with diffe ...

Exploring the asp.net MVC framework with the integration of HTML5 date input

Currently, I am working on an ASP.NET MVC project using Visual Studio 2013. One of the issues I am encountering is related to a date input field. When I click on the field and focus on it, the automatic HTML5 datepicker does not appear. If I enter the da ...

The extent of utilizing the click handler in ECMA script 6

In ES6 arrow functions, the scope of this becomes available. However, there are instances where I cannot access this in an arrow function while it works with a normal anonymous function. For example: Sample 1 $(document).ready(function() { $(' ...

What is causing the links at the bottom of the page to not function properly?

<div class="col-lg-4 col-sm-12 footer-social"> <a href="https://www.facebook.com/unique.page123"><i class="fa fa-facebook"></i></a> <a href="https://twitter.com/UniquePage456"><i class="fa fa-twitter"></ ...

Create an array containing key-value pairs where the values are objects

I've been struggling to create a specific data structure in Javascript and I could really use some guidance: [arrayValue: {objectKey: objectValue}, arrayValue2: {objectKey: objectValue}] Here's what I've attempted so far: var arr = []; var ...

The Ul Li tag cannot be aligned to the right

Having trouble left aligning the logo and right aligning the ul li tag? Despite using float, the code doesn't seem to work as expected. Take a look at the issue: It's puzzling because I've used the same code elsewhere and it worked perfectl ...

What is the best way to set values for columns in jqGrid?

I am currently using jqGrid in conjunction with CodeIgniter 2.1.0. I am facing a challenge regarding how to set a value for a specific column based on a particular event. For example, when entering quantity and rate values in the respective columns, I wan ...

Video solution that works seamlessly across different web browsers

Our organization is in the process of introducing a significant amount of online tutorial and training videos that will be embedded directly on our website. We are looking for a straightforward solution that is compatible across different browsers to ensur ...

AngularJS Expression Manipulation

I am looking to implement a functionality similar to the one below: HTML <mydir> {{config = {type: 'X', options: 'y'}} </mydir> <mydir> {{config = {type: 'a', options: 'b'}} </mydir> JS Dir ...

Learn how to incorporate a newly created page URL into a customized version of django-oscar

Just starting out with django-oscar and trying to set up a new view on the page. I've successfully created two pages using django-oscar dashboard, https://ibb.co/cM9r0v and added new buttons in the templates: Lib/site-packages/oscar/templates/osca ...

MUI: Autocomplete cannot accept the provided value as it is invalid. There are no matching options for the input `""`

https://i.stack.imgur.com/KoQxk.png Whenever I input a value in the autocomplete component, an unresolved warning pops up... Here's how my input setup looks: <Autocomplete id="cboAdresse" sx={{ width: 100 + " ...

Encountering a problem with AngularJS

My AngularJS test is running fine, but I keep getting this error in the console!! Error: [filter:notarray] Expected array but received: {"data":[{"brand":"Samsung A7 Prime","color":"Gold","price":24500,"img":"img/Chrysanthemum.jpg"},{"brand":"iPhone 6 P ...

The total calculations for each row in Javascript and Ajax are experiencing glitches and are not functioning correctly

Below is the script utilized by an AJAX library and JavaScript. The total order column for total price is functioning correctly. However, the total calculations for the discount column and net price column are not working as expected. <script type="te ...

I'm struggling to make background-image display properly in my CSS code

In my quest to enhance the appearance of my website, I've been grappling with getting the background-image property to cooperate in CSS for the past three days. It's frustrating because I've successfully implemented this feature before, but ...

HTML: Enhancing User Experience by Updating Page Content Dynamically

Looking for assistance with creating HTML code that will dynamically generate a table on the same page after a user submits a form. Rather than redirecting to a new page with the output values, I want the results to display at the bottom of the current p ...