Jeff Jeff - 3 months ago 12
jQuery Question

jQuery iFrame Variable from Text File in Wordpress

I am trying embed videos using a set of urls and parameters stored in a text file in Wordpress that change at random on F5 refresh. I am not a coder but I think I am close, but wrong and the example is here:

I have tried a lot of different approaches but cannot seem to get the parameters passed correctly from the file to display the random video and parameters on refresh in the second video frame. From the link above:

  • the first video is an iframe embed command with start and stop parameters and works fine

  • the second video is an attempt to use the var of "video" to use as the beginning of the src= values

  • at the bottom is a random line from the file that changes correctly using div class on refresh of the page that works like I want the video link to.

Any help to redirect my obviously incorrect approach is appreciated. Here is the code:

<iframe width="854" height="480" src="" frameborder="0" allowfullscreen></iframe>

`<iframe width="854" height="480" src=$video frameborder="0" allowfullscreen></iframe>

<div class="video"></div>

<script type="text/javascript" src="js/jquery.js"></script>
<script>// <
jQuery(document).ready(function($) {
$.get('/wp-content/slap/video.txt', function(data) {
var video = data.split("@");
var idx = Math.floor(video.length * Math.random());

Contents of video.txt


Thanks again for any help,


Couple of things I've spotted..

  1. The .video div never closes, so that might lead to some issues. (Maybe it does in your normal code, but it doesn't in what you posted above.

  2. This:

    var video = data.split("@"); idx = Math.floor(video.length * Math.random());

Doesn't seem to do what you want it to. Math.random(), if called without arguments, returns a decimal between 0 and 1. To make it between two numbers, you have to provide a min and a max. In your code, the idx variable is very likely just going to be zero. I think you may want instead idx = Math.random(0, video.length - 1);

  1. You're setting the HTML of .video to just the URL of the video selected. That doesn't work -- You'd need to populate the iframe source attribute tag with the URL to make this work.. Which now begs the question: why are you doing this in Javascript? Does the random video need to be changed again once the page loads? It seems like you could just do this much more simply with only PHP. You'd read from the text file, randomly choose one of the URLs, and then output the <iframe src="$source"> on page load instead of via AJAX and Javascript.