Force the mailto tab to do the correct function after the DOM has loaded

My site has my email address that people started using to send spam emails. So I decided that I needed to update the security for the email addresses on the website.

I changed the website that you need to click on the email to view it (or click on it to open the email client).

The raw HTML looks like this:

<a href='#' address='mailto:person(at)example(dot)co(dot)za'>Click here to view</a>

      

JavaScript looks like this and runs on window.load

$("a[address]").click(function (event) {
        event.preventDefault();
        var address = $(this).attr("address");
        while(address.indexOf("(at)") !== -1){address = address.replace("(at)", "@")}
        while(address.indexOf("(dot)") !== -1){address = address.replace("(dot)", ".")}
        $(this).attr("href", "mailto:" + address);
        $(this).html(address);
    })

      

The user clicks on the tag a

. The email address is displayed correctly. But if I click on it again (remember the href is now mailto:

) it doesn't open the mail client.

How do I force the browser to update the on-click start event for a tag mailto

.

+3


source to share


3 answers


Well I found a solution. I added the following code to the end of the JS:

$(this).unbind("click");

This is because the click is still anchored after the tag is clicked the first time. It would also be interesting to know if there is a way to "force" the mail client to open using JS.



The new JS code looks like this:

$("a[address]").click(function (event) {
        event.preventDefault();
        var address = $(this).attr("address");
        while(address.indexOf("(at)") !== -1){address = address.replace("(at)", "@")}
        while(address.indexOf("(dot)") !== -1){address = address.replace("(dot)", ".")}
        $(this).attr("href", "mailto:" + address);
        $(this).html(address);

       // this is the new code
        $(this).unbind("click");
    })

      

+1


source


If you want to click on a link to trigger a connection, don't talk event.preventDefault();

.



+2


source


You can check if an element has an attribute and remove it after clicking it and then only preventDefault

when the attribute is present.

$("a[address]").click(function (event) {
    if($(this).attr('address')){
        event.preventDefault();
        var address = $(this).attr("address");
        while(address.indexOf("(at)") !== -1){address = address.replace("(at)", "@")}
        while(address.indexOf("(dot)") !== -1){address = address.replace("(dot)", ".")}
        $(this).attr("href", "mailto:" + address);
        $(this).html(address);
        $(this).removeAttr('address');
    }
});

      

0


source







All Articles