Looking for assistance in using JavaScript to determine the percentage of a DIV's width in pixels

Using PHP, I am generating boxes whose width is set to 100% of a container in CSS. Now, I want to determine the equivalent pixel value of that box...

HTML

<div class="masonry" >
<? while($row = $stmt->fetch()){    ?>

     <div class="item" id="needwidth" >
            <a href="#"><img src="..."></a>
     </div>
   <? } ?>
</div>

CSS (masonry will add columns based on available screen width)

.item{width: 100%;}
.masonry { column-count: 4;}

@media only screen and (min-width: 400px) {
    .masonry { column-count: 2;}
}

@media only screen and (min-width: 700px) {
    .masonry {column-count: 3; }
}

@media only screen and (min-width: 900px) {
    .masonry {column-count: 4;}
}

@media only screen and (min-width: 1100px) {
    .masonry {column-count: 5;  }
}

I attempted to utilize this JavaScript in the header:

<script>var width = document.getElementById('needwidth').offsetWidth;</script>

Later in my HTML, I tested it with:

<script>document.write(width);</script>

However, it returns:

undefined

Answer №1

To retrieve the desired value, you can utilize clientWidth. However, ensure that your code is placed at the end of the page or within a function triggered by the onLoad event. This is crucial as the DOM needs to be fully loaded before attempting to access the property value.

<!-- The following approach may not yield the desired result -->
<script>alert(document.getElementById('needwidth').clientWidth);</script>
<div class="item" id="needwidth" ></div>

...

<!-- To ensure success, try this approach instead -->
<div class="item" id="needwidth" ></div>
<script>alert(document.getElementById('needwidth').clientWidth);</script>

If jQuery is incorporated in your project, consider using the methods outlined below:

$('#needwidth').width();
$('#needwidth').outerWidth();
$('#needwidth').prop('clientWidth');

For further clarification, refer to this JSFIDDLE link: http://jsfiddle.net/nanndoj/gjtkvrsy/3/

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 box on my form is leaking my background color outside the 1px border, but only in Internet Explorer

While experimenting with background gradients and borders one day just for the fun of it, I made an interesting observation in Internet Explorer. The issue I encountered was that the background color was overflowing outside the radius border, but this onl ...

Identifying the camera model using getMediaStream

Are there methods available to determine if a user's device has a front, rear, or dual cameras installed? For instance, laptops typically only have a front-facing camera while some devices may have both. I am looking for a way to identify the type of ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

Encountering issue with 'mongodb-connection-string-url'

As a beginner, I am struggling to understand the error message. When I try to run the app.js file, I receive the following log message. I read that I need to upgrade my MongoDB, but since I am using Windows 7, this seems impossible. PS G:\AWebDev&bsol ...

Js: Automatically populating data into various input fields

I've encountered an issue with form input value injection using a <script> and POST requests. When I attempt to create another form with the same input field (same name and id), the value injection doesn't work, and troubleshooting has bee ...

The dynamic table rows are appearing out of order in the DOM

success: function (data, status) { var header = $("#MainDiv"); header.html(null); var headertemplate = $("<table class='searchlistbody'><tr></th><th>Name</th></tr>"); ...

The user authentication is not recognized in the current session (Node.js, Express, Passport)

I have encountered an issue where req.user is undefined, despite my efforts to troubleshoot for over 4 hours. I even resorted to copying and pasting the server/index.js file from a friend's server, modifying the auth strategy to suit my own, but the p ...

What's the deal with using tables or divs in web design? Are they necessary or just a crazy trend?

For my upcoming project, I am eager to take on this task. https://i.sstatic.net/eVSvy.jpg The question remains: which approach should I employ - a Div or table method? ...

Troubleshooting a Jquery example that fails to run on popular browsers like IE, Chrome, and Firefox

I've been struggling to get this particular example to function properly (using vs2010): <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %> <!DOCTYPE html PUBLIC "-//W3C//DTD X ...

Customizing the appearance of the browser's autocomplete feature as we input information into the form field

https://i.sstatic.net/p7PvH.png The image illustrates the issue of the background turning white when the browser autofills. However, I am seeking a solution similar to the transparent input below. ...

My requests are failing because jQuery AJAX does not send hashtag symbols

There's a challenge I'm facing while working with Elixir Phoenix and React.JS. The Token I have includes hashtags, and when I send a request to verify it, the hash symbols and everything after them are not being sent, causing the request to fail. ...

Passing input parameters from a jQuery dialogue box to a handler file (.ashx) in ASP.NET: A step-by-step guide

Hey everyone! I've set up a jQuery dialog box with two input fields as shown below: <div id="dialog" title="Login"> <form action="" method="POST" id="loginForm"> Username: <input type="text" name="username" /><b ...

Is there a way to manually stop a file upload (stream) using a XMLHttpRequest on the server?

Utilizing XMLHttpRequest (Level 2) to transfer a file to a node.js server, I am currently examining the file-stream for valid headers on the server side. The goal now is to halt the upload if any errors are encountered during streaming. My XMLHttpRequest c ...

What is the best way to send {...rest} properties to a text field in react material?

When using a material textfield inside a wrapper component and passing the remaining props as {...otherprops} in a JavaScript file, everything works fine. However, when attempting to do the same in TypeScript, an error occurs. const TextFieldWrapper = (pro ...

Avoid Bootstrap 5 collapse when clicking on links or buttons

In my table, there are parent rows with hidden child rows that can be toggled using the bootstrap collapse feature. Clicking on a parent row toggles the visibility of its child rows. Both parent and child rows can be dynamically added to the table. Parent ...

Adjust the color of the button upon hovering with CSS

I'm having trouble changing the text color from white to black when hovering over the button. The code seems fine, but the text color isn't changing. Can anyone help me figure out how to make it work? .main__btn { font-size: 1.2rem; back ...

What is causing the PUT request to not go through when using POSTMAN?

As I navigate through the paths of my application, I encountered an issue with PUT requests that were not being fully processed by POSTMAN. Below is the configuration of my ExpressJS server: const express = require('express'); const morgan = re ...

AngularJS does not function upon reloading the browser

I am currently working on a new project that involves the following components: Node.js (v0.10.37) Express micro framework Jade templating engine Angular.js (latest) Material design library (material.angularjs.org) Jquery One issue that I am facing is r ...

Delete the display:none; attribute to make the item appear on the screen

The following CSS code styles the element: span { position:absolute; float:left; height:80px; width:150px; top:210px; left:320px; background-color:yellow; display:none; //No display ...

What are the essential Angular 2 observables for me to utilize?

I have created a form input for conducting searches. Upon user input into the search bar, I want to trigger calls to two separate APIs simultaneously. Here is my current attempt: myInput: new FormControl(); listOne: Observable<string[]>; listTwo: Ob ...