1

I'm using the CSS3 :target pseudo selector to create in-page navigation without reloading the page. This works really well!

But I have a problem, I need to reset the forms in a page when the page targetted, how can I know if an element is targetted with javascript? Like element.ontarget = function();

Or maybe something like element.ondisplaychange -> element.oncsschange?

BETTER UPDATE:

var hashcache = document.location.hash;
window.onhashchange = function() {
    if(hashcache != document.location.hash) {
        $(hashcache + ' form input').each(function() {
            $(this).val('');
        });
        hashcache = document.location.hash;
    }
}

UPDATE:

$('a[href^="#"]').each(function() {
    this.onclick = function() {
        href = $(this).attr('href');
        if(href != document.location.hash) {
            $(href + ' form input').each(function() {
                $(this).val('');
            });
        }
    }
});
1
  • onfocus and onblur won't work Commented Nov 23, 2010 at 11:28

3 Answers 3

3

If you're using JavaScript for the navigation, I'd suggest just adding the check to that. But I'm guessing from your question you're not, that you're instead using plain links with just anchors (e.g., <a href='#target1'>, <a href='#target2'>, ...).

A couple of options:

Use a Timer

In that case, basically what you want to do boils down to receiving an event when the anchor changes. As far as I know, and as far as the people answering this other question on StackOverflow in January knew, you can only do that with a timer. (Edit: But see ide's comment below, there's a new hashchange event we'll be able to use soon!) E.g.:

(function() {
    var lastHash = window.location.hash;
    setTimeout(function() {
        var newHash = window.location.hash;
        if (newHash !== lastHash) {
            lastHash = newHash;
            // Trigger your target change stuff
        }
    }, 250);
})();

That checks for changes every quarter second. That may not be enough for you, you could lower the 250, but beware running too much and slowing everything else down.

But as you say below, this is inefficient.

Hook the Link's click event

Since you're already using JavaScript on the page, I'd recommend using handlers on your links instead. If you add a class name or something to them (I bet they already have one; I'll us "navlink" below), this is easily set up:

var links, index, link;
links = document.getElementsByTagName('a');
for (index = 0; index < links.length; ++index) {
    link = links.item(index);
    if ((" " + link.className + " ").indexOf(" navlink ") >= 0) {
        hookEvent(link, 'click', clickHandler);
    }
}

function clickHandler() {
    // `this` will reference the element that was clicked
}

// The 'hook' function:
var hookEvent = (function() {
    var elm = document.createElement('a');

    function hookEventViaAttach(element, event, handler) {
        element.attachEvent("on" + event, handler);
    }
    function hookEventViaAddListener(element, event, handler) {
        element.addEventListener(event, handler, false);
    }
    function hookEventDOM0(element, event, handler) {
        element["on" + event.toLowerCase()] = handler;
    }

    if (elm.attachEvent) {
        return hookEventViaAttach;
    }
    if (elm.addEventListener) {
        return hookEventViaAddListener;
    }
    // I usually throw a failure here saying not supported, but if you want,
    // you can use the DOM0-style stuff.
    return hookEventDOM0;
})();

A lot of the complication of the above goes away if you use a library like jQuery, Prototype, YUI, Closure, or any of several others.

For instance, the jQuery version:

$("a.navlink").click(clickHandler);
function clickHandler() {
    // `this` will reference the element that was clicked
}

The Prototype version:

$$("a.navlink").invoke('observe', 'click', clickHandler);
function clickHandler() {
    // `this` will reference the element that was clicked
}
Sign up to request clarification or add additional context in comments.

7 Comments

I know that, that's how I did it before. But it's not very efficient to use a timer. I'm searching for a alternative way to do this.
@Stijntjhe: Good luck with that. :-) I don't think you'll find a reliable, cross-browser one. You're probably better off hooking up an event handler to the links.
Woot nice idea :) Did not thought about that xD
@Stijntjhe: LOL, as you commented and accepted, I was adding an example FWIW. Glad that helped.
It's not the best solution for the problem at hand, but if you ever need to track changes to the URL #fragment, there is a new "hashchange" event supported in all of the major browsers including IE8.
|
0

The onfocus property returns the onFocus event handler code on the current element.

event handling code = element.onfocus

The onblur property returns the onBlur event handler code, if any, that exists on the current element.

element.onblur = function;

Example: http://jsfiddle.net/g105b/cGHF7/

<html>

<head>
    <title>onblur event example</title>

    <script type="text/javascript">

    var elem = null;

    function initElement()
     {
     elem = document.getElementById("foo");
     // NOTE: doEvent(); or doEvent(param); will NOT work here.
     // Must be a reference to a function name, not a function call.
     elem.onblur = doEvent;
     };

    function doEvent()
     {
     elem.value = 'Bye-Bye';
     alert("onblur Event detected!")
     }
    </script>

    <style type="text/css">
    <!--
    #foo {
    border: solid blue 2px;
    }
    -->
    </style>
</head>

<body onload="initElement()";>
    <form>
    <input type="text" id="foo" value="Hello!" />
    </form>

    <p>Click on the above element to give it focus, then click outside the
    element.<br /> Reload the page from the NavBar.</p>

</body>
</html>

1 Comment

It's not an input in my case, it's a block element article Thanks for the answer anyways.
0

Maybe youcan just code like this

function hashChangeEvent(){
    $(window.location.hash)//do something
}
window.onhashchange = hashChangeEvent;//when hash change
hashChangeEvent();//first load

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.