lundi 10 septembre 2018

Dynamically update iframe's title attribute using JS or Ruby?

Please note I have little JS knowledge so if there's something I can do better please let me know.

I have an iframe with three tabs that are being changed with Ruby link_to. What I am ultimately wanting to do is dynamically update the iFrames' title attribute when the links are clicked.

The original code looks like:

<div class="mobile">
 <%=link_to "one", :id => "one" %>
 <%=link_to "two", :id => "two" %>
 <%=link_to "three", :id => "three %>
 <iframe src="<%=some_url%>" width="100%;" height="100%;" aria-hidden="true", id="myFrame"><iframe>

I've done various attempts with jQuery that didn't seem to work so I've been trying the following in JS that doesn't pull in the change to the code but it's pulling up in the console:

<%=link_to "one", :id => "one", :onclick => "changer()"%>
<script>
 function changer() {
   document.getElementById("myFrame").title = "One Goes Here"
 }
</script>

No errors are present but it's not showing a change to the title.

I've also tried using:

document.getElementById('myFrame').setAttribute('title', 'One Goes Here');

No change happens.

I've also tried:

<script>
var iframe = document.getElementById("myFrame");
var iframeTitle = iframe.contentDocument.title;
document.getElementById("myFrame").onload = function() {
  var iframeTitle = document.getElementById("myFrame").contentDocument.title;
  if (document.title != iframeTitle) {
    document.title = iframeTitle;
    }
}
</script>

This just results in Uncaught TypeError: Cannot read property 'contentDocument' of null

Aucun commentaire:

Enregistrer un commentaire