When it comes to utilizing the method ".style.something" in JavaScript

Here is some javascript code that I am working with:

function createDiv(id){
      var temp = document.createElement('div');
      temp.setAttribute("id", id); 
      document.getElementsByTagName('body')[0].appendChild(temp);
    }

createDiv('upper_outer');

function /*ABSTRACTION*/(e)
    {

          /* Some part of the function is functioning correctly */

          var upper = document.getElementById("upper_outer");

          upper.style.display = "block";
          upper.style.position = "absolute";
          upper.style.height = $(document).height() - init_co[0] + "px";
          upper.style.width = s_box.style.width + "px";
          upper.style.left =  init_co[0] + "px";
          upper.style.top = init_co[1] + "px";
}

I have confirmed through the dev console that the div has been successfully created with the correct id. However, there are no changes happening to the style attribute as expected. Any suggestions on what might be causing this issue? (Please disregard the variables not shown in this code, they are implemented correctly).

EDIT:

The function is being called and a portion of it is indeed working.

Answer №1

Irrespective of the resolution to your problem in traditional javascript, it's evident that a mix of jQuery and plain Javascript is being used. Given that jQuery is already integrated, why not leverage its capabilities fully? (Sounds logical, right?)

Give this a shot:

function createNewDiv(identifier)
{
    $('<div></div>').attr('id',identifier).appendTo('body');
}

createNewDiv('upper_outer');

//Assuming this div is created based on some event.
//Could it be that the event isn't triggering?
//Are all required variables like init_co and s_box defined?
function /*ABSTRACTION*/(event)
{
    $('#upper_outer').css(
    {
        'display':'block',
        'position':'absolute',
        'height':$(document).height() - init_co[0] + 'px',
        'width':s_box.css('width'),
        'left':init_co[0] + 'px',
        'top':init_co[1] + 'px'
    });
}

Please take note: Each page can have only 1 (SINGLE!!!!) ID. IDs must be unique. If this particular div with the assigned ID is being generated multiple times, there's a chance you're not altering the style of the intended div. If multiple instances are needed, using "class" would be more suitable. If not, consider checking if the element exists before creating it.

//Within createNewDiv()
if($('#'+identifier).length)) return;

Answer №2

It seems like the issue lies in not calling the function responsible for changing the style.

Additionally, there are some parameters in the function that do not appear to exist - such as s_box or init_col.

Here is a modified version of the code with the necessary parameters added:

function createDiv(id) {
      var temp = document.createElement('div');
      temp.setAttribute("id", id);
      document.getElementsByTagName('body')[0].appendChild(temp);
}

createDiv('upper_outer');
addStyle();

function addStyle()
{
      var upper = document.getElementById("upper_outer");

      upper.style.display = "block";
      upper.style.position = "absolute";
      upper.style.height = $(document).height() - init_co[0] + "px";
      upper.style.width = s_box.style.width + "px"; 
      upper.style.left =  init_co[0] + "px";
      upper.style.top = init_co[1] + "px";
}

Explore the code on jsFiddle

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

Can a for loop be implemented within a mongoose schema method?

