Is it possible to set a single variable value for multiple attributes simultaneously in Javascript?

I would like to specify the horizontal padding of a styled element as variable 'x' and the vertical padding as variable 'y'. Here's one way to achieve this:

var docex = document.getElementById.style;
docex.paddingTop = y;
docex.paddingBottom = y;
docex.paddingLeft = x;
docex.paddingRight = x;

Is there a more concise method to accomplish this, perhaps something like:

var docex = document.getElementById.style;
docex.paddingTop = docex.paddingBottom = y;
docex.paddingLeft = docex.paddingRight = x;

However, it seems that the above approach might not work and could lead to declaring a global variable, according to another question I found on this site. So, what is the most efficient and minimal way to implement a similar idea using vanilla JavaScript?

Thank you in advance!

Answer №1

If you're looking to simplify your CSS code, you can utilize the short form rule like this:

example.padding = y + " " + x;

This will establish y as both top and bottom padding, while x will represent the left and right padding.

Reference at MDN

Answer №2

However, my understanding is that the above scenario would not function as expected and would result in declaring a global variable

That assumption is incorrect.

Let's examine these two instances:


var foo = bar = 2;

The above code snippet does the following:

  1. Declares foo as a local variable
  2. Sets bar to 2, implicitly creating bar globally in the process
  3. Assigns bar to foo

obj.foo = obj.bar = 2;

This piece of code performs the following actions:

  1. Sets obj.bar to 2, implicitly creating bar as a property of obj if it doesn't already exist
  2. Assigns obj.bar to obj.foo, implicitly creating foo as a property of obj if it doesn't already exist

No global variable is created because there is no reference to a variable name within the code.


On another note, if you are changing all padding properties, consider utilizing the padding shorthand property instead of individually adjusting each one.

padding: <top> <right> <bottom> <left>

or

padding: <vertical> <horizontal>

Therefore:

docex.padding = y + " " + x;

Answer №3

If you want to achieve this, utilize the style.padding property.

let width = "50px";
let height = "25px";

let element = document.getElementById('o');

element.style.padding = height + ' ' + width;
#o{
  width:200px;
  height:100px;
  border:1px solid black;
  box-sizing:border-box;
}
#i{
  width:100px;
  height:50px;
  background:red;
}
<div id="o">
<div id="i">
  </div></div>

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 updating the current user's username value in local storage in Angular

https://i.stack.imgur.com/ZA32X.png https://i.stack.imgur.com/iDHZW.png I am facing an issue with updating the local storage of a current User for only username. When I update the username, it's not reflecting in local storage. Even though I can s ...

Angular backend endpoints for serving non-HTML assets

My goal is to establish routing using ngRoute in Angular. I'm aware that when making GET requests to the backend, the expected response is to return index.html, which then loads Angular, allowing for the correct page to be constructed. The issue I&ap ...

The issue of apples failing to spawn correctly in the Snake game

My Snake game seems to have a bug that causes some strange behavior whenever an apple is collected. Upon collision, the apple disappears and a new one spawns in a new location, but then the original apple reappears in its initial spot. Subsequently, when t ...

Incorporating AJAX and jQuery to dynamically update a numerical value

I need to update the content within a span class using jQuery. The first line of my jQuery code is functioning correctly as it adds a new notification to the list. However, the second line that should replace the existing number with @unseen_notifications. ...

Due to the feature in VISUAL STUDIO CODE that presents folders and subfolders at the same level

While working on my Angular project, I encountered an issue with creating a subfolder within a folder. Despite trying the same process in Windows Explorer, I faced the same problem of them appearing on the same level. What could be causing this discrepan ...

Whenever I try to download express using npm install, I encounter a checksum

I currently have node version 0.10.30 and npm version 1.4.21 installed on my system. When I run the following command: npm install express I encounter the following error: Error: shasum check failed for /tmp/npm-4273-g1Rb0gCE/registry.npmjs.org/express/ ...

Having troubles with the rendering of views and layouts in FlightPHP Framework

I have recently started using FlightPHP for a small website project. My approach involves utilizing views and layouts to render the various web pages: <?php require 'flight/Flight.php'; Flight::route('/', function(){ ...

Submitting data using various submit buttons in PHP

I am facing an issue with multiple submit buttons in my form, each containing hidden values that are dynamically generated. The problem arises when I can see the correct values in the HTML source code, but upon submitting one button, all other values get s ...

Modifying the maximum length of input fields in HTML, Javascript, and PHP is possible by adjusting the value through

Hi there, I'm facing an issue that should be easy for you guys to help me with. I recently discovered a security flaw while using the maxlength function in HTML. Users can easily modify the maxlength attribute by inspecting elements on the website, wh ...

Chrome geolocation feature does not display the permission popup for JavaScript

After the latest Chrome update, we have noticed that the popup to Allow/Block accessing a user's location from a website is no longer appearing. We tested this on Edge, Firefox, and different mobile devices, where it seems to be working fine. Current ...

What is the best method for adding a line break in the body of an email when we include the recipient, subject, and message?

Do you have a requirement where information needs to be sent to an end user via Gmail (preferred) and they need to click on a button in the email body to respond? The button response is set up with predefined to, subject, and body fields, but there are dif ...

Sort posts alphabetically by their first letter using jQuery

Currently, I am dealing with a collection of products sourced from WooCommerce and displayed as custom posts through the Elementor page builder at this link: My attempt to incorporate an alphabetical filter using a plugin has not been successful, most lik ...

Utilizing media queries and page width in a Moodle theme designed with Bootstrap framework

I currently have my LMS set up with Moodle 4 and the boost theme which is based on bootstrap (github) However, the default page layout appears very narrow on all devices and I would like to utilize the responsive design features of Bootstrap for different ...

The error message encountered is: "TypeError: Unable to access the 'apply' property of an undefined object within the

Currently in the process of developing a node js application with the integration of DHTMLX Scheduler feature on one of the pages. However, my progress is hindered by a recurring issue upon loading the page, resulting in the following error message: TypeE ...

Implement dynamic page titles with breadcrumbs in Laravel 8 for a seamless user experience

I am currently utilizing the laravel-breadcrumbs package created by diglactic in conjunction with laravel 8, which is a fork from davejamesmiller/laravel-breadcrumbs. My goal is to incorporate a dynamic page title that aligns with this breadcrumbs package. ...

The resize() function in jQuery triggers a stack overflow exception

I am trying to manage the resizing of a div on my website, but I am encountering a stackoverflow exception when using the resize function. Can someone please help me understand what I am doing wrong? For reference, here is a jsfiddle example: https://jsfi ...

Working with jQuery: Retrieving the ID of an element that is generated dynamically

Looking for some guidance: I'm working on dynamically creating a table based on the response from an AJAX call. The table includes headers and rows, with new rows added using the "after" function. However, I'm facing an issue with accessing the ...

How to deactivate the mobile hardware back button functionality in Ionic 2

Our team has been developing a business application and we've encountered a perplexing issue. Every time we press the mobile hardware back button, our application's GUI becomes disrupted. Despite dedicating numerous hours to finding a solution, t ...

User must wait for 10 seconds before closing a JavaScript alert

Can a JavaScript alert be set to stay open for a certain amount of time, preventing the user from closing it immediately? I would like to trigger an alert that remains on screen for a set number of seconds before the user can dismiss it. ...

Get the JSON array by decoding the JSON data in PHP

I have a JavaScript function that creates a JSON array and uses an AJAX post method. How should this JSON array be decoded on the PHP side? Here is my JavaScript function: var invoices = {invoice: [{ "customerName" : "John" ,"reciptionName" : "Doe" ,"dat ...