Adjust the size of a Div/Element in real-time using a randomly calculated number

Currently, I am working on a script that is designed to change the dimensions of a div element when a button on the page is clicked. The JavaScript function connected to this button should generate a random number between 1 and 1000, setting it as both the width and height of the div. While the Chrome inspector shows that the attribute changes are being made, the actual content on the page does not reflect these updates.

<button onclick="myFunction()">Try it</button>
<div id="block" style="background-color:blue;">
</div>
function myFunction() {
    document.getElementById("block").setAttribute("width", Math.floor(Math.random() * 1001) + "px" );
document.getElementById("block").setAttribute("height", Math.floor(Math.random() * 1001) + "px" );
}

For more detailed information and testing, refer to the following jsfiddle link: http://jsfiddle.net/NR2k6/118/

Answer №1

Changing the appearance of the element, rather than its properties, is what you're aiming for:

let box = document.getElementById("container");
box.style.width = Math.floor(Math.random() * 800) + "px";
box.style.height = Math.floor(Math.random() * 600) + "px";

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

Error: JQuery's on() function is not defined

After modifying the code in the original and changed code boxes, I'm now encountering an Uncaught Type error: Undefined is not a function. Any thoughts on why this might be happening? Thanks Original: $('.comment').click(function(e){ ...

Discover the best practices for utilizing the npm commands.test function

Looking to create a function that can return the output from running npm test. (this function can be called as npm.commands.test(packages, callback) here) Attempted to use it in this way: var npm = require("npm"); npm.load('', function(err, np ...

Trouble with CSS3 Menu Layout and Gradient Display Issues

My task is to replicate this menu: I'm having trouble creating the gradient. Completed Why can't I see it in my code? http://jsfiddle.net/Vtr6d/ Here's what I currently have: CSS: .mainOptions{ float:left; margin:0 20px 0 20px; ...

The value of the checked input with the name `nameofinput` is currently not defined

I'm having trouble passing the input value to another page. $( this ).attr( "href", '?module=module_progress_report&Subject='+ $('input[name=subject]:checked').val()+ '&Centre_Selected_ID='+ encodeURIComponen ...

Having trouble centering my menu bar on CSS, can anyone help?

I'm having trouble getting the buttons inside the menu bar to align properly. Does anyone have any suggestions on how to fix this? I'm not very experienced with coding, so any assistance would be greatly appreciated! .main-navigation { clear ...

Navigating through async functions in an Express.js router

Encountered a lint error indicating that Promises cannot be returned in places where a void is expected. Both functions [validateJWT, getUser] are async functions. Any suggestions on how to resolve this issue without compromising the linter guidelines by u ...

What method can be employed to eliminate choice selection lacking any value?

Currently, I am encountering difficulties in my attempt to remove or hide the first option value from a ransack code. Would you be able to assist me in addressing this concern? Here is the HTML CODE that I am working with: <select id="q_c_0_a_0_name" ...

Is there a way to change an HTML document into a Word file?

I am looking for recommendations on libraries that can help me save HTML documents in memory as Word .DOC files. Any suggestions for both closed and open source options are welcome. Additionally, could someone provide links to these libraries based on the ...

New feature: Material UI Chip Input with floating input label

I installed material-ui-chip-input to implement tags in an input field. I wanted a label alongside it, so I utilized the default Material UI label for consistency with other inputs. However, the input doesn't shrink as expected when clicked on by the ...

Unexpected error occurs when modifying HTML5 video source using JQuery on Internet Explorer

Currently, I am working on developing a web application using asp.net, Bootstrap, and JQuery. While testing it on LocalHost, I encountered an issue that needs debugging. The navigation bar of my application has a dropdown menu with links to tutorial video ...

The unit argument provided for Intl.NumberFormat() is not valid for electrical units such as volts and joules

After attempting to localize my web application, I have run into an issue with Intl.NumberFormat not working properly with electric units such as ampere, ohm, volt, and joule. The documentation provides examples and a list of available units. Despite fol ...

Transferring session data through AJAX in PHP

I'm currently developing an app using PhoneGap. However, PhoneGap only supports HTML, CSS, and JS, not PHP. This led me to the workaround of placing the PHP file on a remote server and using AJAX to call it via the server's URL. My issue now is ...

Validating data with Joi can result in multiple error messages being displayed for a single field

I'm attempting to implement a validation flow using the joi package, which can be found at https://www.npmjs.com/package/joi. 1) First, I want to check if the field category exists. If it doesn't, I should display the error message category requ ...

Implement a loading spinner to display each time a computed method is invoked in a Vue.js

Whenever a checkbox is checked, my filtering method gets triggered. I am trying to implement a loader that displays while the filter process is ongoing and then shows the results. However, I have encountered an issue where the loader remains visible at all ...

What is the best way to trigger a jQuery function when an option is selected from a Select2 dropdown menu?

I have implemented Select2 for custom dropdown styling. The options are structured like this: <option value="001,100">Option 001</option> <option value="002,200">Option 002</option> <option value="003,300">Option 003</opti ...

The "useState" React Hook is restricted from being used in a class component. To utilize React Hooks, they can only be invoked within a React function component or a custom React Hook function

I am relatively new to React frontend development and I am currently working on adding a temporary drawer to my Material-UI NavBar. Here is the code snippet where I added the drawer: class Navbar extends Component { render() { const { authentic ...

Adjusting the size and location of the current browser window using jQuery

Is there a way to modify the height, width, and position of the browser window using jQuery's document.ready() function? ...

Is there a way to adjust the placement of the h1 tag using the before pseudo-element?

I'm looking to place an image on the left side of each h1 tag. I've been attempting to utilize the before pseudo element for this task. The issue arises when there is no content, causing the before pseudo element to overlap with the h1 tag. How ...

Transfer data in an array within value="" separated by ':' through AJAX/JSON in PHP and HTML

Can data be passed in array form using AJAX/JSON? For example, like ".$row['departmentname'].":".$row['jobposition'].":".$row['deptcode']."? Here is a sample code snippet to illustrate this: if(sqlsrv_num_rows($query) > 0 ...

What is the best way to convert JavaScript to JSON in Python programming?

I encountered a situation where I have an HTML page that contains a lengthy product list, making it too large for me to upload. The products are stored within the script section of the page, specifically in one variable. Initially, I mistook this data for ...