How to troubleshoot incorrect div width detection by jQuery in Bootstrap

My asp.net mvc4 project utilizes bootstrap for markup and jquery for client side functionality.

<div class="row">
<div class="col-md-4 container" id="cont">
    <div class="row overlay_container" id="overlayCont">
        <div class="col-md-12 background" id="bg"></div>
        <div class="col-md-12 text" id="txt">
            <h1>This is a test!</h1>
            This is also a test!
        </div>
    </div>
    <div class="row">
        <div class="col-md-12">
            <img src="~/Content/Images/5.jpg" id="porfolioImage" />
        </div>
    </div>
</div>

        var wdth = $("#porfolioImage").width();
        alert(wdth);
        var hgth = $("#porfolioImage").height();
        alert(hgth);
        $("#overlayCont").width(wdth).height(hgth);
        $("#bg").width(wdth).height(hgth);

After triggering the alert, the values returned are wdth = 382 and hgth = 382. However, upon replacing elements, the following line is produced:

[<div class=​"col-md-12 background" id=​"bg" style=​"width:​ 412px;​ height:​ 382px;​">​</div>​]

I am unsure as to why it inserts 412 instead of the expected 382. How can I rectify this issue?

Answer №1

Adjust the width and height of the element with the id "bg" using jQuery: $("#bg").width(wdth).height(hgth);

Remember that the width of the background element does not take padding into account.

When using the Bootstrap class "col-md-12", keep in mind that it adds padding of 15px to the left and right.

To calculate the total width of an image within a col-md-12 element, add the image's base width of 382px to the left and right padding of 15px each, resulting in a total width of 412px.

Answer №2

It seems like the issue may be due to bootstrap or the box-sizing property in your CSS, such as:

-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;

When using .width(), it includes the width of the element plus padding and borders.

To avoid this problem without altering the CSS, you can use .css() instead of .width() and .heigth(), like this:

$("#overlayCont").css({height: hgth, width: wdth});
$("#bg").css({height: hgth, width: wdth});

Alternatively, a shorter version:

$("#overlayCont, #bg").css({height: hgth, width: wdth});

.css("width") and .css("width", number) will get and set the CSS style (ignoring padding, border, and box-sizing).

.width() behavior depends on CSS settings, refer to http://api.jquery.com/width/ for more details.

You can also check the console in the jsfiddle example provided: http://jsfiddle.net/Lyfr5/1/

Hopefully, this information helps you understand better. Have a great day!

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

What is the best way to send an HTML form variable to a Perl script using AJAX?

My goal is to pass the HTML variable from the list menu to the Perl script using POST. However, when I try to do this, the jQuery ajax() function executes the Perl script without including the value obtained from document.getElementById. Below is the sni ...

How to extract metadata from a transformed response using Angular's $resource

