1

I open a window with jQuery. Then I want to close it but window.close or nameOfTheWindow.close does not work. How should I do it?

I have the example here: http://jsfiddle.net/D99Gk/2/

HTML:

<a class="open" href="http://www.google.com" target="_blank"> open window 1 </a>
<br><br>    
<a class="close" href="#"> close window 1</a>

JQUERY:

$(function(){
 //I give the window the name window1 and I open it:
    $('.open').click(function(e){
        e.preventDefault();
        window.open("","window1","width=400, height=400");
    });

    $('.close').click(function(){
        // I tried and does not work:
        // window.close();
        // window1.close();
    });
})
2
  • you can't and that's the answer, but if I try to put that in an answer, I'm sure to be downvoted ;) Commented May 3, 2014 at 13:19
  • 3
    You need to save the reference returned from window.open(), which allows you to access that "window's" object. Commented May 3, 2014 at 13:20

3 Answers 3

5

Like this:

$(function(){    
    var popup;
    $('.open').click(function(e){
        e.preventDefault();
        popup = window.open("","window1","width=400, height=400");
    });

    $('.close').click(function(){
        if(popup) popup.close();
    });
});

DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

The if is a nice touch.
I do not understand why the conditional? If the window is not open and you click the close window, nothing happens
@Nrc Check your console, there is error if not using the if check because undefined hasn't got a close() method
2
$(function(){    
    var winref;

    $('.open').click(function(e){
        e.preventDefault();
        winref = window.open("","window1","width=400, height=400");
    });

    $('.close').click(function(){
        winref.close();
    });
});

http://jsfiddle.net/D99Gk/3/

Note: As A. Wolff does, you should check if winref:

$('.close').click(function(){
    if (winref) winref.close();
});

This is to prevent an error from first clicking the close link before winref exists, or after it is closed.

Comments

1

Try this:

$(function(){    
var wi = null;
    $('.open').click(function(e){
        e.preventDefault();
        wi = window.open("","window1","width=400, height=400");
    });

    $('.close').click(function(){
        wi.close();     
    });
})

Demo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.