Question

I have the following function to load iFrames content when I click on the link.

I'm trying to implement the .next method to load one iFrame at time and not all together.

$('.toggle-next-div').click(function () {
var iframe = $(this).next('.myiFrame');
iframe.attr("src", iframe.data("src"));
});

HTML

<a href="#" class="toggle-next-div">Map</a>
<div class="slidingDiv">
    <div style="margin-top:0">
        <span style="float:left;font-weight:bold">title</span>
        <iframe class="myiFrame" data-src="www.yahoo.com" src="about:blank"></iframe>  
    </div>
</div>
<div class="slidingDiv">
    <div style="margin-top:0; margin-right:10px; margin-bottom:10px; text-align:right">
        <span style="float:left; font-weight:bold">title</span>
        <iframe class="myiFrame" data-src="www.yahoo.com" src="about:blank"></iframe>  
    </div>
</div>
//and so on...

The next() method doesn't work in my html so I need an alternative solution for this html code

Was it helpful?

Solution

.next selects the immediate next sibling of the selected element, i.e the .slidingDiv element(if it matches with the specified selector), you can use .find() and .next() methods:

var iframe = $(this).next('.slidingDiv').find('.myiFrame');

If you want to select all the .myiFrame descendant elements of all the next sibling .slidingDiv elements you can either use .siblings() or .nextAll() methods:

$(this).nextAll('.slidingDiv').find('.myiFrame').attr('src', function(){
   return $(this).data('src');
});

OTHER TIPS

It looks like this is what you were going for

HTML:

<a href="#" class="toggle-next-div">Map</a>
<div class="slidingDiv">
    <div style="margin-top:0">
        <span style="float:left;font-weight:bold">title</span>
        <iframe class="myiFrame" data-src="http://www.yahoo.com" src="about:blank"></iframe>  
    </div>
</div>
<div class="slidingDiv">
    <div style="margin-top:0; margin-right:10px; margin-bottom:10px; text-align:right">
        <span style="float:left; font-weight:bold">title</span>
        <iframe class="myiFrame" data-src="http://www.yahoo.com" src="about:blank"></iframe>  
    </div>
</div>

Javascript (jQuery):

var slidingDivs = $(".slidingDiv");
$('.toggle-next-div').click(function () {
    var iframe = slidingDivs.next().find('.myiFrame');
    iframe.attr("src", iframe.data("src"));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top