Immediately set the width attribute of an HTML element using JavaScript

Can an element's width be dynamically set using the following code:

<img id="backgroundImg" src="images/background.png" alt="" width="javascript:getScreenSize()['width']+px" height="1100px"/>

In this code, getScreenSize() is a JavaScript function.

        function getScreenSize()
        {
            var res = {"width": 630, "height": 460};

            if (document.body) 
            {
                 if (document.body.offsetWidth)  res["width"]  = document.body.offsetWidth;
                 if (document.body.offsetHeight) res["height"] = document.body.offsetHeight;
            }

            if (window.innerWidth)  res["width"]  = window.innerWidth;
            if (window.innerHeight) res["height"] = window.innerHeight;
            alert( res['width'] );

            return res;
        }

Alternatively, should the img's width be adjusted within a JavaScript function?

function changeImgWidth( img )
{
   img.offsetRight = getScreenWidth()['width'] + "px";
}

Answer №1

Using that particular syntax won't work for this task. One option is to utilize the document.write method, but it's recommended to wait until after the DOM has loaded. This is because the accuracy of your getScreenSize function may be compromised otherwise (though testing will confirm).

To implement using document.write:

<script>
document.write('<img id="backgroundImg" src="images/background.png" alt="" width="' + getScreenSize()['width'] + '" height="1100px"/>');
</script>

To execute after the DOM loads, place this code at the very end of your page, right before the closing </body> tag:

<script>
document.getElementById('backgroundImg').width = getScreenSize()['width'];
</script>

In both instances, focus remains on the width attribute (without a unit suffix like "px"). However, consider utilizing the CSS width property (which requires the suffix) as an alternative.


Instead of depending on JavaScript for setting the width, exploring CSS options is advised. You can make the image stretch 100% within its container by including style='width: 100%' within the tag or specifying:

#backgroundImg {
    width: 100%;
}

...within a stylesheet.

Answer №2

It is unnecessary to include "+px" in the image tag.

Answer №3

It is always recommended to separate content (HTML) from behavior (javascript) for better code organization and maintainability. A good example of this is avoiding using inline javascript like

onclick='somefunction(); return false;'

inside HTML elements, such as links. Instead, utilizing libraries like jQuery allows you to define event handling in a more structured way, like so:

$('#somelink').click(function() {//do something});

within a

$(document).ready(

block. This way, all the javascript logic can be centralized and managed efficiently, rather than being scattered throughout the markup. The same principle applies to CSS stylesheets versus inline styles - keeping styles separate ensures cleaner and more organized code.

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

The property 'filter' is not recognized on the 'Object' type. An attempt to filter the response was made

Trying to fetch data from a JSON file that matches the player's name in the URL, such as localhost:4200/players/Febiven, should only retrieve information about Febiven. The code is written in Angular 6. The current code snippet is as follows: player ...

looking to retrieve the corresponding value of a specific array key

I am trying to determine the value of a complex array, but I keep getting values like 0,1,2,3,4,5 as answers. Here is the code snippet I am using to retrieve the state value of the array: var shardState = Object.keys(mydata.cluster.collections[collection ...

substitute tags

Is there a way to change the tagName of a tag using jQuery? For example, if I have an HTML document and I want to replace all 'fieldset' with 'div'. Any suggestions would be appreciated! ...

Encountered a Webpack issue when trying to load the primeng.min

I recently initiated a fresh project using yo aspnetcore-spa. My goal is to integrate the PrimeNG component library. Upon installing font-awesome and primeng: npm install font-awesome primeng --save I included CSS in the webpack vendor list: vendor: [ ...

What is the best way to retrieve a value from a database and display it in a radio

Can you help me figure out how to implement this functionality? I have a database with a "boolean" field that stores 0 or 1 values. On an HTML page, there is a radioButton with options for OK or NO. I need to dynamically load the boolean value from the dat ...

Is there a way to create a navigation menu that highlights as we scroll down the page?

Check out this example of what I am looking for. https://i.stack.imgur.com/fdzvZ.png If you scroll, you will notice that the left menu highlights. Sub-menus will extend when the corresponding menu is highlighted and collapse when other menus are highlig ...

Sending input values to controller action parameters in CakePHP

I am working on an HTML form in which I need the URL output to be structured as follows: "example.com/mycontroller/action/mike/apple" Upon submitting the form using "post" method, the form values are not visible and can only be accessed through "_POST" ...

Duplicate text content from a mirrored textarea and save to clipboard

I came across some code snippets here that are perfect for a tool I'm currently developing. The codes help in copying the value of the previous textarea to the clipboard, but it doesn't work as expected when dealing with cloned textareas. Any sug ...

Tips for displaying diverse content in a DIV container when users click on various sections of an image

Apologies for the unclear title, but I'm struggling to explain my technical goal using jargon. The basic concept is this: there will be an image on the webpage, and when a user clicks on a specific area of the image, relevant information will appear ...

Which names can be used for HTML form tags in jQuery?

Recently, I encountered an issue related to jQuery form serialization which stemmed from naming a form tag "elements". The problem arose when using jQuery $(’form’).serialize(). Here is an example of the problematic code: <form> <input name=" ...

Find the index of the class that contains the specified element

How can I search indexOf in an array of elements with only one specific element from the same class? class Dhash { constructor(Dlable, tophash) { this.Dlable = Dlable; this.tophash = tophash; } } let listohashs = []; listohashs[0] = new Dhash(0 ...

adjust the size of the textarea to perfectly fill the available space

I want my textarea within the wrapctxt container to always fill up the remaining space below the wrapctop section, reaching the bottom of the wrapc element. .panelb{ display:grid; grid-template-columns: 130px 34% auto; height:100vh; width: ...

State is not being updated by useState after the second API call in MUI and ReactJS

I encountered an issue while using the Material-UI Autocomplete component for a search box. The problem arises when fetching options from an API and passing them to the component. Initially, the dropdown displays the options correctly. However, upon closin ...

What level of consistency does the canvas.toBlob() method maintain across various web browsers?

Looking into converting Canvas contents to a Blob, I wanted to explore the support of the native method canvas.toBlob() across different browsers. How reliable is this method in various browser environments? Unfortunately, information about this isn't ...

Creating an overflow effect for sliders using only CSS

Is it feasible to develop a slider that extends beyond its parent elements and the body? The concept involves having content within a section housed in a container. The slider would be part of this section, with slides overflowing past the parent element ...

What is the best way to incorporate products as components into the cart component?

ProductCard import React from 'react'; import { Card, Container, Row, Col, Button} from 'react-bootstrap'; import Cart from './Cart'; import './ItemCard.css'; function ProductCard(props){ return( <Car ...

Utilize JavaScript array to filter, match, and perform calculations based on dates and names

I am working with the following dataset: const data = [ { "employee_name": "Employee A", "commission_date": "14/05/2018", "commission_price": 9000 }, { "employee_name": "Employee A", "commission_date": "17/05/2018", "commissi ...

Refreshing the form upon submission

The form provided below may include various elements such as text fields, drop-down menus, and selection boxes, enabling the user to update their profile. The MySQL fields are updated after the form is submitted. <form method="post"> My Name: <in ...

Initiate an animation upon reaching a designated element using Jquery scroll event

Hey there! I've been trying to create an animation without using any plugins, but unfortunately, I haven't had much luck so far. Here's the code I've been working on. If anyone can help me figure this out, I'd really appreciate it ...

Creating a personalized HTML email template with a TypeScript foreach loop

As I work on developing an app, users will have the opportunity to share product information via email. Each product includes a title, image, description, ingredients, and a list of energy values. Currently, I am able to send an email with all the product ...