Computed attributeName in jQuery.attr () multiple methods?

I am wondering why this works:

var $blur = $("#blur"),
    blH = $blur.height();
    blHS = $blur.height() + 1;
    $blur.attr('data--' + blH + '-top', 'filter: blur(5px)');
    $blur.attr('data--' + blHS + '-top', 'filter: blur(0px)');

      

but this is not the case:

var $blur = $("#blur"),
    blH = $blur.height();
    blHS = $blur.height() + 1;
    $blur.attr({
        'data--' + blH + '-top': 'filter: blur(5px)',
        'data--' + blHS + '-top': 'filter: blur(0px)'
    });

      

Chrome says:

Unprepared SyntaxError: Unexpected token +

and Firebug says:

SyntaxError: missing: after property id

I don't know what is the correct syntax!

I cannot figure it out and I really appreciate any help.

+3


source to share


2 answers


you had Javascript syntax error, computed property name is not supported yet, but it will be in ECMA6

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer



if you really want to do the second way, this is how you do it

var attrs = {};
attrs['data--' + blH + '-top'] = 'filter: blur(5px)';
attrs['data--' + blHS + '-top'] = 'filter: blur(0px)';

$blur.attr(attrs);

      

+2


source


Because you cannot use this syntax as an Object property. You can use this:

var obj = {};
obj['data--' + blH + '-top'] = 'filter: blur(5px)';
obj['data--' + blHS + '-top'] = 'filter: blur(0)';
$('footer').attr(obj);

      

Note that when you get the value $blur.height()

, you can use the cashhed value instead of calling it again, I mean this:



var $blur = $("#blur"),
    blH = $blur.height();
    blHS = blH + 1;

      

Instead:

var $blur = $("#blur"),
    blH = $blur.height();
    blHS = $blur.height() + 1;

      

+1


source







All Articles