document.getElementById("img1").addEventListener("click", function(event){
event.preventDefault()
});
I have tried the above JavaScript, which does disable the link, while retaining right and middle button click actions which is what I want.
However, I have many links, each with a dynamically created ID and I cannot figure out how to pass the ID to the above code.
I have tried the following:
HTML:
<a id="img' . $row["idImage"] . '" onClick="passID(this.id)" href="images/img01"><div></div></a>
JavaScript:
function passID(linkId) {
var imgid = linkId;
alert(imgid);
document.getElementById(imgid).addEventListener("click", function(event) {
event.preventDefault()
});
But it doesn't disable the link. I put an alert in and it does return the correct ID of the clicked link but does not disable it so I'm at a bit of a loss on how to proceed from here.
If you're okay with using event handler attributes, simply use
onclick="return false;"
and you're done.If you want to use
addEventListener()
, then you'll need to be able to distinguish the elements that should not be able to redirect. You can use a selector likea[id^="img"]
to select all anchor elements who'sid
attribute starts withimg
.Then you need to select all elements that apply, loop over them, and add the event listener.
Although it would probably be more clean and less error prone to add classes to your anchor tags that you want to prevent from redirecting and select those.