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: