Tips for creating a function to assign a CSS width using a JavaScript variable?

Here is the code snippet I have been working on:

...<script>
function adjustElementSize()
{
var newSize = window.innerWidth - 600;
document.getElementById("spin").style.width = newSize + "px";
document.getElementById("spin").style.height = newSize + "px";
}
</script>
</head>
<body>
<section id="spin" onLoad="adjustElementSize()">...

I am attempting to create a function that dynamically sets the height and width of an element based on the window size using a specific formula. However, despite my best efforts and following various examples, I am struggling to make this code work. As a newcomer to JavaScript with limited knowledge, I am seeking assistance to identify any mistakes in my approach. Any guidance would be greatly appreciated!

Answer №1

I've identified an issue where the onload event for the section tag is not triggering. To fix this, you can include your JavaScript as a self-executing anonymous function at the end of the body tag.

    <body>
        <section id="spin" style="border:5px solid black;"></section>

        <script>
            (function () {
                var setWindowSize = window.innerWidth - 600;
                document.getElementById("spin").style.width = setWindowSize + "px";
                document.getElementById("spin").style.height = setWindowSize + "px";
            })();
        </script>
    </body>

For a demonstration, you can view it here: http://jsfiddle.net/T7DW6/

Answer №2

It is recommended to place the onload event in the body tag:

<body onload="handleResize()">
<section id="spinner">...

Answer №3

If you're looking to enhance your web development skills, I recommend utilizing the popular JavaScript library known as jQuery. This library is widely used across the globe. To implement jQuery in your projects, follow these steps:

function adjustElementSize(elementId) {
   var windowInstance = $(window); // Obtain window instance
   var element = $('#' + elementId); // Get element instance using jQuery
   var width = windowInstance.width();
   var height = windowInstance.height();
   // Set width and height to be equal
   if (height > width) {
      height = width;     
   } else {
      width = height;
   }
   element.css({
      width: width,
      height: height 
   });
}

// Execute this script once the document is fully loaded
$(document).ready(function(){
   adjustElementSize('spin');
});

The above function will dynamically adjust the width and height of an element to match the window size. If the height is greater than the width, it will set the width to match the height and vice versa.

If you want this resizing to occur automatically when the window is resized, add the following code:

$(window).resize(function(){
   adjustElementSize('spin');
});

Answer №4

When an object finishes loading, the onload event is triggered.

Typically, the onload event is used within the tag to run a script after a webpage has fully loaded all its content, such as images, scripts, CSS files, etc.

The onload event is only compatible with certain HTML tags, including: body, frame, frameset, iframe, img, input type="image", link, script, style

Source: event_onload

If you're considering using a tag, it might be better to use a div instead, as height and weight properties don't have an effect. To understand the difference, check out this discussion: what-is-the-difference-between-section-and-div

Answer №5

After testing your exam, I found that it functions correctly. The only modification I made was adjusting how the function is called.

   function handleSize(){
            var setWindowSize=window.innerWidth - 600;
            document.getElementById("spin").style.width=setWindowSize + "px";
            document.getElementById("spin").style.height=setWindowSize + "px";
            }

            window.onload = function () {
                handleSize();
 }

My thought is that using onLoad="handleSize()" should actually be onload="handleSize()", but I recommend avoiding this practice as it is not best practice.

Answer №6

this method is effective

<!DOCTYPE html>
<html>
<body>

<p id="demo">Press the button and observe the transformation.</p>

<button id = "myButton" onclick="myFunction()">Test it</button>

<script>
function myFunction()
{
var w = window.innerWidth;
var h = window.innerHeight;
var x = document.getElementById("myButton");
x.style.width = w + "px";
x.style.height = h + "px";
}
</script>

</body>
</html>

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

Creating interactive dialogue: the speech bubble script

I'm having trouble with my code overlapping in sections, and I just can't seem to figure out why. I've tried adjusting borders, adding padding, adjusting spaces, changing widths, reviewing the code, and even removing absolute positions, but ...

Wait for the definition of a variable before returning in React Native

I am currently receiving data asynchronously and displaying it within the render() function using {data}. My dilemma is how to ensure that the render() function waits until the variable is defined. Currently, the placeholder variable remains the same or d ...

Issue with jquery curvy corners not functioning properly on Internet Explorer 8

Check out my website at If you view the page in IE8 and then in IE7 compatibility mode, you'll notice a strange issue. The box on the right disappears in IE8 but displays perfectly rounded corners in IE7. I am currently using the jQuery Curvy Corner ...

