views:

42

answers:

2

Hello, I have a list of links eg :

<ul> 
<li><a href="http://google.com"&gt;Link1&lt;/a&gt;&lt;/li&gt;
<li><a href="http://example.com"&gt;Link2&lt;/a&gt;&lt;/li&gt;
<li><a href="http://example.com/sdf"&gt;Link3&lt;/a&gt;&lt;/li&gt;
</ul>

When a link is clicked, a iFrame should be generated in the middle of the screen loading the page like a lightbox.

How to do this with jQuery ?

A: 

You can do something like this:

// we only want to use a single iframe:
var $iframe = $("<iframe>").css({
  width: '100%', 
  height: '10em'
  // we can set more css properties to make it positioned where we want, etc...
});
$("a").click(function() {
   // stick it at the end of the <body> tag, and set its src property
   $iframe.appendTo('body').attr('src',this.href);
   return false;
});

Of course for anything other than a demo, you'll want a more specific selector than a which will find every link, something like .myLinks a and add class='mylinks' to the <ul> is probably the best option. You also have more options for styling the <iframe> using css properties/classes.

Demo on jsfiddle

gnarf
Hey thank you, jsfiddle is really good. Thanks for you code and intro to jsfiddle
Aakash Chakravarthy
@Aakash Chakravarthy - No problem - also, you can mark an answer as "accepted" by clicking on the checkbox below the posts score.
gnarf
+1  A: 
$(document).ready(function(){
 $('a').bind('click', function(e){
    $('<iframe/>', {
       src:   $(this).attr('href'),
       class: 'myiframe',
       css:   {
           position: 'absolute',
           width:    '200px',
           height:   '200px',
           top:      window.innerHeight / 2 + 300,
           left:     window.innerWidth / 2 + 300
       }          
    }).appendTo(document.body);

    return(false);
});

$(document.body).bind('keydown', function(e){
  if(e.which === 27)
     $('.myiframe').remove();
});
});​

I poorly calculated the top/left coordinates there, you might want to replace that with a css class anyway. Use class: "classname" for that within creation.

References: .bind(), .attr(), .appendTo(), jQuery Core

jAndy