How can I start JavaScript with a button click (on WordPress)? - javascript

I want to insert a button in a page WordPress that open this a JavaScript when a click happened.
The HTML script is this
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
test=()=>{
var script = document.createElement('script');
script.src = 'https://www.jdoodle.com/assets/jdoodle-pym.min.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}
</script>
<input type="button" onclick="test()" value="test">
<div height="200px" width="300px" data-pym- src="https://www.jdoodle.com/iembed/v0/x6e?rw=1"></div>
</body>
</html>
I've tried to insert a jquery version like this.
On wordpress page
<button onclick="F()">Click me</button>
and in functions.php
function javascript_footer() {
?>
<script>
// your javscript code goes
function F(){
alert("test");
$.getScript("https://www.jdoodle.com/assets/jdoodle-pym.min.js", function(data, textStatus, jqxhr) {
});
alert("stop");
}
</script>
<?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');
What's is wrong? it seems that it doesn't load property the script.
Thank you.

Enqueue your script.
See wp_enqueue_script() for more details.
/**
* Enqueue a script with jQuery as a dependency.
*/
function wpdocs_scripts_method() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
Your problems though
Is that you're currently not declaring your anonymous function test()
Try:
const test = () => {
var script = document.createElement('script');
script.src = 'https://www.jdoodle.com/assets/jdoodle-pym.min.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}

Related

How can I load all the website content before call a JavaScript function in php

<?php
$homepage = file_get_contents('https://finance.yahoo.com/quote/0016.HK/news p=0016.HK"');
echo $homepage;
?>
<script type="text/javascript">
function test(){
.....
}
The script was executed before the website load all the contents and thus, I can't get all the content after running the script.
How can I fully get the content from the website first and then run the script? thanks!
<script type="text/javascript">
document.addEventListener( 'DOMContentLoaded', function( event ) {
function test(){
console.log("DOM loaded");
}
});
</script>

Load reCAPTCHA dynamically

There are several ways to load reCAPTCHA using javascript such as below:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
This code load captcha on pageload. I want load reCAPTCHA just when clicked on "MYBTN". So the code changes into:
<html>
<head>
<title>Loading captcha with JavaScript</title>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script type='text/javascript'>
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
});
</script>
</head>
<body>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
</body>
</html>
But this code didn't work when I click on "MYBTN" and reCAPTCHA not load.
Help me plz. Thanks.
You just need to call loadCaptcha()
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
loadCaptcha(); // THIS LINE WAS MISSING
});
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<div id="captcha_container"></div>
<input type="button" id="MYBTN" value="MYBTN">
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit"></script>
Simple situation
Html
<input type="button" id="MYBTN" value="create captcha">
<div id="captcha_container"></div>
JS
var testSitekey = '6LeLzA4UAAAAANNRnB8kePzikGgmZ53aWQiruo7O';
$('#MYBTN').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': testSitekey
});
}, 1000);
});
Online demo (jsfiddle)
You just mentioned onload in your embedded script. Either you just remove onload from your embedded script or just keep your code outside of the onclick event in the function name loadCaptcha.
1. First Solution:
$('#MYBTN').on('click',function(){
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
}
});
<script src="https://www.google.com/recaptcha/api.js?render=explicit"></script>
2. Second Solution
<script type='text/javascript'>
var captchaContainer = null;
var loadCaptcha = function() {
captchaContainer = grecaptcha.render('captcha_container', {
'sitekey' : 'Your sitekey',
'callback' : function(response) {
console.log(response);
}
});
};
</script>
<script src="https://www.google.com/recaptcha/api.js?onload=loadCaptcha&render=explicit" async defer></script>
In first Solution your code will work when you click your button. Even you don't have to put then in loadCaptcha function you can directly call grecaptcha.render.
But when you mention onload in your script tag then it will not work according to your click then it will find the callback function you mentioned in the script. And as you wrote the loadCaptcha in onload of script and you wrote this function inside the onClick event. When the script tag executed, the code tried to find the loadCaptcha function which was not initialised till the script tag executed (as it would initialise on click event), So your script was not working.
JS
// Loading captcha with JavaScript on button click
jQuery(document).ready(function ($) {
$('#MYBTN').on('click',function() {
$.getScript( "https://www.google.com/recaptcha/api.js?render=__YOUR_KEY__" )
.done(function( script, textStatus ) {
if(typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
grecaptcha.execute('__YOUR_KEY__', {
action: 'homepage'
})
.then(function (token) {
var recaptchaResponse = document.getElementById('captcha_container');
recaptchaResponse.value = token;
});
// Your other code here
// You can control captcha badge here
});
}
});
});
});
HTML
// Required HTML:
<body>
<input type="button" id="MYBTN" value="MYBTN">
<div id="captcha_container"></div>
</body>
I've implemented the captcha to be loaded only after one of the required fields of my form was focus. I also implemented a check variable to see if the captcha's dependencies were inserted before.
Here is is:
jQuery('#MyRequiredInputId').focus(function () {
if(typeof loadedRecaptcha != 'undefined'){
return;
}
jQuery.getScript("https://www.google.com/recaptcha/api.js?render=___YOURKEY__")
.done(function (script, textStatus) {
if (typeof grecaptcha !== "undefined") {
grecaptcha.ready(function () {
var siteKey = '___YOURKEY___';
jQuery('body').append(jQuery('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': siteKey
});
}, 1000);
});
}
loadedRecaptcha = true;
});
});
Note that in my case, I have a <div id= "captcha_container"></div> where I want to display my captcha.
Result:
I got the same issue today when I discovered that there are about 21 requests for Google Recaptcha even without open the login modal, this is indeed too much ):
After trying this method:
HTML
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div>
</div>
JS
<script>
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
finally, I get the results I want, now the recaptcha only loads when the login modal opens (based onClick function).
Unfortunately, I found that the main Google Recaptcha script still loads in console even while using the delay method mentioned above because the main script is declared on the page head:
<script src="https://www.google.com/recaptcha/api.js"></script>
So, I removed it from the page head then combined some lines of codes together to get it to work and only loads when the modal opens as follow:
Final code:
<div class="row">
<div class="col-sm-12 btm10">
<div id="captcha_container"></div>
</div> //Wherever you want the reCaptcha to appear
</div>
<script>
//Add to the header or the footer it doesn't matter
var Sitekey = '<?php echo config('google_key') ?>';
$('#loginbtn').click(function() {
$.getScript("https://www.google.com/recaptcha/api.js") //The trick is here.
$('body').append($('<div id="captcha_container" class="google-cpatcha"></div>'));
setTimeout(function() {
grecaptcha.render('captcha_container', {
'sitekey': Sitekey
});
}, 1000);
});
</script>
You can view it in action here:
https://youtu.be/dAZOSMR8iI8
Thank you
Tell Google you want to render the recaptcha explicitly (when you are ready). https://www.google.com/recaptcha/api.js?render=explicit
After the api script has run grecaptcha is available globally.
<!DOCTYPE html>
<html lang="en">
<head> </head>
<body>
<div id="whereIWantRecaptcha"></div>
<button id="myButton">show Recaptcha</button>
<script
src="https://www.google.com/recaptcha/api.js?render=explicit"
async
defer
></script>
<script>
var button = document.querySelector('#myButton');
button.addEventListener('click', function(){
grecaptcha.render('whereIWantRecaptcha', {
'sitekey' : '6LeIxAcTAAAAAJcZVRqyHh71UMIEGNQ_MXjiZKhI'
});
});
</script>
</body>
</html>

