implementing a position absolute that is responsive by utilizing javascript

I have prepared a code snippet to illustrate my issue.

img {
    border:1px solid;
}
.bubble1 {
    width:50px;
    height:50px;
    background:pink;
    opacity:0.8;
    position:absolute;
    top:65px;
    left:45px;
}
.bubble2 {
    width:50px;
    height:50px;
    background:cyan;
    opacity:0.8;
    position:absolute;
    top:135px;
    left:155px;
}
.bubble3 {
    width:50px;
    height:50px;
    background:orange;
    opacity:0.8;
    position:absolute;
    top:190px;
    left:68px;
}
.bubble4 {
    width:50px;
    height:50px;
    background:red;
    opacity:0.8;
    position:absolute;
    top:220px;
    left:213px;
}
<img src="http://i.imgur.com/62GOyK9.png" />
<div class="bubble1"></div>
<div class="bubble2"></div>
<div class="bubble3"></div>
<div class="bubble4"></div>

There are 4 boxes that I want to position on a background, and I achieved it using absolute positioning.

However, the challenge is making it responsive. When viewed on larger or smaller screens, the image gets distorted and the positioning is incorrect. How can I address this issue using JavaScript?

Answer №1

Do you really need a javascript solution for this?

Why not utilize percentage values in CSS position properties instead?

img {
    border:1px solid;
}
.bubble1 {
    width:50px;
    height:50px;
    background:pink;
    opacity:0.8;
    position:absolute;
    top:15%;
    left:10%;
}
.bubble2 {
    width:50px;
    height:50px;
    background:cyan;
    opacity:0.8;
    position:absolute;
    top: 30%;
    right:30%;
}
.bubble3 {
    width:50px;
    height:50px;
    background:orange;
    opacity:0.8;
    position:absolute;
    bottom: 30%;
    left:30%;
}
.bubble4 {
    width:50px;
    height:50px;
    background:red;
    opacity:0.8;
    position:absolute;
    bottom: 20%;
    right:10%;
}
<div class="bubble1"></div>
<div class="bubble2"></div>
<div class="bubble3"></div>
<div class="bubble4"></div>

Answer №2

$(function () {
  var init_width = $(window).width();
  var all_div = $('div');
  var init_left = function (){
    var result = [];
    all_div.each(function (i){
      var left = parseInt($(all_div[i]).css('left'));
      result.push(left); 
    });
    return result;
  }();  
  $(window).resize(function (){  
    var width = $(window).width();
    all_div.each(function (i){
      var now_left = init_left[i] / init_width * width;
      $(all_div[i]).css('left',now_left);
    });
  });  
});
img {
    border:1px solid;
}
.bubble1 {
    width:50px;
    height:50px;
    background:pink;
    opacity:0.8;
    position:absolute;
    top:65px;
    left:45px;
}
.bubble2 {
    width:50px;
    height:50px;
    background:cyan;
    opacity:0.8;
    position:absolute;
    top:135px;
    left:155px;
}
.bubble3 {
    width:50px;
    height:50px;
    background:orange;
    opacity:0.8;
    position:absolute;
    top:190px;
    left:68px;
}
.bubble4 {
    width:50px;
    height:50px;
    background:red;
    opacity:0.8;
    position:absolute;
    top:220px;
    left:213px;
}
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<div class="bubble1"></div>
<div class="bubble2"></div>
<div class="bubble3"></div>
<div class="bubble4"></div>

I have created a DEMO to showcase how the responsive layout is achieved. The main points to keep in mind are:

  1. Upon DOM ready, gather the initial set of numbers for each div's left and convert these values to percentages for responsiveness.
  2. Recalculate the window width upon resizing.

Once you grasp the first key point, achieving responsive design becomes straightforward. The resize functionality simply enhances the adaptability of the DEMO.

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

tips for uploading image data using JavaScript

My HTML form sends POST data to my PHP script and uses AJAX for a live preview The issue arises with the image input field in the form Here's an example of the form structure: <form method="post" action="scripts/test.php" enctype="multipart/form ...

Maintaining the proportions of divs containing background images

