Using Jquery to assign negative values in CSS styling

Here is the jQuery code snippet I am working with:

<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript">
 $(document).ready(function() {
     get_font_size();
     set_sidebar();

});
function get_font_size()
{
var b=$(window).width();
var side_size=b*260/1440;
b=b-side_size;
$("#sidebar").css({"width":side_size});
$("#alexa-widget img").css({"width":side_size});
$(".fb-like-box").attr("data-width",side_size); 
}
function set_sidebar()
{
var b=$(window).width();
var font_size=b*65/1440;
var font_size_2=b*133/1440;
var margin_top=b*10/1440;
margin_top*=-1;
margin_top=Math.round(margin_top);
$("#my_tabs li").css({"font-size":font_size});
$("#header").css({"font-size":font_size_2,"margin-top":margin_top});

}
</script>

Although everything works smoothly, I am facing an issue with the margin-top property. Assigning a negative value to margin-top fails, while other CSS properties are applied correctly. Could anyone explain why jQuery CSS settings do not support negative values, whereas it works fine when directly applied in CSS? My goal is to dynamically adjust webpage layout based on screen resolutions, so using CSS directly is not an option. I have already included the viewport meta tag in my code, so viewport or media query solutions are not relevant. I have verified the margin_top variable using alert(margin_top) and it displays the correct negative value. The calculation seems to be correct, but the CSS setting part is failing. Any assistance in resolving this issue would be greatly appreciated. Thank you.

Answer №1

Is there an issue with approaching it in this manner?

$('div').css({marginTop:-100});​

Not everything must adhere to being strongly typed.

Answer №2

When using jQuery to set the margin-top property, remember to include the units (e.g. px) at the end.

For example:

>>> $("body").css("margin-top");
"0px"
>>> $("body").css("margin-top", "10");
[body]
>>> $("body").css("margin-top");
"0px"
>>> $("body").css("margin-top", "10px");
[body]
>>> $("body").css("margin-top");
"10px"

UPDATE (to clarify how to correct your code):

Modify the line in your code that appears as:

$("#header").css({"font-size":font_size_2,"margin-top":margin_top});

to

$("#header").css({"font-size":font_size_2,"margin-top":margin_top + "px"});

Answer №3

It is necessary to specify a unit of measurement for the margin you are setting.

$("#header").css({"font-size":font_size_2,"margin-top":margin_top+"%"});

Answer №4

After some troubleshooting, I was able to solve the issue by applying the following CSS using jQuery:

$("#header").css({"font-size":font_size_2,"margin-top":margin_top+"%"});
.

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 enhancing the speed of drawing circles in mouse movement using JS and CANVAS

My current script allows me to draw a circle during mousemove, but it's not as fast as I'd like. Before drawing the circle, I gather the color pixel during mousemove in order to draw a circle on the canvas with the picked color. I came across ...

What is the best way to display the weather information for specific coordinates in ReactJS?

I've been working on a code that retrieves farm details based on longitude and latitude. My goal now is to fetch the weather information for that specific farm using openweathermap However, each time I attempt to do so, an error message {cod: '4 ...

Utilizing node-json2html, generate individual HTML tables for each record

