Reputation: 233
So I have a page that will list out any enewsletter (pure html) from a folder called 'enews' When user clicks the list, the html page will be displayed in an iframe (still in the same page)
<ul><li><a class="iframesrc" href="/enews/today.html" target="viewcontent">Today</a></li>
<li><a class="iframesrc" href="/enews/yesterday.html" target="viewcontent">Yesterday</a></li>
</ul>
<iframe id="viewcontent" name="viewcontent"></iframe>
The enews html page is not made by me so I don't have full control how the page will be. and all the files are still in the same domain.
So I CAN display the html page inside the iframe without problem. The only thing that my boss wants is to make every hyperlink inside that html page to be opened on new tab/window.
Of course I can just add "target=_blank" to the enewsletter html page itself but it is not feasible as we have more than 100 of them, I can't be manually doing it, plus the person in charge doesn't have programming skill so he actually is only changing the content of the html.
Now, is there anyway to make that happen?
I have tried to use jquery to access the content inside iframe (to add ) but it doesn't work quite well.
<script>
$( document ).ready(function() {
$('a.iframesrc').click(function() {
console.log("clicked enewslink");
var link = $(this).attr("href");
console.log(link);
$("#viewcontent").attr("src",link);
$("#viewcontent").ready(function () {
var content = $( "#viewcontent" ).contents().find("body").html();
console.log(content);
});
});
});
</script>
So when the page is loaded, and I click "today", the console DOES retrieve the link href, but the "content" of iframe is empty plus the iframe DOES display the correct content. When I click "yesterday", console can retrieve the link href, but this time the "content" of the iframe is printout (in console) and the iframe displays the correct content also.
Why can't the browser capture the link on first click?
Thanks and any help is greatly appreciated.
EDIT:
On first click:
on second click:
Upvotes: 0
Views: 602
Reputation: 1072
I made the following changes to your original code:
id
of the iframe
to viewcontent
$("#viewcontent").ready(...)
to $("#viewcontent").load(...)
$("#viewcontent").load(...)
outside $('a.iframesrc').click(...)
(so that it would be already bound when the link is clicked for the first time)and it seems to be working now.
Here's the modified (partial) code:
IFrame:
<iframe id="viewcontent" name="myiframe"></iframe>
Script:
<script>
$( document ).ready(function() {
$('a.iframesrc').click(function() {
console.log("clicked enewslink");
var link = $(this).attr("href");
console.log(link);
$("#viewcontent").attr("src",link);
});
$("#viewcontent").load(function () {
var content = $( "#viewcontent" ).contents().find("body").html();
console.log(content);
});
});
</script>
Upvotes: 2