Tobi
Tobi

Reputation: 1

Decreasing Font Size If Text Is Too Long

I want to change the font size to 36px if my h1 has more than two words and keep it as is if not.

This is my code:

window.addEvent('domready',function() {
    
        var $quote = ('#header .col-sm-12 h1');
    
        var $numWords = $quote.get('text').split(' ').length; 
    
        if (2 < $numWords) {
                $quote.setStyle('font-size','36px'); }
});

However, it doesn't work. What's wrong with it?

The site in question is 6wo.de

Please note: Changing the size via CSS by using the viewport unit is not an option in this case.

Upvotes: 0

Views: 1112

Answers (1)

Engin
Engin

Reputation: 815

First of all it's not addEvent but addEventListener. Then you probably mean DOMContentLoaded, because domready is not an event.

To make the title smaller give an id or class to identify it easier in JavaScript.

<h1 id="page-title">My page title</h1>

Now you can make the title smaller like this.

window.addEventListener('DOMContentLoaded', function() {
    const title = $('#page-title');

    var numWords = title.text().split(' ').length; 

    if (numWords > 2) {
        title.css('font-size', '36px');
    }
});

UPDATE

If you don't want to give an id to the title for some reason, you can do like this.

window.addEventListener('DOMContentLoaded', function() {
    const title = $('#header .bottom-header h1');

    var numWords = title.text().split(' ').length; 

    if (numWords > 2) {
        title.css('font-size', '36px');
    }
});

Upvotes: 1

Related Questions