views:

79

answers:

1

I have a snippet to create a 'Like' button for our news site:

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

However, to make it work properly, because the button posted an error saying the button was on an invalid URL address, I added a bit of jQuery to tweak the URL like this:

<script type="text/javascript">
    $(document).ready(function(){    
        var imageFile = $('#likeButton').attr( 'src');
        eval("imageFile = imageFile +"+"window.location.href;");     
        eval("$('#likeButton').attr( 'src', function(){return imageFile +"+"window.location.href;});");
    });
</script>

That works as far as I can tell.

I want to change the button from like to recommend and know from the Facebook site that I need to append an attribute of action=recommend to the URL. But as a newbie I've been unable to add it so it works. How can I add attributes to the URL?

+2  A: 

First of all, you have no business calling eval in this case. It is very rare that eval is ever needed, and it should be avoided at all costs. Having said that, look at the following code. I am simply building the new src attribute using standard query string syntax to add your new action value, and then I set it. Pretty self-explanatory...

$(document).ready(function(){
  var iframe = $("#likeButton");
  var newSrc = iframe.attr("src");
  newSrc += encodeURIComponent(location.href);
  newSrc += "&action=recommend";

  iframe.attr("src", newSrc);
});

If anything in there does not make sense to you, feel free to ask and I will explain further.

Josh Stodola
This should work, yes, but might I suggest you change your `var img` to some other name? `#likeButton` is an `<iframe>`, not an `<img>`
Ryan Kinal
@Ryan Good point! Update has been made.
Josh Stodola
That's brilliant. I'm still getting to grips with basic string manipulation so I appreciate your help.
elksie5000