Forum Moderators: open
<a href="https://example.com/some-url?p=someparam" id="myLink">Click to Execute</a>
<script>
const link = document.querySelector("#myLink");
link.addEventListener('click', function (event) {
event.preventDefault(); // this prevents the link from navigating to the next page
const myHref = event.target.getAttribute("href")
console.log('myHref is',myHref)
// do something with the href
})
</script>
<button data-url="https://example.com/some-url?p=someparam" id="myButton">Click to Execute</a>
</script>
const button = document.querySelector("#myButton");
button.addEventListener('click', function (event) {
// you no longer need to prevent anything event.preventDefault(); // this prevents the link from navigating to the next page
const myHref = event.target.getAttribute("data-url")
console.log('myHref is',myHref)
// do something with the href
})
</script>
No I don't want to navigate to the url, just run a JS file that'll use the URL clicked.Is there a reason you can't simply put
<script type = "text/javascript" src = "filename.js"></script>
in the HEAD of the document?
BTW in the second code example do you need this code?
event.preventDefault();
Got a vague idea you no longer need to specify a “type”,