seymar
seymar

Reputation: 4063

Do something on :target with javascript

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('');
            });
        }
    }
});

Upvotes: 1

Views: 1789

Answers (3)

Defims
Defims

Reputation: 243

Maybe youcan just code like this

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

Upvotes: 0

T.J. Crowder
T.J. Crowder

Reputation: 1074445

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
}

Upvotes: 3

Greg
Greg

Reputation: 21909

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>

Upvotes: 0

Related Questions