Skip to content Skip to sidebar Skip to footer

Applying A Style To And Inserting A Line Break After The First Word In A Link

I've been asked to recreate an HTML site in WordPress and have it all done except for a meny bar that has me stumped. See image at: http://img36.imageshack.us/img36/8964/menubare.j

Solution 1:

$('#nav').children('li').find('a').each(function(){
var old = $(this).text();

$(this).html(old.substring(0,old.indexOf(' ')) +'<br/>'+old.substring(old.indexOf(' '),old.length));
});

if you need to apply some class

$(this).html('<span class="first">'+old.substring(0,old.indexOf(' ')) +'</span><br/><span class="next">'+old.substring(old.indexOf(' '),old.length)+"</span>");

Solution 2:

Without an HTML example of your menu, its hard to give you a specific answer.

But you could use some jQuery like the following, it will allow you to add styling to the first word, and the rest of them. It will .split() the HTML on spaces, giving you an array. Wrap the first item in a span allowing styling. Then uses jQuery's .each() to loop through the rest of the items adding them back to the string. Then replaces the HTML with the new version:

$('#header > ul.nav > li > a').each(function() {
    var obj = $(this);
    var text = obj.html();
    var parts = text.split(' ');
    var replace = '<span class="firstWord">'+parts[0]+'</span><br />';
    parts.shift();
    $.each(parts, function(key, value) { 
        replace += ' '+value;
    });
    obj.html(replace);
});

Example CSS:

.firstWord {
    font-size: 15px;    
}
.menuHeader {
    margin-left: 10px;
    float: left; 
    font-size: 40px;
}
.menu {
    width: 100%;
    height: 120px;
    background-color: #FF8C00;    
}

Take a look at a working demo


Update to the demo reflect code from comment.

Use the selector:

$('#header > ul.nav > li > a')

To select only the first menu item. You should only need to add:

.firstWord {
    font-size: 15px;    
}

To your CSS to adjust the size of the first item.


Good suggestion by Edwin V., you could change the jQuery to:

$('#header > ul.nav > li > a').each(function() {
    var obj = $(this);
    var text = obj.html();
    var parts = text.split(' ');
    var replace = '<span class="firstWord">'+parts[0]+'</span><br />';
    parts.shift();
    replace += parts.join(' ');
    obj.html(replace);
});

To shorten it a little. Demo here..

Post a Comment for "Applying A Style To And Inserting A Line Break After The First Word In A Link"