Insert result of a script or the code of a script into a div

0

How do I load a script into a page, the result appears in div ?

Example:

<script type="text/javascript">

/*
   conteúdo do script
*/

</script>

<div id="script" class="000000"></div>

The goal is for script to load on the page, its result will appear where div is located.

I have an example here:

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

<iframe width="854" height="510" ID="caixa" frameborder="0" allowfullscreen></iframe>

<script>
var video = $("#video").attr('class');
$('#caixa').attr('src', "https://www.youtube.com/embed/" + video);
</script>

With this code you can do this with a Youtube video, but I would like to do the same with a script . Trying to clarify a little more ....

Let's look at the example of Lightbox that is used to view images. This script snippet:

$("a[href$='.jpg'], a[href$='.png'], a[href$='.jpeg'], a[href$='.gif']").fancybox();

It indicates that by loading script , and it finds images with the ending, .jpg , .png and others it will do the desired effect.

In the case of a script I wanted it to run as a div specified.

Type it finds the .png image, but it will show it on the Sidebar for example, why script found div there.

    
asked by anonymous 18.08.2014 / 01:40

1 answer

3

The answer to your problem and the answer to your question are, in my view, slightly different.

To load a script on the page needs a string with the contents of the script, then you have to create a script element that will be added to the page and then run directly.

Example:

var scriptString = "var video = 'uT3SBzmDxGk';$('#caixa').attr('src', 'https://www.youtube.com/embed/' + video);";
var script = document.createElement('script');
script = $(script).append(scriptString);
$('#novoScript').html(script); // podia tambem ser "$(document.body).append(script);"

Demo: link

To change the video within iFrame you do not need to have a new script to add to the page. Here it is best to have an event listener that listens to click in elements with a given class. There you have to change the HTML a bit.

For example:

HTML

<div class="video" data-youtubeid="UJAwNkhbYWM">Video 1</div>
<div class="video" data-youtubeid="gIdqiis3Mts">Video 1</div>
<div class="video" data-youtubeid="Q78COTwT7nE">Video 1</div>
<div class="video" data-youtubeid="Z88qapIgOLg">Video 1</div>
<div class="video" data-youtubeid="oUX2RSyLw3w">Video 1</div>
<iframe width="854" height="510" ID="caixa" frameborder="0" allowfullscreen></iframe>

JavaScript / jQuery

$('.video').on('click', function () {
    var video = $(this).data('youtubeid');
    $('#caixa').attr('src', "https://www.youtube.com/embed/" + video);
});

Demo: link

    
18.08.2014 / 08:45