I'm trying to copy the following JSFiddle: https://jsfiddle.net/7nbr6/10/
Onto my WordPress site.
When I copy it onto the site it doesn't do anything when I click the buttons.
I am using this plugin to put the javascript onto my page: https://wordpress.org/plugins/css-javascript-toolbox/
HTML:
<!-- Throw in a nice looking font just for the fun of it -->
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Yanone+Kaffeesatz:400,700,300,200">
<div id="wrap">
<h2>Kelly calculator</h2>
<div class="formStyles">
<input id="probability" type="text" value="Probability"><br>
<input id="odds" type="text" value="Odds"><br>
<input id="balance" type="text" value="Balance"><br>
<input id="submit" type="submit" value="Submit">
<input id="reset" type="reset" value="Reset">
<div id="result"></div>
</div>
</div>
Javascript:
<script type="text/javascript">
jQuery('#submit').on('click', function() {
var probability = jQuery('#probability').val();
var odds = jQuery('#odds').val();
var balance = jQuery('#balance').val();
result = parseFloat(((probability/100)* (odds - 1) / (odds - 1) * odds - 1).toFixed(4)) * 0.95;
var stake = ((balance / 100) * parseFloat((result * 100).toFixed(2)))
jQuery('#result').text((result * 100).toFixed(2) + '% of' + balance + '€ which is ' +stake + '€');
});
</script>
The code is definitely embedded into the page header (visible by viewing the page source), but the buttons don't work.
I initially thought it was an issue with noConflict() detailed here: TypeError: $ is not a function when calling jQuery function
I also have this error in the editor (inside the plugin), but it doesn't appear in the console when I navigate to the page:
https://i.imgur.com/3FKt1Mi.png
I tried removing the script tags, but then it would just put it into the header as text.
Thanks for your help
when your code is loaded, jQuery is not ready. Therefore your code is quite ignored.
Put your code inside:
You're trying to attach a handler to an element before the DOM is ready. Wrapping the code inside a
ready
handler resolves this issue:The code wrapped around your JavaScript is shorthand for jQuery's
.ready
event.