Jacques Koekemoer
Jacques Koekemoer

Reputation: 1414

Force mailto tag so it executes correct function after DOM load

My website has my email address on which people started using to send spam mails to. So I decided that I need to upgrade security for email addresses on the website.

I changed the website that you have to click on an email address in order to view it (or to click on it to open the mail client).

The unprocessed HTML looks like this:

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

The JavaScript looks like this and is executed 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 a tag. The email address displays correctly. But if I click it again (remember that the href is now mailto:) it does not open the mail client.

How can I force the browser to update the initial on-click event for a mailto tag.

Upvotes: 3

Views: 428

Answers (3)

Pindo
Pindo

Reputation: 1625

You can check if the element has an attribute and remove it once it has been clicked, 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');
    }
});

Upvotes: 0

Jacques Koekemoer
Jacques Koekemoer

Reputation: 1414

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 bound after the tag is clicked the first time. It would be interesting still to know if there is a way to "force" open the mail client 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");
    })

Upvotes: 1

Quentin
Quentin

Reputation: 943579

If you want clicking on the link to cause the link to be followed, don't say event.preventDefault();.

Upvotes: 2

Related Questions