Divs remain oblivious to changes in screen size

One div acts as a category, while the other contains a series of photos.

I had an idea to create a feature where clicking on an image would cause the first div to move 0.7 of the screen width to the right and all images in the second div would disappear. So, I implemented the following code:

$(document).ready(function() {
                $("img").click(function() {
                    var my_width = screen.width * 0.7;
                    $(".second_div").find("img").hide();
                    $(".first_div").css({
                        "transform": "translate(" + my_width + "px,0px)",
                        "-webkit-transform": "translate(" + my_width + "px,0px)",
                        "-ms-transform": "translate(" + my_width + ",0px)"
                    });
                });
            });
.first_div {
                transition-duration: 2s;
            }
<div class="first_div col-md-1">
                //some code
            </div>
            <div class="second_div col-md-11>
                    //some codes
            </div>

Initially, the functionality worked as expected with full-screen display. However, upon resizing the window and trying again, the first div did not align at the correct position (0.7 of the screen width). What could be causing this issue?

Answer №1

When determining the width of a window, I recommend using the following code snippet:

let my_window_width = document.documentElement.clientWidth * 0.7;

This method is universally compatible across various browsers and mirrors the approach utilized by jQuery's $.width() function.

To explore alternative approaches for obtaining window width measurements, you can refer to this informative resource.

Answer №2

Consider using the inner width of the window instead of the screen width to make it relative to the viewport size. Simply update

var my_width = screen.width * 0.7 ;

to:

var my_width = window.innerWidth * 0.7 ;

Check out an example here:

http://codepen.io/anon/pen/jWWEKO

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

The incorporation of SVG within a span disrupts the conventional left-to-right arrangement of its child elements

As I was working with some basic HTML, I encountered an issue. <span> <span>Hello</span> <span>World</span> </span> The above code displays: Hello World However, when I tried adding an SVG element like this: <s ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...

Dynamically generate nested JSON from an array of objects

My collection of objects looks like this: { title: "A", parent_id: "root", has_children: true} { title: "A1", parent_id: "A", has_children: true} { title: "A11", parent_id: "A1", has_children: false} { title: "A12", parent_id: "A1", has_children: false} ...

How can Vuejs switch between different attributes of an object?

How can I switch between first name and last name in an array of objects on a button click? new Vue({ el: '#app', data() { return { myArray: [{ firstName: 'ricky', lastName: 'martin' ...

Exploring ASP.NET AJAX with UserControls: mastering client-side scripting

I am facing a scenario where I need to dynamically include a UserControl in a page multiple times based on specific business rules. Currently, the UserControl contains a JavaScript function that needs to be triggered during the ASP.NET AJAX pageLoad event. ...

Error handling: Encountered unexpected issues while parsing templates in Angular 2

I'm a beginner with Angular 2 and I'm attempting to create a simple module, but encountering an error. app.component.html import { Component } from '@angular/core'; import { Timer } from '../app/modules/timer'; @Component({ ...

What steps can I take to ensure that the text content stays within the borders and does not overlap with the photo?

click here for the image description Html <p><img src="index-foto1.jpg" align="left" width=65% style="border-radius: 10px;" margin-right: 2px> <div class="tant"><h3>More detailed inform ...

Customize the background color of the body and navbar in Bootstrap 5

Here is a snippet of the HTML code I am working with: <nav class="navbar navbar-expand-lg navbar-dark bg-success "> <div class="container-fluid"> <div class="d-flex justify-content-between w-100" style=&qu ...

Other than the doctype declaration and the opening html tag, what additional markup can reside outside of the head and body elements in an HTML document

When it comes to an HTML document, the majority of content is typically found within the html head and body. However, what other elements can exist outside of these sections? ...

Two paths in AngularJS

In the AngularJS application, the ui-router is used to manage two types of pages: Pages with routes explicitly specified in routes.js Pages with routes dynamically derived on demand Upon loading the page, the application sends a request for data (type, ...

What is the best way to update the value of a specific key in discord.js?

As I struggle to explain properly due to my limited English proficiency, I am reiterating my question. In my config.json file, there is a key named "status" with a corresponding value of "online". I am attempting to change this value but haven't been ...

Positioning buttons in a grid using CSS - Tips and tricks

Help needed! Seeking professional advice. I have a few issues that I can't seem to solve on my own. Firstly, regarding the second menu - should I use padding to position it correctly? Secondly, although I managed to make the navigation bar visually s ...

The anchor tag is failing to register when placed inside a dynamically created table cell

I'm attempting to place an anchor tag within a cell of an HTML table. Here is the code I am using, but for some reason, the tag is not being identified and no hyperlink is displayed in that cell. Is there an issue with the syntax? $("#tranTbodyI ...

Decoding deeply nested JSON data using JavaScript

After browsing through countless threads on the topic, I have yet to find a solution. I successfully parsed a JSON response that looks like this: { "1": { "id": "1", "name": "Fruit", . . . "entities": { ...

Maintain the username data after refreshing the page in React by utilizing local storage

I'm attempting to manage the value of username using local storage. Upon page load, the user should be greeted with a heading that says welcome John. Additionally, I want this value to persist when the page is reloaded. However, upon loading the page ...

What is the best way to make an HTML form show fields depending on certain conditions?

Initially, I created an index page containing a form with various fields. The utility was built to handle all the fields, but now there's been a change in requirements. What I need is for only the Controller Type and Test Type fields to be displayed f ...

Issues with aligning text in TextBoxes

I'm struggling to center align my text boxes and write labels on either side. I want it to look like this: https://i.stack.imgur.com/6QsNv.png Despite trying different solutions, I can't seem to get the boxes to align in the center. Is there a ...

Mastering the DELETE Method with ID in Node.js and ReactJS

Today, I encountered a challenging problem that I would like to discuss. This particular issue seems more complex than usual, so let me elaborate. Initially, I begin by fetching data asynchronously: getRandom = async () => { const res = await axios.g ...

Enhance the efficiency of AJAX requests

I have a problem with the speed of my ajax request in jQuery and asp.net. Here is how I am currently making the request: $.ajaxSetup({ type: "POST", contentType: "application/json; charset=utf-8", dataType: "json" }); $.ajax({ url: "/WebServices/ ...

Showing navigation items in Vuejs based on authentication status

In my current project, I am developing a Single Page Application (SPA) using vuejs with vuetify and integrating authentication via a laravel/passport API. The challenge I'm facing is related to conditional rendering of navigation icons based on user a ...