Search code examples
javascriptjqueryhtmlminimize

How to minimize code in jQuery


This may be a weird question, but i didnt find a solution for thiw anywhere. My question is simple, how can i minimize / optimalize code like this? Can this be done with some function or loop. I dont want to have like 500 lines in simple jQuery code like this.

var span1w = $("span", panel1).width();
var span2w = $("span", panel2).width();
var span3w = $("span", panel3).width();
var span4w = $("span", panel4).width();

var span1 = $("span", panel1);
var span2 = $("span", panel2);
var span3 = $("span", panel3);
var span4 = $("span", panel4);      

$(span1).css("margin-left", "-" + span1w / 2 + "px");
$(span2).css("margin-left", "-" + span2w / 2 + "px");
$(span3).css("margin-left", "-" + span3w / 2 + "px");
$(span4).css("margin-left", "-" + span4w / 2 + "px");

My HTML is just this with a bunch of JS under it. What im trying to do is center the span element by getting the width and using a simple css.

<body id="body">
    <img src="images/logos2.png" alt="KOP-KA logo Martin Mali" class="logo">
    <div id="web" class="uk-grid uk-width-1-1">
        <div class="uk-width-1-4" id="panel1">
            <canvas class="canvas"></canvas>
            <span>SNAKE</span>
        </div>
        <div class="uk-width-1-4" id="panel2">
            <canvas class="canvas"></canvas>
            <span>APP</span>
        </div>
        <div class="uk-width-1-4" id="panel3">
            <canvas class="canvas"></canvas>
            <span>????</span>
        </div>
        <div class="uk-width-1-4" id="panel4">
            <canvas class="canvas"></canvas>
            <span>O KOP</span>
        </div>           
    </div>

This is my CSS.

#panel1,#panel2,#panel3,#panel4{
    transition: background-color 0.6s linear;
    -moz-transition: background-color 0.6s linear;
    -o-transition: background-color 0.6s linear;
    -webkit-transition: background-color 0.6s linear;      
}

#panel2{
    border-left:1px solid rgba(32,145,216, 0.3);   
}
#panel3{
    border-left:1px solid rgba(32,145,216, 0.3);  
    border-right:1px solid rgba(32,145,216, 0.3);  
}
span{
    color:white;
    font-family:Impact, Charcoal, sans-serif;
    font-size:60px;
    position:absolute;
    left:50%;
    margin: 0;
    top:50%;
    transform: translate(0, -50%);
}

I really love fresh, fast and simple codes, that works well.


Solution

  • You could use the .css() callback function. The callback is called once for each element in the set. This means css iterates through the collection behind the scenes. Within the handler this keyword refers to the current element of iteration.

    $('.uk-grid > div').find('span').css('margin-left', function() {
        return "-" + $(this).width() / 2 + "px";
    });