jquery open image in new window

21,829

Solution 1

Try this:

JS:

window.open(filePath + img_to_load + '.jpg', '', 'width=640,height=480');

Change the width and height to suit, or if you cannot specify an exact width and height, just use

window.open(filePath + img_to_load + '.jpg');

See window.open - MDN.

Because it is opened on the click event, it won't be blocked by pop-up blockers, as long as the URL being opened is in the same domain.

Solution 2

I'd suggest:

$('ul li a').click(function(e) {
    // prevents the default action of the link's click-event ('e'), above
    e.preventDefault();
    // finds the 'img' element within the 'a', using 'find()`
    // and converts that, using '[0]' to a plain DOM node
    // and retrieves the full, absolute, 'src' from that element
    var img_to_load = $(this).find('img')[0].src,
        imgWindow = window.open(img_to_load, 'imgWindow');
});​

JS Fiddle demo.

The above will open any subsequently clicked images into the same window (reloading the opened-window with the new image element), as it will first see if there's a window open with the same name (in this case 'imgWindow', the second parameter in the window.open() function) and, if it exists, re-use it. Otherwise it'll open a window with that name.

If you want images to open in their own window every time, simply omit that parameter and simply use:

$('ul li a').click(function(e) {
    e.preventDefault();
    var img_to_load = $(this).find('img')[0].src,
        imgWindow = window.open(img_to_load);
});​

JS Fiddle demo.

References:

Share:
21,829
lharby
Author by

lharby

I can haz file?

Updated on September 11, 2020

Comments

  • lharby
    lharby almost 4 years

    I have the following html:

    <li><a href="#" filename="prettygirls_1"><img src="large/prettygirls_1.jpg" alt="Pretty Girls Doing Horrid Things" /></a></li>
    <li><a href="#" filename="prettygirls_2"><img src="large/prettygirls_2.jpg" alt="Pretty Girls Doing Horrid Things" /></a></li>
    

    I am trying to write some jquery that will pass the filename property into a variable and then open a large version of the source file in a new window.

    My jquery looks like this (I know this is incorrect):

    $('div#slider ul li a').click(function() {
        var img_to_load = $(this).attr('filename');
        filePath = 'large/'; 
        $('<a href=" ' + filePath + img_to_load + '.jpg' + 'target="_blank"' + '</a>').html();
        //alert (img_to_load);
    });
    

    How do I construct this?

    All the code is actually available here: http://dev.jessicaharby.com/work/tempindex.cfm