Reputation: 63
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/
//Swap words effect
(function() {
// List of 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 seconds
}, 2000);
})();
.gr-title {
font-family: "Arial", Georgia, Serif;
}
.uppercase {
text-transform: uppercase;
}
.title-red {
color: #CB0000;
}
.title-black {
color: #191919;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<h1 class="gr-title uppercase">
<span class="title-red">GET MORE</span> <span id="wordSwap" class="title-black">PROFITS</span>
</h1>
Upvotes: 1
Views: 103
Reputation: 63
Alex Kudryashev helped me come up with this and it solved my issue perfectly:
//Swap words effect:
var words = [
{ word: 'Profits', spacing: '8px' },
{ word: 'Enjoyment', spacing: '0px' },
{ word: 'Freedom', spacing: '4px' },
{ word: 'Disconnection', spacing: '-2px' },
{ word: 'Time', spacing: '0.98em' },
{ word: 'Value', spacing: '0.5em' }
], i = 0, n = 0;
setInterval(function () {
$('#wordSwap').fadeOut(function () {
$(this).html(words[i = (i + 1) % words.length].word)
.css('letter-spacing', words[n = (n + 1) % words.length].spacing).fadeIn();
});
// 2 seconds
}, 2000);
(disregard the random letter-spacing values, they are random for testing purposes)
Upvotes: 1
Reputation: 9480
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);
Upvotes: 1