Aaron Brewer Aaron Brewer - 2 months ago 5
Javascript Question

How Can I Compact This jQuery Code?

How can I compact the jQuery Code Below?

//FIRST CODE
jQuery('.expand-two').click(function(){
jQuery('.content-two').slideToggle('fast');
});
jQuery('.expand-two').toggle(function() {
jQuery('.content-two').slideDown('slow');
jQuery(this).find("img").css({
"-webkit-transform": "rotate(90deg)",
"-moz-transform": "rotate(90deg)",
"filter": "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"
});
}, function() {
jQuery('.content-two').slideUp('slow');
jQuery(this).find("img").css({
"-webkit-transform": "rotate(0deg)",
"-moz-transform": "rotate(0deg)",
"filter": "progid:DXImageTransform.Microsoft.BasicImage(rotation=0)"
});
});
//SECOND CODE
jQuery('.expand-three').click(function(){
jQuery('.content-three').slideToggle('fast');
});
jQuery('.expand-three').toggle(function() {
jQuery('.content-three').slideDown('slow');
jQuery(this).find("img").css({
"-webkit-transform": "rotate(90deg)",
"-moz-transform": "rotate(90deg)",
"filter": "progid:DXImageTransform.Microsoft.BasicImage(rotation=1)"
});
}, function() {
jQuery('.content-three').slideUp('slow');
jQuery(this).find("img").css({
"-webkit-transform": "rotate(0deg)",
"-moz-transform": "rotate(0deg)",
"filter": "progid:DXImageTransform.Microsoft.BasicImage(rotation=0)"
});
});


How would I be able to have multiple DIV Classes plugged into one line? Without having to have so much code for each and every snippet?

Thank you so much!

Answer

One idea I see - make some function for element rotating - eg.

function setRot( jqElm, angle ) {
    var angleIe = Math.round( angle / 90 );
    jqElm.css({
        "-webkit-transform": "rotate(" + angle + "deg)",
        "-moz-transform": "rotate(" + angle + "deg)",
        "filter": "progid:DXImageTransform.Microsoft.BasicImage(rotation="+ angleIe +")"
    });
}

Then in code make this

setRot( jQuery(this).find("img"), 90 );

Second thing you can do is to use multiple selectors ( if it is possible ) by querying with comma -

jQuery('.expand-two, .expand-three' )....
Comments