Here is the API structure I am working with: { "meta": { "total_item": 1, "number_of_pages": 1, "page_number": 1, "status": "Success" }, "data": [ { "name": "Operator 1", "short_name": "OP1", "_id": "534d69bba75 ...

How to handle a CF error while invoking a CFC through Ajax requests

I am currently working on a ColdFusion application that utilizes jQuery to make a call to a CFC using $.post. I have implemented error handling in the CFC, but what about scenarios like the following: CFC: <cfcomponent> <cffunction name="fun ...

Setting up a new package through JPSM installation

I utilize jspm in my web application. My goal is to install the npm:angular2 package without needing to set it up in the config.js file. Instead of loading the angular2 module via jspm, I manually added the angular2 library like this: <script src="jspm ...

Eliminating the need for RequireJS in the Typescript Visual Studio project template

After integrating RequireJS into my Typescript template using the nuget package manager, I found that it was more than what I needed and decided to uninstall it. Even though I removed the package through nuget and the files were deleted properly, my Typesc ...

Incorporating SASS/SCSS syntax within the <style> element

Can I include SASS/SCSS syntax directly in an .html file within a style tag? I'm interested in defining a variable within the .html file and then utilizing it in a .sass file. ...

Tips for delaying the evaluation of an <input> field?

I am interested in analyzing the content of an <input> field when there is no activity from the user. One simple example I have considered is counting the number of characters, but the actual analysis process is very resource-intensive. To optimize ...

Displaying a notification for a multi-selection using JavaScript

I need help with a piece of Html code I have. It's a list of countries, and what I want is to show an alert when one or more countries are selected to display which ones were chosen. I'm working with JavaScript only and don't want to use Jqu ...

Tips for connecting elements at the same index

.buttons, .weChangeColor { width: 50%; height: 100%; float: left; } .weChangeColor p { background: red; border: 1px solid; } .toggleColor { background: green; } <div class="buttons"> <p><a href="#">FirstLink</a></ ...

Some inquiries regarding the fundamentals of JavaScript - the significance of the dollar sign ($) and the error message "is not a function"

Teaching myself JavaScript without actually doing any explicit research on it (crazy, right?) has led to a few mysteries I can't quite crack. One of these mysteries involves the elusive dollar sign. From what I gather, it's supposed to be a con ...

Switching Up Poster Images in Chrome with Afterglow HTML5 Video on Hover

I have been experimenting with the html5 video player from AfterGlow. In my sample video, I included a poster attribute. However, I noticed an issue when viewing the video in Chrome - whenever I hover over it, the poster image flickers, creating an undesir ...

Organize three image links side by side using HTML layout

Hello there! I'm currently working on a website project and I'm struggling with arranging some image links in a specific layout. The grey rectangles you see represent where the images should be placed, all of them are uniform in size (275 x 186) ...

Input field in a tableview

I have a ListView that features a dropdown, 4 textboxes and buttons. My goal is to only show the fourth textbox (enclosed in a span) when the dropdown value in each row of the ListView is set to 2. For instance, if there are 5 records being displayed in t ...

ThreeJs is known for effortlessly handling an abundance of vertices, far surpassing the number typically found

I came across this code snippet: function loadObject(filePath){ var loader = new THREE.OBJLoader(); loader.load( filePath, function ( object ) { child = object.children[0]; var geometry = new THREE.Geometry().fromBufferGeometry( ch ...

PHP prepared statements do not seem to be effectively updating or inserting entire datasets

My website allows members to create and update posts using a text editor. However, I've run into an issue when the post content includes new lines or spaces such as <p>&nbsp;</p> or <div>&nbsp;</div>. The problem arises ...

What causes the fixed div to appear when scrolling horizontally?

I have replicated this issue in a live example: http://jsfiddle.net/pda2yc6s When scrolling vertically, a specific div element sticks to the top. However, if the window is narrower than the wrapper's width and you scroll horizontally, the sticky elem ...

Combining two objects by aligning their keys in JavaScript

I have two simple objects that look like this. var obj1 = { "data": { "Category": "OUTFLOWS", "Opening": 3213.11, "Mar16": 3213.12, "Apr16": 3148.13, "May16": 3148.14, "Jun16" ...

Navigating through Ruby on Rails' index routes

I have set up an index for the object "request". Each request has an address and a body. I configured the index to display the address as a link, with the intention of directing users to the show page of that specific object. However, when I click on the l ...

The issue arises when trying to use both CSS Sprite and Background Gradient simultaneously in Chrome/Safari

Lately, I've been having issues with the gradient not displaying correctly in Webkit, although it seems to be working fine in Firefox. Could someone take a look and see if there's an error in how I set it up? Please disregard the images, as it&ap ...

iPad screen not displaying overflow for x and y axis

I'm encountering an issue with displaying the scrollbar on a div while using an iPad device. Currently, I am utilizing: -webkit-overflow-scrolling: touch; Although this is functioning properly, my goal is to have the scrollbar visible without the ...