Search code examples
coffeescriptmootools

How to combine js lines into one?


Hi I have several js/mootools code in a coffee file that I want to combine together as in

        $$("#head").setStyle('border-right-color','#e64626');
        $$("#head").setStyle('background','#e64626');
        $$("#console").setStyle('border-right-color','#e64626');
        $$("#console").setStyle('background','#e64626');

Is it possible to combine this into one line?


Solution

  • Although what @sergio gave you is the correct answer and what you wanted, it's probably the wrong thing to do (though his answer is not at fault, its the question that is off).

    Setting element inline styles in JavaScript for effects is just not a very good practice. It has its uses in animation/fx but this does not seem to be the case. The reason is that it breaks cascading due to the high specificity and makes it much more difficult to revert, control or change afterwards. It also makes it harder to skin and restyle your app as there's a clear lack of separation of concerns, style in code is rigid.

    You need to solve this via CSS

    scenario 1: static, non mutable - not very good due to use of ID rather than classes but:

    #head, #console {
        border-right-color: #e6426;
        background-color: #e6426;
    }
    

    scenario 2: dynamic, need to differentiate elements on some event such as click, focus, mouseover - though you can solve most of these with pseudos like :focus or :hover, then abstract this into a class:

    css:

    .highlight-red {
            border-right-color: #e6426;
            background-color: #e6426;
    }
    

    javascript:

    var els = $$('#head,#console');
    
    // on whatever event... 
    els.addClass('highlight-red');
    // ... later
    els.removeClass('highlight-red');
    

    you will thank yourself later or your successor will or your client, whatever. this has the added benefit that next time you need to change styling or add more rules to differentiate, you have one place to go to. you can even add transitions / animation effects for evergreen browsers.