HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Custom event to match CSS :target pseudo-class

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
targetcssmatchcustompseudoclassevent

Problem

The following code makes jQuery trigger a new target event on elements when they become the target of the fragment identifier.

For a very basic example, the following target event handler:

$('.question-page .answer').on('target', function highlight(){
    $(this).stop().css({'background':'orange'}).animate({'background':'white'}, 300);
});


…Would emulate what following CSS would express with the :target pseudo-selector:

.question-page .answer:target {
    animation: 0.3s highight;
}

@keyframes highlight {
    from {
        background: orange;
    }
    to {
        background: white;
    }
}


The plugin code follows. My concerns are mostly on the sanity of the event triggering, particularly the handleHashChange and ignoreHashChange functions which attempt to mitigate a click triggering a target event for an element, and that same click bubbling up to cause a hashchange (which without this code, would trigger another target event — although it is holistically the same target event).

I'm also interested in style and integration with jQuery API — I have doubts as to whether passing the originalEvent as a second argument is a good idea or not (should I just fold that event's preventDefault into the target event?), particularly in the case of the fake ready event constructor.

Any other criticism more than welcome.

```
void function jQueryTargetEventClosure($){
// Returns a 'ready' event to pass when 'target' is triggered by initial hash state on document load:
// Prevents critical failure when attempting to invoke event methods on 'target' handlers
var readyEventConstructor = (function readyEventConstructorClosure() {
var history = window.history;
var historySupport = history.replaceState && typeof history.replaceState === 'function';

return function readyEventConstructor() {
var location = window.location;
var readyEvent = $.Event( 'ready' );

Solution

to start with a terrible pun; I would avoid void where possible,
history.replaceState( '', '', location.href.split( location.hash )[ 0 ] ); makes more sense to me. Also for your return statements I would rather see

return link.hash ?  link.href.split( link.hash )[ 0 ] : link.href;


Furthermore, it seems that a lot of your code could be replaced with jQuery's event.stopPropagation(), am I missing something?

Other than that the code is very well documented, and teaches the reader some new tricks.

Code Snippets

return link.hash ?  link.href.split( link.hash )[ 0 ] : link.href;

Context

StackExchange Code Review Q#29214, answer score: 2

Revisions (0)

No revisions yet.