I need assistance in consolidating my JSON data into a single HTML table, instead of generating separate tables for each record through my current transformation process. var data=[{"name":"aa","mid":"12345","user":"a123","password":"a@123"},{"name":"bb" ...

What is the best approach to achieve the old THREE.SpriteAlignment effect in the latest version of three.js?

After adapting an old three.js code for my application that includes a 3D function with axes grids, I encountered an issue when trying to update it to the latest revision, r74: https://jsfiddle.net/cjfwg2c4/ Without THREE.SpriteAlignment.topLeft, sprites ...

Generating variable names dynamically in JavaScript

To prevent a javascript heap issue, I implement the usage of multiple arrays including 'family1', 'family2','family3' and 'dogs1', 'dogs2', 'dogs3'. For instance, you can use 'family1 and dog ...

The placement of Bootstrap Datepicker is experiencing issues

I have integrated the Bootstrap Datepicker from Eternicode into my ASP.Net MVC website. While the functionality is working well, I am facing difficulty in positioning the datepicker modal using the orientation option mentioned in the documentation and code ...

Guide to receiving intermediate feedback from my REST service for a standalone GET request

I have been working on designing a user interface that includes a progress bar to display the percentage of completion for a user request. However, my backend REST service performs complex computations and is relatively slow. I would like to provide the u ...

Incorrect script enqueue order in child theme of WordPress

Help needed with enqueuing a script in a WordPress child theme. Despite specifying Jquery dependency, the script is loaded before Jquery. The code in question: add_action( 'wp_enqueue_scripts', 'child_theme_scripts' ); function child_ ...

The categorizing and organizing of arrays

My goal is to create a messaging application where users can view a list of their recent messages, along with a preview of the latest message received/sent, before selecting a conversation. However, I'm facing an issue with my script that displays all ...

Developing a password strength checker using Javascript for ultimate security

Currently encountering an issue with my javascript project. The main goal is to validate user input against a list of known bad passwords and also their "1337" versions. Initially, checking for the basic bad password list was straightforward. However, th ...

HTML5Up! Skyrocketing with Meteor showers

While attempting to utilize a responsive site template from , I encountered several issues. To test the template, I downloaded the Striped package and created a clients folder in a Meteorite app where I placed the Striped folder. In order to make it work, ...

Bundle Thirdparty Dependencies with Webpack

I am looking to package a webpack bundle that includes all common third-party vendors such as Angular 1.4, jQuery, and other libraries. Currently, the following modules have been developed: Module A Vendor Module Vendor Module: Create a simple module ...

Update the CSS classes exclusively for the specified ID

Attempting to modify and override certain classes within the complex control (dxList) of DevExtreme has been successful thus far. .dx-loadpanel-content { transform: translate(0px, 0px) !important; margin: auto !important; left: 0px !important; ...

Why is my Bootstrap row exceeding the page width when I resize it?

As a newcomer to Bootstrap, I have been following tutorials to learn more about it. Currently, I am attempting to recreate the layout of Google's homepage. However, I am facing challenges with the grid system's responsiveness. I have managed to ...

What steps are involved in setting up a search results page for example.com/s/keyword?

app.js app.get('/results',showResult) var express = require('express') var n = req.query.query; mysql_crawl.query('SELECT prod_name, full_price FROM `xxx` WHERE MATCH(data_index) AGAINST("'+n+'")', function(error, p ...

What's causing the "Uncaught SyntaxError: Unexpected token u" error to consistently pop up in Chrome?

I've been trying to figure this out all day by searching online, but I'm still stuck. My code is quite long and runs fine in Firefox, but Chrome throws an error: "Uncaught SyntaxError: Unexpected token u". Could someone please point out where I ...

Modify the td attributes while retaining the extracted data values from the website

I'm currently utilizing this code to extract data from another website: $searchURL = "http://www.anotherwebsite.com"; $html = file_get_contents($searchURL); $patternform = '/(<tbody.*<\/tbody>)/sm'; preg_match_all($patternfor ...

Retrieve an object using a variable

Essentially, my question is how to extract a value from a variable and input it into a sequence. Being Dutch, I struggle to articulate this query correctly. var channelname = msg.channel.name; "description": `${config.ticketlist.channelname.ticketmessage} ...

Ways to verify user login through jQuery post method

I am currently working on a login test application that utilizes jQuery post and PHP. I'm encountering an issue where the application is able to read the input values but fails to send the data to server.php and consequently does not return any data. ...

Issue with CSS background color not extending to full screen in webkit browsers when using 960.gs grid system

When using 960.gs, I have created a login screen with a div for the login form that has a background image. This div is positioned below a header, which centers it in the browser window. In my CSS, I am setting the body color as follows: body { backgr ...