The margins within the div of the new tab are not applying as expected

Greetings! Currently, I am in the process of generating a dynamic form within a new tab using JavaScript. For some reason, the margin effects on the div element are not being applied correctly. Despite my attempts to set the margins using both classes and IDs in CSS as well as through div.setAttribute, they do not seem to take effect as expected. Here is the snippet of code that I am working with:

var openWindow = window.open('dynForm.html','_blank','');
    var windoc=openWindow.document;
    windoc.write("This is dynamic form ");
    var div=document.createElement("div");
    div.setAttribute("style","border:solid; margin-left:1cm; margin-right:1cm; margin-bottom:1cm; margin-top:1cm; background-color:lightblue;");

Right now, only the background color appears to be applying correctly in the new tab. Regardless of the specified margin values, the layout looks consistent. You can view how it appears by following this link to the screenshot provided: https://i.sstatic.net/laIdN.png

Question 2: Interestingly, even though I have defined classes and IDs in my CSS file, they do not seem to be properly applied to the div element.

#myDIV2{
    background-color:lightblue;
}

I attempted setting an ID using div.id="myDIV2";

Additionally, I also tried div.setAttribute("id","myDIV2"), but unfortunately, the outcome remains the same. The classes applied did not yield any noticeable changes in the display. I'm not quite sure what could be causing this issue or where I may have gone wrong. Any assistance would be greatly appreciated.

Answer №1

Make sure to combine your styles before setting the style attribute in order to avoid overriding them every time you call setAttribute:

var openWindow = window.open('dynForm.html','_blank','');
    var styles= [
      "border:solid;",
      "margin: 1cm;",
      "background-color:lightblue;"
    ];
    var windoc=openWindow.document;
    windoc.write("This is dynamic form ");
    var end_styles = "";
    for (var i=0; i<styles.length;i++) {
        end_styles += styles[i];
    }
    var div=document.createElement("div");
    div.setAttribute("style", end_styles);

Note: the fiddle won't work on stackoverflow, I used it because it's easier to format code

Answer №2

The reason for this occurrence is that your style attributes are being overridden by the previous use of div.setAttribute, and only the last attribute

div.setAttribute("style","background-color:lightblue");
is being applied. To avoid this, consider applying all styles at once using
div.setAttribute("style","style1:value1;style2:value2;style3:value3;");

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

Avoid the need for users to manually input dates in the Custom Date Picker

After referencing this custom Date picker in ExtJs with only month and year field, I successfully implemented it. However, I am facing an issue where manual entry into the date field is not disabled. My goal is to restrict input for that field solely thr ...

Guide on sending information using ajax using a button within a form

I've been working on creating a form that utilizes HTML5 validations and integrates Ajax to show the status of mail sending. However, I'm facing an issue where clicking the send button does not initiate the expected action. Form HTML: <div c ...

Utilizing Zend JSON encoding for seamless integration with JavaScript

I'm currently working with the Zend Framework. My objective is to pass JSON data from the controller to JavaScript. I have a simple array: $array = array('a' => 1, 'b' => 2); After encoding this array into JSON format: ...

Create an interactive HTML5 drag-and-drop interface that restricts the dropping of nested elements to only within form fields. This functionality is achieved

I have implemented Sortable.JS in a form builder to enable drag and drop functionality. My goal is to allow users to drag sections (which is mostly working) and questions within those sections, either within the same section or into other sections. The is ...

What is a way to automatically run a function at specific intervals in PHP, similar to the setTimeout() function in JavaScript?

I have a JavaScript code snippet that looks like this: setTimeout('$.ajaxCall("notification.update", "", "GET");', 1000); Now, I want to execute the following PHP function every 1000 milliseconds, similar to the above JavaScript code: $notific ...

Choosing the subsequent div after the current one using Jquery

I am currently in the process of creating a drop-down menu button that, when clicked, reveals the previously hidden div underneath it. The code is functioning properly without the use of $(this).next, but it is displaying all divs with the class .menudrop ...

Creating a String Array and linking it to an Input Field

I'm currently working on a code that involves mapping through an array of strings using observables. My objective is to display the value from this array inside an input field. However, despite being able to view the array in the console, I encountere ...

Emphasizing the date variable within a spreadsheet

Hey there! I'm struggling with the code below: <html> <head> <title>highlight date</title> <style> .row { background-color: Yellow; color:blue; } </style> <script type="text/javascript"> </script> &l ...

What is the best way to monitor a Vue instance property within a component?

I recently implemented a plugin that introduces a new property to the Vue instance. This property can then be accessed within components using this.$plugin.prop. However, I am encountering difficulty in watching for changes to this property. I need to perf ...

Move the material ui menu to the far left side of the page

How can I adjust the menu to align with the left side of the page without any gaps? I've tried various methods but it's not moving to the left. Any suggestions? Here is the relevant code snippet: <Menu an ...

Can you provide a succinct explanation of what constitutes a well-defined "landing page"?

Could someone provide a clear and concise explanation of what exactly constitutes a landing page and how it should be utilized? I'm struggling to grasp the concept. Where is the optimal placement for a landing page on a website? Is it best placed o ...

Creating a vertical line at the bottom using CSS

Is it possible to add a centered line to the bottom of the "numberCircle" in a responsive table created with twitter-bootstrap? I would like it to look like this image: Thank you .numberCircle { border-radius: 50%; width: 50px; height: 50px; ba ...

Center align for drop-down menu

I'm currently working on styling an asp:DropDownList element using custom CSS. I have successfully set the height, but I am facing a challenge with getting the text to align in the middle of the element rather than at the bottom. The vertical-align:mi ...

Guidelines on navigating a blank page using the Nuxt-js method

I have run into an issue in my Nuxt.js project where I need to open a link in a new target when a user clicks a button. Despite trying various solutions, I haven't been able to find a workaround within the Nuxt.js framework itself. <a :href=&qu ...

Enhance your React application by making two API requests in

Below is the React Component that I am working on: export default function Header () { const { isSessionActive, isMenuOpen, isProfileMenuOpen, setIsMenuOpen, closeMenu, URL } = useContext(AppContext) const [profileData, setProfileData] = useState({}) ...

Prevent the Rain from descending

Looking for a way to toggle a particle emitter on or off, I've encountered memory leaks with my Reactjs code that generates rain/snow particles using the canvas element. Despite attempts to stop the animation properly, it seems to be projecting a new ...

Tips for finding group words within a div panel

Check out this interactive demo I created to demonstrate what I need help with. There are multiple panels containing words, each separated by a line break. I am trying to create a filter that will hide panels that do not match the words entered in the sea ...

How to alter row colors in SQL/PHP tables

echo "<tbody"; echo "<tr>"; echo "<td>{$id}</td>";// display customer Id echo "<td> {$firstname} {$lastname}</td>"; //display customer title,firstname,lastname echo "<td>{$date->format('h:i A')}</td> ...

Issue with uncaught exceptions in promise rejection test

I am experiencing an issue with the following code: function foo(){ bar().catch(function(){ //do stuff } } function bar(){ return promiseReturner().then( function(result){ if(_.isEmpty(result)){ throw "Result is empty"; ...

AngularJS postback method fails to trigger

Seeking assistance with my angularJS AJAX postback method. Below is the HTML code I have created: <html xmlns="http://www.w3.org/1999/xhtml" ng-app> <head runat="server"> <title></title> <script src="Scripts/angular.js ...