user3628240
user3628240

Reputation: 927

Jquery With Button Onclick Function

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>

Upvotes: 3

Views: 25169

Answers (2)

Super User
Super User

Reputation: 9642

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>

Upvotes: 1

Satpal
Satpal

Reputation: 133403

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)
});

Upvotes: 8

Related Questions