exchange data-src by src with javascript

2

In the site I'm doing I have a lot of thumbnail in which when clicked goes to another page where there are several blocks of code. Each block corresponds to a thumb. The problem is that I need when I go to another page it does not load <iframe> except the one of the thumb that I clicked. I found a code right here in the English stak but it does not serve exactly the purpose and as I'm starting backend I turned to you.

Home page

Let's suppose that this link tag is a thumb that clicks on internal.php

<a href="interna.php#thumb1" class="thumb" ></a>

Internal page

When in the internal the code exchange Data-src by src to load the video in question

<div id="thumb1">
    <iframe width="820" height="420" data-src="https://www.youtube.com/embed/eBordIVMoDQ"frameborder="0" allowfullscreen></iframe>
</div>

Code that I am using

Code found in StackOverflow

$('.thumb').on("click", "img", function () {
var t = this;
var source = $(t).children("iframe");        
$source.attr({
    src: $t.attr('data-src')

  }).removeAttr('data-src');
}

This is the code solved (obs: I made the same page with pop-up):

   $(document).ready(function(){
        var iframes = $('iframe');  
        $('.button').click(function() {
            iframes.attr('src', function() {
                var src = $(this).attr('data-src');
                $(this).removeAttr('data-src');
                return src;
            });
        });
    });
    
asked by anonymous 21.05.2015 / 01:14

1 answer

2

In this code you have several problems:

$('.thumb').on("click", "img", function () {
    var t = this;
    var source = $(t).children("iframe");        
    $source.attr({
        src: $t.attr('data-src')
      }).removeAttr('data-src');
}
  • missing ) at end after }
  • $ missing in variable name here var source = ...
  • $t does not exist, has never been declared

Suggestion of code to change src of iFrame would be:

$('.thumb').click(function(e) {
    e.preventDefault();
    var src = this.getAttribute("href").split('#');
    var id = src.pop();
    var url = src[0];
    var iframe = document.querySelector('#' + id + ' iframe');
    iframe.src = iframe.dataset.src;
});

By steps:

  • prevent the link from being followed
  • extract what is in the href of the anchor
  • separates in id and url . ( Note: I do not understand why you need this interna.php ?)
  • select iFrame using id that we fetched from anchor '
  • assigns to iFrame the src that is in its own data-src

Example: link

    
21.05.2015 / 06:37