0

I'm trying to take the function outside the loop and then call it from within, but I'm not sure how to do it.

const links = document.querySelectorAll( 'a' );

for ( let i = 0; i < links.length; i++ ) {

    links[i].addEventListener( 'click', ( event ) => {
        const targetID = '#' === event.currentTarget.getAttribute( 'href' ) ? 'start' : event.currentTarget.getAttribute( 'href' );
        ...rest of the function...
    } );
}

This is what I've tried so far:

const links = document.querySelectorAll( 'a' );

function smoothScrolling( event ) {
    const targetID = '#' === event.currentTarget.getAttribute( 'href' ) ? 'start' : event.currentTarget.getAttribute( 'href' );
    ...rest of the function...
}

for ( let i = 0; i < links.length; i++ ) {

    links[i].addEventListener( 'click', smoothScrolling( event ) );
}

I'm not sure why, but I'm getting the following error: Uncaught TypeError: Cannot read property 'currentTarget' of undefined.

2
  • 4
    links[i].addEventListener( 'click', smoothScrolling); Commented Mar 13, 2019 at 0:57
  • 1
    func() is calling the function. func is referencing/passing the function. Commented Mar 13, 2019 at 1:10

1 Answer 1

1

You've almost got it... The problem is that you're CALLING the function and passing the result. Instead, you just want to pass the function itself, like it was an object. Try this:

const links = document.querySelectorAll( 'a' );

function smoothScrolling( event )
{
     const targetID = '#' === event.currentTarget.getAttribute( 'href' ) ? 'start' : 
     event.currentTarget.getAttribute( 'href' );
     ...rest of the function...
}

for ( let i = 0; i < links.length; i++ )
{
    links[i].addEventListener( 'click', smoothScrolling );
}

By specifying the function without any arguments, it will be passed instead of being called. The way you did it, it is calling the smoothScrolling and then using the result of that, which is not what you want.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks you very much, my friend! That did the trick :) Sometimes I am so tired that I miss the most obvious things Dx

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.