Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
141
rated 0 times [  148] [ 7]  / answers: 1 / hits: 55670  / 12 Years ago, thu, may 3, 2012, 12:00:00

I was just trying to do the following in jQuery:



var newCanvas = $('<canvas/>',{'width':100,'height':200,'class':'radHuh'});
$(body).append(newCanvas);


This is working (kind of) and generates the following markup:



<canvas style=width:100px; height:200px; class=radHuh></canvas>


As most of you might know canvas elements don't really like CSS dimensions but expect a width and height attribute, so this object creation failed for me.



I do know I could just do:



var newCanvas = $('<canvas/>',{'class':'radHuh'}).attr({'width':100,'height':200});


instead, but I was just wondering nonetheless if there is any way of telling jQuery that width and height should be treated as attributes when creating the element via $('element',{attributes}) and not as CSS?


More From » jquery

 Answers
91

jQuery try to match each attribute name with a jQuery function name. Matched functions are called.



width and height are jQuery functions, so your original code is equivalent to this:



  var newCanvas = 
$('<canvas/>',{'class':'radHuh'})
.width(100)
.height(100);


width(value) and height(value) functions set CSS width and height of an element.






Relevant jQuery source code line (https://github.com/jquery/jquery/blob/master/src/attributes.js#L308)



if ( pass && name in jQuery.attrFn ) {


attrFn object definition (https://github.com/jquery/jquery/blob/master/src/attributes.js#L288):



attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},

[#85819] Wednesday, May 2, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leifw

Total Points: 88
Total Questions: 103
Total Answers: 103

Location: France
Member since Thu, May 6, 2021
3 Years ago
;