简体   繁体   中英

How to always bring a window to the front with Javascript?

Here is a link in my page (MAIN) :

<a href="log_details.jsf#MyAnchor" target="log">View details</a>

If no window is alredy opened, a new one appears (let's call it LOG) and is bringed on top pointing at the anchor.

If LOG stays opened and user decides to go back to MAIN for clicking on another link like this

<a href="log_details.jsf#MyAnchor2" target="log">View details</a>

The position in LOG is moved to MyAnchor2 but LOG is not bringed to top.

How can I make LOG appears on top any time the user click on a link similar to :

<a href="log_details.jsf#MyAnchorXXX" target="log">View details</a>

If the window is already open and is known by the variable log in your Javascript, you should be able to call log.focus() on the window to bring it to the front.

Edit:

When you use the target attribute, it give the window a 'name'. This name is separate from Javascript variables, though. So in the instance where target="log" , there is no corresponding variable named log to reference with the .focus() function.


function logLinks(){
    //Get every A tag
    var links = document.getElementsByTagName('a');
    //Iterate through the elements and...
    for(i=0; i<links.length; i++){
        //If the element has a class of 'log'
        if(links[i].className=='log'){
            //Clone it
            var dup = links[i].cloneNode(true);
            //Strip move the href elsewhere
            dup.id=dup.href; 
            dup.href='';
            //Add a click listener
            dup.addEventListener('click', function(){openLog(this.id);}, false);
            //Replace the existing element on the page
            links[i].parentNode.replaceChild(dup, links[i]);
        }
    }
}

function openLog(link){
    //Open a window and give it focus
    var wh = window.open(link, 'logWindow');
    wh.focus();
}

//Run this function on page load
document.addEventListener("DOMContentLoaded", logLinks);

The above code will go through the page and replace any a tags that are set to have the log class with a version that opens a window to the relevant href of that link and then does focus on the resulting window.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM