Matthew Beckman
Matthew Beckman

Reputation: 1722

Why & Where Is This Script Returning Undefined?

I'm attempting to use the following code to append a # (hashtag) to the URL to close lightboxes that were built utilizing the CSS :target attribute. This script executes on the keydown of the 'esc' key just fine, but returns example.com/#undefined instead of just example.com/#.

I apologize for being a JS beginner, but how do I define it to return just the single #?

$( document ).on( 'keydown', function ( e ) {
    if ( e.keyCode === 27 ) {
        var href = this.href;
        window.location.hash = href;
    }
});

Returns #undefined instead of just #.

Upvotes: 0

Views: 55

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

The answer is, in your handler this refers to the document object which does not have href property value. So your href variable has the value undefined thus the hash is updated as undefined.

Now a solution to the problem will depend on details that is not shared in the question like how is the html looks like, when and how it is suppose to work etc

You you want to get the href of the target element, then you can use

var href = e.target.href || '';

or

var href = $(e.target).closest('[href]').attr('href') || '';

Upvotes: 2

Related Questions