Insert JS Snippet To WP Site

I've been slowly truing to teach myself some simple aspects regarding coding. Right now, I want to upload a snippet of JS code onto a single page. Here is some background followed with the code I want to use:
The code will go on one page. This page is a form page where if someone does anything other than press "submit" a module pops up with some questions. I've been using wordpress. Any thoughts, guidance, etc. would be perfecto!
<script>
var config = new Object();
config.surveyID = 3160325;
/*config.animationMode = 0;*/
config.takeSurveyURL = 'http://www.surveyanalytics.com/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.surveyStartMessage = 'Start Survey';
config.popupInvitationLaterMessage = 'Later';
config.showFooter = true;
config.invitationDelay = 0;
config.skipCount = 0;
config.popupMode = 0;
config.expirationTime = 60
window.onbeforeunload = function() {
QP_popupMain();
};
</script>
<script language="javascript" type="text/javascript" src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"></script>
<noscript>
Start Survey Survey
</noscript>
Since WordPress doesn't like <script> tags within functions.php, instead put your code into a ".js" file and register the script in functions.php and then enqueue it in your shortcode.
In your functions.php file:
add_action( 'wp_enqueue_scripts', 'register_my_script' );
function register_my_script() {
//This example puts it in plugins, but you can put it in your theme instead
wp_register_script( 'script-name', plugins_url( '/js/script.js' , __FILE__ ), array(), '1.0.0', true );
}
//Replace "PUT YOUR JAVASCRIPT CODE IN HERE" with your actual code
function myTestFunction( $atts )
{
//Now enqueue the script
wp_enqueue_script( 'script-name' );
}
add_shortcode( 'myjavascriptfunction', 'myTestFunction' );
Then in the CMS, go to that page and add the call to the shortcode in the content text box:
[myjavascriptfunction /]
This is the code in script.js
<script>
var config = new Object();
config.surveyID = 3160325;
/*config.animationMode = 0;*/
config.takeSurveyURL = 'http://www.surveyanalytics.com/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.surveyStartMessage = 'Start Survey';
config.popupInvitationLaterMessage = 'Later';
config.showFooter = true;
config.invitationDelay = 0;
config.skipCount = 0;
config.popupMode = 0;
config.expirationTime = 60
window.onbeforeunload = function() {
QP_popupMain();
};
</script>
<script language="javascript" type="text/javascript" src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"></script>
<noscript>
Start Survey Survey
</noscript>
This is the code in function.php
add_action( 'wp_enqueue_scripts', 'register_my_script' );
function register_my_script() {
//This example puts it in plugins, but you can put it in your theme instead
wp_register_script( 'script', plugins_url( '/script.js/' , __FILE__ ), array(), '1.0.0', true );
}
//Replace "PUT YOUR JAVASCRIPT CODE IN HERE" with your actual code
function myTestFunction( $atts )
{
//Now enqueue the script
wp_enqueue_script( 'script' );
}
add_shortcode( 'myjavascriptfunction', 'myTestFunction' );

