I have the following code which contains 20 code blocks. They are all the same excepting the ID number for each. I tried looking how to simplify the code pasted below using substr. Can someone please explain if this is posible and offer an example.
$( "#ep1box" ).on('mouseover focusin' , function() {
$('#episode-1__heading-text').css('text-decoration','underline');
$('#episode-1__heading-number').css('color','#fff');
});
$( "#ep1box" ).on('mouseleave focusout' , function() {
$('#episode-1__heading-text').css('text-decoration','none');
$('#episode-1__heading-number').css('color','#18be91');
});
$( "#ep2box" ).on('mouseover focusin' , function() {
$('#episode-2__heading-text').css('text-decoration','underline');
$('#episode-2__heading-number').css('color','#fff');
});
$( "#ep2box" ).on('mouseleave focusout' , function() {
$('#episode-2__heading-text').css('text-decoration','none');
$('#episode-2__heading-number').css('color','#c428ff');
});
You don't need to use substr because what you're trying to do is build a string. Just put it together with +:
for(i=0; i < 20; i++) {
$( "#ep" + i + "box" ).on('mouseover focusin' , function() {
$('#episode-' + i + '__heading-text').css('text-decoration','underline');
$('#episode-' + i + '__heading-number').css('color','#fff');
});
$( "#ep" + i + "box" ).on('mouseleave focusout' , function() {
$('#episode-' + i + '__heading-text').css('text-decoration','none');
$('#episode-' + i + '__heading-number').css('color','#18be91');
});
}
Of course, it would make things much more straightforward if you could just give them all a specific class to denote that they have something in common. Then you don't need a loop at all.