Is there a way to modify this for loop so that it runs through the entire array instead of adding one by one? Any suggestions? EndorsedSkillSchema.methods = { async userEndorsedSkill(arr) { for (var i = 0; i < arr.length; i++) { const skil ...

Does 1 CSS point amount to the same as 75% of a CSS Pixel?

Can anyone help clarify the relationship between CSS pixels and CSS points in modern web design? I've come across information stating that one CSS point is equivalent to 3/4 of a pixel. Is this accurate? Also, is it true that we can disregard the old ...

Animating Elements with CSS and HTML

Struggling with my website project, specifically creating a login page. The issue arises when resizing the browser, causing elements to look misaligned and chaotic. Before: view image here After: view image here /* Bordered form */ form { margin-l ...

Guide on traversing to various sections within a single page with Vuetify

I attempted to use HTML anchors to achieve this: <ul> <li><a href="#dashobard">Dashboard</a></li> </ul> Here is what my target looks like: <v-card id="dashboard"> <v-card-text class="document"> Con ...

Generating JSON data from Dom elements within a specified `div` container

My goal is to extract all the elements from within a div element, which may consist of multiple inputs, checkboxes, radiobuttons etc. After that, I want to convert the id or name and value attributes into a format that can be read as JSON. I attempted to ...

An issue with npm arises on Windows 10 insider preview build 14366

It appears that npm and nodejs are experiencing issues on the latest Windows version build 1433 When I ran the following command: npm -v events.js:141 throw er; // Unhandled 'error' event ^ Error: This socket is closed. ...

The art of rotating PDF files and various image formats

Looking for a way to rotate PDF and image files displayed on an HTML page using jQuery. I attempted: adding a CSS class - without success. Here is an example code snippet: .rotate90 { webkit-transform: rotate(90deg); moz-transform: rotate(90de ...

Ways to delete a class if it currently exists?

Is there a way to manage multiple toggle classes within a single div? It can be frustrating when clicking the maximize or close button triggers the minimize function as well. How can this situation be addressed? Is there a way to manage multiple toggle cl ...

Using a variety of images to fill various shapes on a grid canvas

I'm currently working on creating a hexagonal grid using canvas, with the goal of filling each tile with a unique pattern taken from an image. However, the code I have written seems to be applying the same image pattern to every tile in the grid, resu ...

Creating a query string using a jQuery array that contains multiple values for a query variable

After writing some code to convert an array into a filter string, I noticed that the generated string was not in the format I wanted. product_size=123&product_size=456 Instead of this, I needed it to be product_size=123+456. To achieve this, I reali ...

How do I go about adding a specific class to every row within a Vue.js table?

I have an html table structured like this : <tbody> <tr v-for="employee in employees" :key="employee.EmployeeId" @dblclick="rowOnDblClick(emplo ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

Failure to trigger Ajax callback function

I am currently working on a form page that will be submitted using Ajax. The steps I have planned are: 1. Use Ajax to check if the email already exists 2. Verify if the passwords match 3. Switch to another "screen" if they do match 4. Final ...

Position Font Awesome to the right of the text in the list

Hi there, I am currently working on a project where I want to align font awesome icons to the right of my text within a list. My website is in a Right-to-Left (RTL) language and I can't seem to find any resources on how to achieve this. Any help would ...

insert information into a fixed-size array using JavaScript

I am attempting to use array.push within a for loop in my TypeScript code: var rows = [ { id: '1', category: 'Snow', value: 'Jon', cheapSource: '35', cheapPrice: '35', amazonSource ...

How can I toggle the visibility of a div based on whether a variable is defined or not?

How can I display a specific div on my webpage only when certain variables in PHP pull out a specific result from a database? I attempted to use the code snippet below, but it's not working as expected. Can someone provide guidance on how to achieve ...

Ajax is functional, however the server is not responding

After many attempts to resolve the issue with my website, I am turning to this community in hopes of finding a solution. The problem lies in the fact that while the ajax success function appears to be working and shows a status code of 200 in the network ...

The scroll-to-top arrow remains concealed when the height of the html and body elements is set to 100

I recently added a scroll-to-top arrow using Jquery, and it's functioning flawlessly. However, I encountered an issue when I set body and html to a height of 100%, as it mysteriously disappears. View this fiddle for reference The HTML structure is a ...

Handling memory in javascript jquery mobile using phonegap

I have encountered an issue while building a jQuery Mobile + PhoneGap app for iOS. The app functions correctly on a web browser, but when bundled with PhoneGap and tested on a phone, it starts to forget JavaScript functions. For instance, panels that shoul ...

Troubles encountered during the development of Nextjs/Javascript application

I encountered the following errors while developing my application. I am unsure of the reason behind this issue. I created a fetch request in a separate function and attempted to call this fetch function (which is structured as a custom react hook) within ...