php - Code Executing on Page Load instead of OnClick
one text
Solution:
Obviously I can't do a full test on your code, too many parts are missing to reproduce the problem and the whole environment. But I have created a skeleton of the basic structure of what I think you want to achieve. And it seems to work.
You can try the code online here: https://www.w3schools.com/php/phptryit.asp?filename=tryphp_compiler It is the only site I have found that allows you to mix html, js and php.
<?php
function get_javascript() {
ob_start();
?>
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#fpd-share-button').click(function(evt) {
alert("Testing");
evt.preventDefault();
});
});
</script>
<?php
$output = ob_get_contents();
ob_end_clean();
return $output;
}
?>
<!DOCTYPE html>
<head>
<script
src="https://code.jquery.com/jquery-3.6.0.min.js"
integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4="
crossorigin="anonymous"></script>
<?php
echo get_javascript();
?>
</head>
<body>
<button id="fpd-share-button">SHARE</button>
</body>
</html>
Source