Reputation: 11
There is a page with some basic HTML that I cannot touch that looks like this:
<a class="continue-shopping" href="https://someURL">Continue shopping</a>
What I want to do is send the user to a different link when they click on the someURL text link. The user can come to a page containing this HTML from many other pages.
I have tried many hours, but cannot get my JavaScript to recognize a click event for a class associated with hyperlinked text. I could really use some help here. This is the JavaScript code I wrote and which does not work.
window.onload = function() {
prepEventHandler();
}
function prepEventHandler() {
var myClass = document.getElementsByClassName("continue-shopping");
myClass[0].onclick=window.open(document.referrer,"_self");
/* which make my pages go haywire OR THIS -- which also does not work */
myClass[0].addEventListener("click", function() {
window.open(document.referrer,"_self");})
}
It just keeps ignoring the second function, and I am sure I am doing some really basic that is wrong. Again, thanks for any help!
Upvotes: 1
Views: 3246
Reputation: 41143
Apart from preventDefault()
you could also use return false
window.onload = function () {
var myClass = document.querySelector(".continue-shopping")
.onclick = function () {
window.location.href = "http://elsewere.com";
return false;
}
}
Upvotes: 1