How to use javascript in posts?


#1

I am trying to grab youtube title using oembed
This is my code with some errors like index.js: Unexpected token (3:12) in codepen. Please correct it.

<script>
		  function getyoutubetitle(id) {
		  	var json = 'http://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3D' + id + '&format=json';
			document.write(json[title]);
		  }
	  </script>
getyoutubetitle(xh6mpAOD9ho);

http://songs.justinechacko.in/malayalam/2018/02/01/file5.html


#2

um … how about:

<script>getyoutubetitle(xh6mpAOD9ho);</script>

this is bad practice however.
You should be doing something like

<span class="youtube" id="xh6mpAOD9ho"></span>
<script>
    $('span.youtube').each(function() {
      var id = $(this).attr('id');
      var json = 'http://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3D' + id + '&format=json';
      $(this).html(json[title]); 
    }
</script>

note: this code is completely untested, not sure whether it works :slight_smile:


#3

http://www.youtube.com/oembed?url=http%3A//youtube.com/watch%3Fv%3D' + id + '&amp;format=json this is a url and I have doubt that I can simply collect the value in a variable since it is a remote url?


#4

For some reason javascript is not working in posts. Is it default behavior?


#5

I can see in your link you not using any js
as mentioned above:
wrap your code in script tags:
<script>getyoutubetitle(xh6mpAOD9ho);</script>


#6

Already tried, please check now <script>getyoutubetitle("iClTTtecJhs");</script>. It loads with some problem…