Matt Beckman Matt Beckman - 6 months ago 3
Javascript Question

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
attribute. This script executes on the keydown of the 'esc' key just fine, but returns
instead of just

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;

instead of just


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 = || '';


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