php - Wordpress using javascript to change iframe src
Get the solution ↓↓↓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 thevideoFrame
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;
}
}
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: videoxxx
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.