Using Javascript/JQuery to apply pixel values in CSS styling

Recently, I've come across a discrepancy between two different ways of accessing CSS properties in jQuery:

<foo>.css('marginTop')

(which I always assumed was the standard notation) and

<foo>.css('margin-top')

(which I believed to be non-standard).

For example, if foo has margin-top: 3em;, using the first notation returns 3em, while the second notation returns 48px (the equivalent of 3em in pixels). I find this behavior interesting, but couldn't locate any information about it in the API.

Why does this difference exist and where can I learn more about it?

P.S.: Just to clarify, this difference applies to attributes other than margin-top as well...

Thank you!

Answer №1

The documentation states that "jQuery has the ability to interpret both CSS and DOM formatting of properties with multiple words", but in reality, this is achieved through somewhat unreliable workarounds that may not always produce expected results.

Specifically, when you provide a DOM-style camelCaseName, jQuery will first attempt to access the inline style declaration as style.camelCaseName. If this fails (usually because the style was not set inline), it will then try using getComputedStyle with the camelCaseName converted to hyphen-separated-name(*). The computed style can differ from the declared style as the browser may resolve various relative declarations, such as converting lengths to pixel units.

On the other hand, if you supply a CSS-style hyphen-separated-name, jQuery will directly use the code for computed style(*) without attempting to convert it to camelCaseName and checking the inline style.

This behavior seems somewhat unreliable and I would hesitate to rely on it entirely. To ensure consistent results, it is recommended to keep the inline style declaration off the element being measured so that the computed style is always returned, regardless of the type of name used. However, jQuery does not explicitly promise this behavior. This highlights the challenge of concealing a complex system behind a seemingly straightforward "Do What I Mean" interface.

(*): This is different in Internet Explorer where there is no getComputedStyle function, so it resorts to a cumbersome combination of currentStyle, runtimeStyle, and document manipulation in an attempt to retrieve a computed style.

Answer №2

The discrepancy arises from the differing notations used in CSS and JavaScript to refer to the same concept. This distinction is found not within the jQuery API, but rather in a CSS guide.

While CSS employs margin-top, JavaScript uses marginTop to indicate the identical attribute. The default value for margin-top in CSS is 0px, leading to a display of 48px instead of 3em.

For further information, please visit http://www.w3schools.com/css/css_reference.asp.

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

Navigating through JSON arrays can be achieved by utilizing iteration techniques

I'm having trouble with a script and can't figure out how to make it display in the designated div. It may have something to do with how I'm handling the response. In Chrome devtools, the response looks like this: { "[\"record one& ...

The dropdown menu vanishes from sight as soon as the cursor moves away from a link

Recently, I encountered an issue while trying to create a dropdown menu using Jquery. The problem arose when attempting to select the second link, as the entire menu would disappear. Additionally, is there a way to ensure that only one dropdown menu is vis ...

Delaying the search in Jquery until the input is finalized

Is there a way to delay the search trigger until the user finishes typing? I'm utilizing a function created with mark.js () which initiates the search as the user types, resulting in jumping to the first result during the search. However, the issue is ...

jQuery issue with hover and mousedown

Hello everyone, I have a little challenge that I believe shouldn't be too complicated. What I want to achieve is displaying an image in a cell when the mouse hovers over it. Here's the setup: <table id="selectable"> <tr> ...

The map failed to display any information

<div> {!props.isLoading && <div> {normalizedData.map((outerObj,index) => { { <p className="space_name"> {outerObj.space_name} </p> ...

Determine whether an element has padding using jQuery

How can one determine if a specified element has padding properties applied to it? For instance, could we achieve this code block: if($('div.MiddleColumn') contains a padding of 5px) { perform certain action } else { perform an alternat ...

Ways to resolve the error message "Uncaught TypeError: props.options.map is not a function occurring when using a dropdown select

While working on my project, I encountered a strange error with the react select dropdown. Despite following suggestions online to pass an array of objects as options, I'm still facing the same issue. Surprisingly, when I directly input the data fetch ...

The series in angular-chart is not displayed at the top as shown in the documentation

angular-chart.js provides an example of a bar chart, which can be found here. Using this as a foundation, I made some modifications to the js and markup code like so. HTML <body ng-app="app"> <div class="row"> <div class="col-m ...

Troubleshooting React/Jest issues with updating values in Select elements on onChange event

I am currently testing the Select element's value after it has been changed with the following code: it("changes value after selecting another field", () => { doSetupWork(); let field = screen.getByLabelText("MySelectField") ...

Is it possible to animate the change in background color dynamically using jQuery?

I am struggling to implement a change/animate feature for the background color. When I place the background script within the form submit event but outside the ajax call, I can briefly see the color change. However, once the remote content loads, the colo ...

How to manage access controls for the Admin Page in node.js

Hi everyone, I am facing an issue with my admin page access control on my application. I want to restrict access to all users except the one named John. In my app.js file, here is what I have: app.get('/admin', requireLogin, function(req, res){ ...

Secure your browsing experience with AngularJS authentication prompt

Currently, I am working on building an application using AngularJS for the front-end and JavaEE for the back-end. In my AngularJS application, I am trying to access a REST resource provided by the back-end which is protected with JAAS authentication, allow ...

Trigger javascript function with a button click

Is there a way to trigger a JavaScript function from an HTML button that is not functioning properly? REVISED To see the issue in action, please visit this jsfiddle link: http://jsfiddle.net/winresh24/Sq7hg/341/ <button onclick="myFunction()">Try i ...

How can I force a Kendo UI Chart to resize in VueJS?

When integrating Kendo UI's Chart component within a Vue application, how can we trigger the chart to refresh or redraw? Although the chart automatically adjusts to changes in width by filling its parent container horizontally, noticeable stretching ...

React conditional statement within a map function embedded in a JSX element

Below is the function I have created to generate tabbed items: function ConstructTabs(props) { const tabs = props.tabs; const makeTabs = tabs.map((tab, index) => { <React.Fragment> <input className="input-tabs" id ...

TS1086: Attempting to declare an accessor within an ambient context is not allowed

While using Angular, I encountered the error TS1086: An accessor cannot be declared in an ambient context. when using Javascript getters and setters in this Abstract Typescript class. Here is the code snippet causing the issue: /** * The current id ...

Is there a way to assign a specific color to individual users in a chat?

I have successfully implemented a chat feature using Pusher, but now I want to customize the appearance by changing the color of the username for the logged-in user when they are active in the conversation. Currently, both my username and another user&apos ...

How can I locate the ID of the HTML input element with jQuery?

I am trying to create a page with a button that looks like this: <input type="button" id="btnAddBusinessUnit" value="Add Business Unit" class="clsAddBusinessUnit" alt="testBtn" /> When the button is clicked, I want to display the id 'btnAddBus ...

What is the best way to generate a live map with constantly updating markers?

Is it possible for me to learn how to develop a live map similar to the one on this site: www.lightningmaps.org? It's fascinating to watch new markers pop up every few seconds. I'm interested in building a real-time map that can track IP locatio ...

Executing control with AngularJS when ng-change event occurs

When using AngularJS One interesting scenario I encountered is having a ng-change event on a text field and seeing the function being called correctly: <input type="text" ng-model="toggleState" ng-change="ToggleGroupVisiable()" data-rule"" /> The ...