How to create HTML buttons with CSS that maintain proper proportions?

How can I ensure that my HTML buttons adjust proportionally to different screen sizes? I've been working on coding an Android app using HTML and CSS, and everything seems to be running smoothly. However, when I share the file with a friend, he compla ...

Receiving an undefined error response when attempting to submit a form using JQuery ajax for file retrieval

Due to security issues with file manipulation, I must use an Ajax post method to request the file. The server-side URL responds with a pdf file. The Java Servlet code on the server side is as follows: ServletOutputStream out = response.getOutp ...

Optimizing Angular.js templates for faster loading using Node.js pre-compilation

As I delve into learning Angular and integrating it with my current Node.js framework, I find myself facing some challenges. Previously, I utilized Handlebars.js as my templating engine in Node.js, where I would build the context on the server side and the ...

Tips for Loading a Selected Option from an Ajax Call in Angular JS on Page Load

How do I automatically set the selected option from an ajax call when the page loads? I am fetching zones using an ajax call and I want to trigger the change function of the zones on page load in order to set the selected option of the cities select box. ...

Using Laravel to retrieve the selected value of a dynamically generated radio button through a for loop in jQuery

In my view, there is a form with dynamically populated radio buttons sourced from the database. The code snippet for this functionality is as follows: <div class="row"> @foreach($status as $s) <div class="col-md-6"> <label class ...

I'm still trying to figure out the property position. Why won't my page scroll? (My first time using HTML)

I'm having an issue with my webpage where it doesn't scroll even when the content exceeds the page length. I've tried adjusting the position settings for the body, html, and div elements but haven't seen any changes. Here is the HTML ...

Use React Router to create a link that goes to the same URL but passes along unique state

Can someone help me figure out how to open the same URL using react-router Link while passing different state each time? <Link to={items.vehicleModelId === 2 ? '/ecgo-3' : items.vehicleModelId === 3 && '/ecgo-5' ...

Concealing and revealing information with jQuery and AJAX

Need help hiding a Message and displaying an alert message after 5 seconds, but it's not working. What I want is for the Message to be hidden and show an alert message 5 seconds after clicking submit. <script> $(document).ready(function () { ...

Establishing a dynamic database feature (such as a real-time leader board) on a website

Recently, I designed a fun JavaScript game for my website and now I am contemplating adding a leaderboard feature. However, I am unsure about which type of database would be the best fit - MongoDB, SQLite, or something else entirely. I have heard that SQ ...

When I include scroll-snap-type: y; in the body tag, the scroll-snapping feature does not function properly

Hey there! I've been trying to implement scroll-snapping on my project but unfortunately, I couldn't get it to work. I tested it out on both Chrome and Firefox, but no luck so far. Here's the code snippet I've been working with, would a ...

Any recommendations for updating input in a directive without relying on $broadcast?

I am currently facing an issue with my contact list on controller A. Whenever I select a contact, the contact's information gets broadcasted to controller B and also to the datepicker directive in controller B. Although this method works, I am wonderi ...

Trouble with executing two asynchronous AJAX calls simultaneously in ASP.NET using jQuery

When developing a web application in asp.net, I encountered an issue with using jQuery Ajax for some pages. The problem arose when making two asynchronous Ajax calls - instead of receiving the results one by one, they both appeared simultaneously after the ...

Use the given URL to set the background image

Having trouble setting a background image for an <a> tag. The image link is set in the background-image:url property, but the image isn't showing up as the background. Here's my code, what could be the issue? <a href="#" data-to ...

Switching the URL without reloading the page in NEXT.JS

Currently, I am in the process of building an ecommerce store using NEXT.JS and Redux. Within the product listing page, I have incorporated a sorting select dropdown featuring options such as Price Low to High, Price High to Low, and New Arrivals. My goal ...

What is the distinction between declaring a variable as var $a=$() versus var a?

In some cases, in JQuery we assign a variable like var $a=$(), resembling the declaration of a function. I am curious to know if there is any difference if we simply define the variable as var a? ...

Modifying the style of a specific row when the form is submitted

My webpage contains nested records, with each nested record displaying a total number of clicks in a div labeled "count". I am looking to increment the count by 1 for each specific record when the button with a class of view is clicked. Currently, clicking ...

Convert a Material UI dropdown into a Bootstrap dropdown

The reason for this transformation is due to the unsightly appearance of the dropdown from Material UI. Despite that, the code is functioning properly. It features a dropdown with multiple choices, loading a list of strings and their corresponding images. ...