How to focus a popup with javascript without reloading it

Recently I’ve been challenged to focus a popup when clicking on the same link that opened the popup. After some research on google and stackoverflow, I decided to compile the findings into one small tutorial about this issue.

1. I will make a link example that opens a popup:

<a href="javascript:void(0);" onclick="window.open('page_example.html', 'popupexample', 'width=450, height:450');">Open Popup</a>

The problem here is that whenever you click on this link the popup will refresh if already exists. If it doesn’t exist, we all know that it will be created.

Next step is to make a function that will be called when you click on this link.

2. Let’s create the function that opens the popup:


function popupOpen(target_url, window_name){

    window.open(target_url, window_name, 'width=450, height=450');

}

As you can see, this function receives 2(two) params that will help you open flexible popups in the future:

  1. target_url: which, in our example is ‘page_example.html’
  2. window_name: which, in our example is popupexample. Be very careful with the window name, because the Internet Explorer doesn’t accept spaces in it.

3. Now, let’s modify the link to use the function above:

<a href="javascript:void(0);" onclick="popupOpen('page_example.html', 'popupexample');">Open Popup</a>

So now, we have the link the uses the function which creates the popup.

We need to make the function know if the popup already exists so when called, will focus the popup if it does. In order to do this, we will we create an object that will hold every opened popup.

4. Create the object that will hold all the popups and modify the function to insert the popups in it and the focus them:


var popups_holder = new Object();
function popupOpen(target_url, window_name){

    if(typeof(popups_holder[window_name]) == undefined || typeof(popups_holder[window_name]) == 'undefined'){
         var w = window.open(target_url, window_name, 'width=450, height=450');
         popups_holder[window_name] = w;
    }else{
        popups_holder[window_name].focus();
    }

}

Now when you click on the link, if the popup exists in the popups created object, it will be focused without refreshing the content. Otherwise it will be created and added to the popups object.

Basically that’s it. No rocket science, no special effects.

Later on, I will create a page where you can test the code and I will take the tutorial even further, with page reload and other failure points.

Leave a Reply

Your email address will not be published. Required fields are marked *