preventDefault, make changes and continue routine

716 Views Asked by At

I have a small site with a script that runs a query with mysql and returns me some data, including domains. These domains are generated html links and I want to change in javascript, since I can not access the part of php, but yes to the javascript and css code.

I just want you the code is run when the click event is triggered on a link. I tried to stop the execution by default and make a change, but my code does not open the page. If I remove preventDefault only works in firefox, but I have not chrome. (window.open not use, I want to change the original link).

var domains = document.getElementsByClassName("domain");

for(var x = 0; x < domains.length; x++){
    if(domains[x].addEventListener) {
        domains[x].addEventListener("click", changeLink, "false");
    } else if(domains[x].attachEvent) {
        domains[x].attachEvent("onclick", changeLink);
    }
}

function changeLink(evt){

    var urlOriginal = this.href;

    // If I remove preventDefault, the function runs correctly on firefox but not in chrome
    evt.preventDefault();

    if(urlOriginal != 'http://google.com') {

        urlOriginal = urlOriginal.replace(/http:\/\//g, '');

        evt.stopPropagation();

        this.href = 'http://intodns.com/' + urlOriginal;

        console.log('Okay !');

    }

    return true;
}

I tried several changes but none is running, not really the case.

Does anyone know the cause of malfunction? How I can fix it without window.open?

Thanks

2

There are 2 best solutions below

3
On

try stopPropagation instead

http://api.jquery.com/event.stoppropagation/ - read more about it

0
On

If I understand correctly, you want to redirect the user to a different link, instead of the one that is set in the href attribute.

Once the click is made, nothing will happen if you change the href attribute of the element. What you are looking for is redirecting the user, and this is made possible by modifying the location object which resides on window.

Instead of this line:

this.href = 'http://intodns.com/' + urlOriginal;

Try this:

window.location = 'http://intodns.com/' + urlOriginal;