call javascript function from new window

sorry this problem might be resolved already, but I have not been able to find the answer.
I basically have 2 files:
form.html code:
<!DOCTYPE html>
<html>
<head>
<title>BACKUP MONITOR</title>
<script>
function getEvents()
{
alert("getEvents");
}
alert("in HTML");
var w = window.open();
var s = w.document.createElement("script");
s.type = 'text/javascript';
s.src = ".../fileA.js";
w.document.body.appendChild(s);
w.alert("New Window");
</script>
</head>
<body>
</body>
</html>
fileA.js code:
alert("in fileA");
getEvents();
Question:
I can't call getEvents() from fileA.js (new Window). Is there any way to do this?
thank you very much

Loading js dynamically not reflecting

I want to load js on the fly which is happening but the one more js file which is included in index is loading before (file i am loading dynamically) is there way to fix the order
i am adding global.js dynamically and i want variable declared in global.js shoud be initialised before dynamicjs.DynamicJs is loaded
------------- Index.html -------------
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<script src="resources/sap-ui-core.js"
id="sap-ui-bootstrap"
data-sap-ui-libs="sap.ui.commons"
data-sap-ui-theme="sap_goldreflection" >
</script>
<!-- add sap.ui.table,sap.ui.ux3 and/or other libraries to 'data-sap-ui-libs' if required -->
<script src="js/dyn.js"></script>
<script></script>
<script>
sap.ui.localResources("dynamicjs");
var view = sap.ui.view({id:"idDynamicJs1", viewName:"dynamicjs.DynamicJs", type:sap.ui.core.mvc.ViewType.JS});
view.placeAt("content");
</script>
</head>
<body class="sapUiBody" role="application">
<div id="content"></div>
</body>
</html>
function loadScript(url){
var xhrObj = createXMLHTTPObject();
// open and send a synchronous request
xhrObj.open('GET', url, false);
xhrObj.send('');
var e = document.getElementsByTagName("script")[1];
var d = document.createElement('script');
d.src = url;
d.type = 'text/javascript';
d.async = false;
d.defer = false;
e.parentNode.insertBefore(d,e);
}
function addScriptDynamically(){
loadScript('js/global.js'+'?scheme=12345');
}
function createXMLHTTPObject(){
var xmlhttp=new XMLHttpRequest();
if( typeof xmlhttp == 'undefined' || xmlhttp == null )
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
return xmlhttp;
}
/*call function */
addScriptDynamically();
Why won't you try to load script with jQuery.getScript()
http://api.jquery.com/jQuery.getScript/
If you want compatibility with other libraries like prototype or mootools you can set jQuery.noConflict()

Categories