views:

125

answers:

2

I have the following iframe control (intended to be a facebook like button):

<iframe id="likeButton"
    src="http://www.facebook.com/plugins/like.php?href=" 
    scrolling="no" 
    frameborder="0"         
    style="border:none; overflow:hidden; 
    width:450px; height:80px;"
    onprerender="setupLink()"
</iframe>

I have the javascript function defined above this as follows:

<script type="text/javascript">
  function setupLink()
  {
    var iframe = $("#likeButton");
    var newSrc = iframe.attr("src");
    newSrc += encodeURIComponent(location.href) + lblKey.Text;

    iframe.attr("src", newSrc);
  };
</script>

lblKey is a label on the ASP.NET page that references the specific section of the page. However, as far as I can determine, this function doesn’t get called (if I put an alert() at the start it brings nothing up). I’m new to javascript, but looking around at some articles on the web would indicate that this should update the src property on the iframe.

EDIT:

I have also tried the following:

<script type="text/javascript" >
$(function() {
    var iframe = $("#likeButton");
    var newSrc = iframe.attr("src");
    newSrc += encodeURIComponent(location.href) + '<%= lblKey.Text %>';

    iframe.attr("src", newSrc);
});
</script>

Which doesn't work, but neither does:

<script type="text/javascript" >
$(function() {
    alert('Hello');
});
</script>
+2  A: 

asp.net events (like prerender) don't apply anywhere else (like javascript)

assuming you are using jquery, I would wrap that in a $(), which is a shorthand for "Execute the following as soon as the page has loaded enough to start manipulating it". Also, asp.net controls have a different api then dom elements, so if you want to use that api you need to wrap it in a scriptlet tag

<script type="text/javascript">
  $(function ()
    {
      var iframe = $("#likeButton");
      var newSrc = iframe.attr("src");
      newSrc += encodeURIComponent(location.href) + "<%= lblKey.Text %>";

      iframe.attr("src", newSrc);
    });
</script>
Matt Briggs
Thanks for this. But if I put an alert(newSrc); just above iframe.arrt(... then it doesn't do anything.
pm_2
A: 

Have you considered using the onload event and passing a reference to the iframe?

<script type="text/javascript">
function change_source(iframe)
{
  if (iframe.src.indexOf('facebook') < 0)
  {
    iframe.src = 'http://www.facebook.com/plugins/like.php?href=&lt;%= lblKey.Text %>';
  }
}
</script>

HTML something like this...

<iframe id="likeButton"
    src="about:blank" 
    scrolling="no" 
    frameborder="0"         
    style="border:none; overflow:hidden; 
    width:450px; height:80px;"
    onload="change_source(this);"
</iframe>
JayTee