A helpful tip for dynamically adjusting the canvas size is to utilize its height and width attributes to resize it whenever it undergoes a change

I am encountering an issue with the canvas element in my code. The canvas is supposed to update whenever its containing div is resized.

window.addEventListener('resize',function()
{
    let mapwidth = $('.canvas').attr("width")
    let mapHeight = $('.canvas').attr("height")

    console.log(mapwidth ,mapHeight)
    

    $('.canvas').css("width",mapwidth);
    $('.canvas').css("height",mapHeight);
});
canvas
{
  border: solid black 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas class="canvas" tabindex="0" width="511" height="333" style="position: absolute; left: 0px; top: 0px;"></canvas>
<br>
<canvas class="canvas" tabindex="0" width="232" height="1333" style="position: absolute; left: 0px; top: 0px;"></canvas>

However, the current output shows only 0 for both width and height of the canvas.

  1. The main question I have is how can I retrieve the current height and width of the canvas within the inline style attribute.
  2. Additionally, I would like to apply different heights and widths to each canvas element based on their individual attributes rather than applying the same dimensions to all canvases.

Answer №1

For the purpose of iterating over each element with the class .canvas, you will need to utilize the jQuery selector ($(".canvas")) to target all instances of this class. Subsequently, you can loop through these elements using the .each() method.

Here is an example:

$(".canvas").each(function()
{
    console.log(this.height, this.width);
});

The code above will output the current width and height for every .canvas element.

Moreover, you can include conditional logic based on specific attributes, like so:

$(".canvas").each(function()
{
    console.log(this.height, this.width);
    if ($(this).attr("height") > 50)
    {
        console.log("Greater than 50.");
    }
    else
    {
        console.log("Not greater than 50.");
    }
    // Alternatively, you can use the ternary operator to shorten the previous if statement:
    // $(this).attr("height") > 50? console.log("Greater than 50."): console.log("Not greater than 50.");
});

Below is a demonstration of the initial code snippet - please resize the page to observe its functionality.

window.addEventListener('resize',function()
{
    $(".canvas").each(function()
    {
      console.log(this.height, this.width, "these are the values set for the physical canvas space")
      $(this).css("height", 100 + "px")
      console.log(this.style.height, this.style.width, "these are the physical inline styles for each of the canvas elements; notice width hasn't been set yet.");
      // there are 3 ways you can set width - the first one is the same way we set height:
      // $(this).css("width", 100 + "px");
      // the second will let you set the !important flag, if you need to (which is my preference):
      // this.style.setProperty("width", value);
      // this.style.setProperty("width", value, "important");
      // lastly, you could do (I think):
      // this.style.height = value;
    });
});
canvas
{
  border: solid black 1px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<canvas class="canvas" tabindex="0" width="511" height="333" style="position: absolute; left: 0px; top: 0px;"></canvas>
<br>
<canvas class="canvas" tabindex="0" width="232" height="1333" style="position: absolute; left: 0px; top: 0px;"></canvas>

EDIT 1:

I suspect that the event listener may be added twice in this code snippet not due to the code itself, but perhaps because the SO page preloads the snippet?

EDIT 2: There are several options available for defining the inline styles - here they are:

  • Consider this option ->
    $(this).css("width", 100 + "px");
  • This alternative -> allows you to set the !important flag if necessary
    • this.style.setProperty("width", value);
      (ensure units are included)
    • this.style.setProperty("width", value, "important");
      (ensure units are included)
  • Another choice for inline styling might be -> this.style.height = value; (include units)

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

Enhancing HTML "range" element with mouse scroll functionality for incrementing values in step increments

I'm working on developing a scroll feature that operates independently from the main window's scrolling function. I aim to trigger specific events in the primary window based on interactions with this separate scrollbar. The only solution I coul ...

Having trouble with the GitHub publish action as it is unable to locate the package.json file in the root directory, even though it exists. Struggling to publish my node package using this

I've been struggling to set up a publish.yml file for my project. I want it so that when I push to the main branch, the package is published on both npm and GitHub packages. However, I am facing difficulties in achieving this. Here is the content of ...

Deleting tags using jQuery

I've attempted multiple iterations of the "unwrap" method, yet I consistently receive an error message stating that unwrap is not a function. How can I eliminate the b tags in this scenario? <div id="top_left"> <font size="3"> ...

Ways to correct the issue of multiple <div>s overlapping each other after being rotated by 90 degrees

Can someone assist me with rotating multiple divs without them overlapping? Below is a simplified version of my code: <div> <div class="rect"></div> <div class="rect"></div> <div class="rect"></div> & ...

Using jQuery's .load() method to load a PHP file can result in an exponential increase in XHR finished loading time with each subsequent load

There seems to be an issue with my code using .load() to load a PHP page into a div whenever the navbar or link is clicked. After multiple clicks, I noticed that the "XHR finished loading" increases exponentially and it appears that the same PHP file is be ...

Unable to retrieve data upon page refresh in Next.js

I encountered an issue while trying to develop a basic Next.js page using data fetched from the backend. I am utilizing useSWR for fetching the data. When I refresh the page or load it for the first time after running in development mode, I face a TypeScr ...

What causes the AJAX JSON script to output an additional 0?

Within my WordPress website, there is an AJAX function that reaches out to a PHP function in order to retrieve a specific value from a transient record stored in the Database. Whenever I trigger this function with jQuery, I successfully receive the result ...

Issue with aligning items vertically using CSS and Javascript

I must admit, I am not well-versed in CSS. My goal is to create a performance bar using CSS and Javascript. So far, I have managed to generate a background bar with another bar inside that fills up to a specific percentage. However, my issue lies in the fa ...

Storing Array Data in Angular $scope (Javascript)

I am currently altering the Altair Material Design Template and incorporating an Angular JS controller. After successfully calling an API and creating variables in a for loop, I intend to write them to $scope.dragulaItems. While this process seems to work ...

What causes the unexpected behavior of __filename and __dirname after being minified by webpack?

Could someone offer some insight into a strange issue I've encountered? In my project, the structure is as follows: index.js src/ static/ favicon.ico styles.css server.js routes.js app.jsx //[...] dist/ /sta ...

Removing extra spaces from a hyperlink using CSS

Can CSS be used to remove extra whitespaces? Within the code snippet provided, there is an additional whitespace in the <a> tag. This link is generated by a WordPress plugin and I prefer not to make changes directly to the source files of the plugin. ...

Angular 7: An unexpected error occurred when trying to inject TripsMenu into MenuWidgetComponent in AppModule

Encountering an issue in angular 7, where I am trying to inject my MenuWidgetComponent in the home component. I have imported it in the widget component and exported it via index.ts. However, the following error persists: I searched online but couldn&apos ...

Manipulating CSS content property in React using Material UI

I am trying to set content: "" on my i element: "& i::before": { content: "" }, "& i::after": { content: "" }, However, the style is not being applied and I am seeing an ...

Jquery Visualization Chart not displaying

I am struggling to get the jquery visualization to work properly. Although the table and caption appear fine, there is no data showing up in the chart. I've carefully followed the example and searched for any issues, but I can't identify what&apo ...

Create a streaming service that allows for multicasting without prematurely ending the main subject

In my implementation of caching, I am utilizing BehaviorSubject and multicast. The cache stream should begin with an HTTP request and I want the ability to manually trigger a cache refresh by calling next on the subject. While the conventional method of us ...

Set the background color of the Material UI Drawer component

Need some advice on changing the background color of Material UI's Drawer. I've attempted the following approach, but it's not producing the desired result. <Drawer style={customStyle} open={this.state.menuOpened} docked={false} ...

What is the best way to add flair to the HTML <title> tag?

Just a quick question - I'm wondering if there is a method to apply CSS styles to an HTML element. Here's an example declaration: title { color: red; font-family: 'Roboto', sans-serif; } ...

What is the most effective way to transfer visitor hits information from an Express.js server to Next.js?

I've developed a basic next.js application with an express.js backend. What I'm aiming for is to have the server track hits every time a user visits the site and then send this hit count back to the next.js application. Check out my server.js cod ...

Steps for resetting data() on a route without parameters:

Having trouble restarting a route on a new editor I have a specific route /editor as well as /editor?_id=dasd448846acsca The /editor route consists of a simple form with empty inputs, while the /editor?_id=dasd448846acsca route has the same component bu ...

Tips for stopping html form from refreshing upon submission

Hello, despite extensive searching and testing, I am still unable to locate the issue and therefore I am reaching out to seek your assistance in resolving my problem. Within a form that I have created, upon clicking the submit button, a javascript functio ...