iamx iamx - 5 months ago 9
jQuery Question

Change CSS dinamically based on a value from array

I have this part of html:

<h1 class="gr-title uppercase">
<span class="title-red">GET MORE</span>
<span id="wordSwap" class="title-black">PROFITS</span>
</h1>


...and this jquery code that changes the value of the span with ID wordSwap:

(function(){

//Words:
var words = [
'Profits',
'Freedom',
'Time',
'Enjoyment',
'Disconnection',
'Value'
], i = 0;

setInterval(function(){
$('#wordSwap').fadeOut(function(){
$(this).html(words[i=(i+1)%words.length]).fadeIn();
});
// 2 second interval
}, 2000);

})();


I'm trying to change the
letter-spacing
for each value in the array based on what value/word comes next, but I am stuck and can't get it to work. For example I'd like the word "Time" to have letter-spacing = 30px, and the word "Value" 20px, and so on. How can I get this done?

Here is a jsfiddle of what I have up to now: https://jsfiddle.net/vgum6jn6/

Answer

Try something like this:

var baseWidth = 100; //some value
setInterval(function(){
    $('#wordSwap').fadeOut(function(){
        $(this).html(words[i=(i+1)%words.length]).fadeIn()
          .css('letter-spacing','') //reset spacing
          .css('letter-spacing', function(){
                var ratio = baseWidth / $(this).prop('offsetWidth');
                return ratio + 'px';
               });
    });
   // 2 second interval
}, 2000);