Hi this may be unusual, but I need to expand this code to a more readable form so I can undertsand what it’s doing, then I can maybe expand on the code to make it do what I need it to do. Here’s the code: in full (taken from here)
$(function(){
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('.article a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
The specific line I dont understand is this one:
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
This is just unreadable to me at my stage of development. I’d like to learn though.
I mean, i get what it’s doing 100%… but i dont know how to affect the parent of “that” with this kind of code, I dont know where i’d put “parent”?
This
is a horrible line of code which uses the ternary (
?:) operator to pick a function to call.In long hand it would be:
The original code takes advantage of the fact that
$(this).foois the same as$(this)[foo], sothat.foois the same asthat[foo], sothat.foo(args)is the same asthat[foo](args)and then to further complicate things, they made
fooa conditional expression!