3

I'm just starting web development, and have a function loadTweets that pulls from another file and displays, and when I get rid of the button, and just run it directly as an anonymous function it works, however, for some reason the button does not work to call the function.

Any help would be greatly appreciated, thanks!

<html>
  <head>
    <script src="jquery.js"></script>
    <script src="data_generator.js"></script>

  </head>
  <button type = "button" onclick="loadTweets"> Load </button>
  <body>
    <script>
      $(document).ready(function(){
        var loadTweets = function(){
          var $body = $('body');
          $body.html('');
          var index = streams.home.length - 1;
          while(index >= 0){
            var tweet = streams.home[index];
            var $tweet = $('<div></div>');
            $tweet.text('@' + tweet.user + ': ' + tweet.message);
            $tweet.appendTo($body);
            index -= 1;
          }
        }
      });
    // });



    </script>
  </body>
</html>
1
  • call your function like this <button type = "button" onclick="loadTweets()"> Load </button> Commented May 5, 2017 at 6:03

2 Answers 2

8

You need define the function outside the document-ready handler and to use () with function

<button type = "button" onclick="loadTweets()"> Load </button>

<script>
  var loadTweets = function(){
      //
  });
</script>

However I would suggest you to use unobtrusive event handler.

HTML, Add an ID attribute to button

<button type="button" id="loadTweets"> Load </button>

Script, then use ID selector to target the element and .on() to bind event handler.

$(document).ready(function () {
    var loadTweets = function () {
        //existing code
    }

    $('#loadTweets').on('click', loadTweets)
});
Sign up to request clarification or add additional context in comments.

Comments

1

You can use in another way

<html>
  <head>
    <script src="jquery.js"></script>
    <script src="data_generator.js"></script>

  </head>
  <body>
  <button type = "button" onclick="loadTweets()"> Load </button>
    <script>
        function loadTweets(){
          var $body = $('body');
          $body.html('');
          var index = streams.home.length - 1;
          while(index >= 0){
            var tweet = streams.home[index];
            var $tweet = $('<div></div>');
            $tweet.text('@' + tweet.user + ': ' + tweet.message);
            $tweet.appendTo($body);
            index -= 1;
          }
        }
    </script>
  </body>
</html>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.