Jquery With Button Onclick Function
html, javascript, jquery
Solution
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)
});
Problem
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> ```