redteamwynns
redteamwynns

Reputation: 95

How do I use an HTML DOM Event on new tab load?

I have a custom homepage which loads upon opening a new tab in Firefox. I want to reposition the caret on load but I can't find the event which will handle this on a tab load.

The window.onpageshow and window.onload events do not work when the page is loaded from a new tab event, but work fine on a refresh or similar. Throwing the event in with an element has no effect either, such as:

<body onload="blah()">

Is there a way to call my cursor reposition function when the page loads in this manner? Edit: Here is the setCursor code

<script type="text/javascript">
window.onload = ready;
function ready()
{
    setCursor(document.getElementById('sbar'), 0, 0)
};
</script>


<script type="text/javascript">
function setCursor(el, st, end) 
{
    if (el.setSelectionRange) {
        el.focus();
        el.setSelectionRange(st, end);
    } else {
        if (el.createTextRange) {
            range = el.createTextRange();
            range.collapse(true);
            range.moveEnd('character', end);
            range.moveStart('character', st);
            range.select();
        }
    }
};
</script>

Upvotes: 3

Views: 1182

Answers (1)

Ismail RBOUH
Ismail RBOUH

Reputation: 10460

You have several options if you want to hook the page load (tab load):

The first option is using onload event:

window.onload = ready;
function ready()
{
    alert("Hi !");
};

Demo: http://jsfiddle.net/vy79v39k/

The second option is placing your javascript at the very end of the body:

<body>
  ...
  <script type="text/javascript">
    ready();
  </script>
</body>

The third option is using jQuery (which I vote for!) :

jQuery(function($) {
    //Your code here
});

Or:

jQuery(document).ready(function($) {
    //Your code here
});

Upvotes: 1

Related Questions