I'm dealing with a background image that features a large blue diagonal line where we want our content to align. However, I'm encountering difficulties in maintaining the alignment of the content as it resizes (resulting in the background diagon ...

Exporting the state of a Redux reducer as an array in a TypeScript file

Having an issue where my reducer is undefined and I can't seem to figure out why. It's working fine when it's not an array, but when it is an array it stops working. This is how my code looks like in groupSlice.ts: export interface GroupSta ...

What's the Best Way to Align a Floating Element in the Center

I am struggling to align three h3 tags horizontally within a div tag. The first h3 should be left aligned, the second centered, and the third right aligned. Despite finding solutions here, I have not been able to execute them successfully. Appreciate any h ...

Breaking down a statement into individual elements within an array, incorporating keys alongside the elements within the array

let condition = "[AccNum]==true&&[AccNum]==[ARID]&&[AccNum]==aaaa || [ARID]!=true&&[DOB]&gt;[ARID] || [DOB]&gt;bbb&&[DOS]&gt;=[ARID]&&[DOS]&lt;[Gender]&&[66642]&lt;=cccc&&[66642] I ...

Best practices for starting and stopping trace spans in express / nodejs applications

Currently, I am conducting an experiment with utilizing the Opentelemetry.js nodejs/express library and attempting to refactor the reviews application from the bookinfo Example found in Istio. I followed the tracer configurations laid out in the sample: ...

Tips on serializing two arrays into JSON format and incorporating them in an AJAX request

I have a task where I need to retrieve all the names and details associated with a specific reference number. To accomplish this, I am using a while loop. However, I am unsure of how to encode these values in JSON format so that I can use them in AJAX for ...

Exiting the window event

While searching the internet for a solution, I discovered that the method I thought was the simplest way to handle a window being exited (window.unload()) has been deprecated in an earlier version of jQuery. Does anyone know of a straightforward approach t ...

Adaptive component transformation

Hey there, I'm having some trouble figuring this out... I need help with making sure that the element identified by the red rectangle in the images moves in alignment with the containers below, regardless of the screen size. I want to create a respon ...

Is it possible to retrieve Firebase values, but not able to access them?

I'm facing an unusual issue where pushing a value to a Firebase object leads to two unexpected outcomes: I am unable to retrieve it from the array when pulling the object from Firebase. The array I receive does not have a length property. Let' ...

How many requests per second can a Selenium client-sided load test handle?

I am currently using Selenium for client-side testing on an AngularJS web application with a specific browser. My objective is to execute a load test by generating numerous requests from concurrent users. For instance, sending 1k requests per second from x ...

Utilize Angular to create a dropdown filter activated by a click event

Having trouble filtering or searching for relevant data using a dropdown input? The task is to select an option from the dropdown and click on the button to filter or display the corresponding data in a table using Angular. Directly achieving this works, b ...

The Request Dispatcher triggering a jQuery $.get function to display an alert with the contents of the webpage

For instance: Let's say I have a JavaScript code like: $.get('Test_Controller.html',function(response){ alert(response); }); And in my Test_Controller.html servlet, I have: request.setAttribute("test","testData"); RequestDisp ...

Tips for positioning the search bar on the opposite side of the navbar in Bootstrap 5

In my navbar, I have items aligned on the left and a search bar aligned on the right. However, when I try to move the items to the right using the ms-auto class, only the items move and the search bar stays in place. How can I adjust the alignment so that ...

Obtaining a value using the Node.js inquirer package

I'm currently working on a flashcard generator using the node.js inquirer package, but I'm struggling to capture the user's selection. When the user selects an option, I want to be able to log that choice, but right now it's just return ...

How can Typescript help enhance the readability of optional React prop types?

When working with React, it is common practice to use null to indicate that a prop is optional: function Foo({ count = null }) {} The TypeScript type for this scenario would be: function Foo({ count = null }: { count: number | null }): ReactElement {} Wh ...

Is it possible to customize the width of text color alongside a progress bar?

My Bootstrap 4 Website contains the following HTML code snippet: <div class="container"> <div class="row"> <div class="col-md-6 mx-auto> <h2>Example heading text</h2> <h6>Example subh ...

Issue with tooltip functionality in the image gallery setup

I am currently working on creating tooltips to overlay on images in an image-gallery-like layout. While the tooltips are somewhat functional in the browser, I noticed that on the second and third image, they tend to appear too far to the right. Additionall ...

Guiding the way with headings listed beneath every point

Hello there! I am trying to achieve a specific layout using this image as a reference. In the image, there are 3 different background images (represented by three Divs) and I want to add 3 List Points labeled as "LV", "RP", "IP" with centered descriptions ...

Error alert: Index not defined!

I have a dropdown select that needs to be populated with values from a database. I then need to validate the selected value using a JavaScript function, which is already implemented. The dropdown list has two columns: one for ID identifiers and another fo ...