php - Wordpress using javascript to change iframe src
I am trying to implement javascript on a Wordpress page which uses a template php file. But the onlcick is not changing the src and in the browser debug console I am receiving the message "Uncaught Type Error: Cannot set property 'src' of null"
I have added the Javascript code below to a .js file
videoFrame = document.getElementById('video');
function setLanguage(lang) {
switch(lang) {
case 'en':
videoFrame.src = 'https://player.vimeo.com/video/1';
break;
case 'fr':
videoFrame.src = 'https://player.vimeo.com/video/2';
break;
}
}
I then added the enqueue to the functions.php file
add_action('wp_enqueue_scripts' ,'translate_script');
function translate_script(){wp_enqueue_script('translate', get_stylesheet_directory_uri().'/js/translate.js');}
Finally I added the code for the buttons on the template.php file
<button onclick="setLanguage('en')"></button>
<button onclick="setLanguage('fr')"></button>
Any help or suggestions would be appreciated as I can get the code working in CodePen but not within the wordpress environment. Thanks
Answer
Solution:
The problem is that you are trying to get the videoFrame
before the full page is loaded. You can fix this problem by putting that code inside a document.ready or by acessing the video inside the function, so it search for it when the button is clicked (and the full website has been already loaded)
function setLanguage(lang) {
videoFrame = document.getElementById('video');
switch(lang) {
case 'en':
videoFrame.src = 'https://player.vimeo.com/video/1';
break;
case 'fr':
videoFrame.src = 'https://player.vimeo.com/video/2';
break;
}
}
Source