0

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

Skatox
  • 3,919
  • 10
  • 39
  • 42
code-404
  • 25
  • 5
  • 1
    Does this answer your question? [Why does jQuery or a DOM method such as getElementById not find the element?](https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element) – CBroe Jul 16 '20 at 14:02

1 Answers1

0

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;
  } 
}
Skatox
  • 3,919
  • 10
  • 39
  • 42
  • 1
    Thank you so much, that fixed the problem instantly. I've been staring at the code all morning and couldn't see my mistake. Also thank you for fixing my code formatting in the post, I'm still learning. – code-404 Jul 16 '20 at 14:06
  • No problem, I'm glad it helped you. – Skatox Jul 16 '20 at 14:06