2

I used to have code that uses:

$(document).on('click', 'a[href^="http"]', () => {});

To intercept link clicks. For complicated-to-explain reasons, I had to move this code somewhere before jQuery is loaded. How can I write this code in pure JavaScript?

2
  • 1
    I think there is no way to ask jQuery to bind an event handler before it is loaded into browser env. If there is a solution I would like to know Commented Feb 22, 2017 at 3:22
  • I don't specifically mean using jQuery; I'd like to cut jQuery out of it if at all possible, and do this using just JavaScript. Commented Feb 22, 2017 at 3:25

1 Answer 1

2

Base on the comments above, you can convert the event binding jQuery code above to something below using vanila JavaScript,

var links = document.querySelector('a[href^="http"]');
links.forEach(function(link) {
    button.addEventListener("click",function(e){
       // handling logic
    }, false);
} )

Code above bind event handler to every a element which can be expensive.

Create an event delegate

Add an event handler to the document and see if the target is the link you want,

document.addEventListener("click", function(e) {
    // check the target has an attribute of `a[href^="http"]`
    if(e.target && e.target.nodeName == "a") {

    }
});

Code above using event bubbling to catch click event inside the document.

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

1 Comment

I prefer the second suggested solution as I believe it's more analogous to what I have, and also works for links added after the code runs. Thanks!

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.