Champop
Champop

Reputation: 89

Showing value on page load

I have a button and when I click it, it dislays a random line from a txt file.

$(function() {
    $('button').click(function() {
        $.get('teas.txt', function(data) {
            var teas = data.split('\n');
            random = teas[Math.floor(Math.random() * teas.length)];
            $('p').text(random);
        });
    });
});

I would like to show a random line when the page is loaded.

I tried this code and of course it works :

$(function() {
    $.get('teas.txt', function(data) {
        var teas = data.split('\n');
        random = teas[Math.floor(Math.random() * teas.length)];
        $('p').text(random);
    });
    $('button').click(function() {
        $.get('teas.txt', function(data) {
            var teas = data.split('\n');
            random = teas[Math.floor(Math.random() * teas.length)];
            $('p').text(random);
        });
    });
});

But I'm pretty sure there is a simpler and cleaner way to do it without duplicating the .get.

I tried several things without any success...

Any idea?

Upvotes: 0

Views: 98

Answers (2)

j08691
j08691

Reputation: 207913

Instead of duplicating the code as you showed, just trigger a click by adding .trigger('click') to what you have when the document loads:

$(function() {
    $('button').click(function() {
        $.get('teas.txt', function(data) {
            var teas = data.split('\n');
            random = teas[Math.floor(Math.random() * teas.length)];
            $('p').text(random);
        });
    }).trigger('click');
});

Upvotes: 5

Vali S
Vali S

Reputation: 1461

This should do:

    function append_text(){
      $.get('teas.txt', function(data) {
                var teas = data.split('\n');
                random = teas[Math.floor(Math.random() * teas.length)];
                $('p').text(random);
            });
    }    
    $(function() {
            append_text(); 
    });
    $('button').click(function() {
            append_text();
    });

Upvotes: 0

Related Questions