Question

What's the best way to combine two strings

String 1:

<a href="javascript:myFunc();" onclick="alert('myFunc executed')">Click here</a>

and String 2:

<a href="http://google.com">click here</a>

so that: myFunc() executed; alert appears; once alert is clicked, the page is being redirected to http://google.com

I'm asking about the most correct way to do that.

Thank you.

Was it helpful?

Solution 3

Try this :

<a href="javascript:void(0)" onclick="alert('myFunc executed');myFunc();window.location='http://google.com'">Click here</a>

explanation :

javascript:void(0) Is for u to see a link.

OTHER TIPS

Use:

<a href="http://google.com" onclick="myFunc(); alert('myFunc executed'); return true">click here</a>

Your approach is very "obtrusive" JavaScript. Nowadays, folks tend to recommend an Unobtrusive JavaScript approach.

<a id="myLink" href="http://google.com" data-message="myFunc executed">Click Here</a>

Note that there is no JavaScript in the HTML.

Then, in your script module, you can initialize as below (I use jQuery for brevity):

$("#myLink").click(function(){
    var href = $(this).attr("href"),
        message = $(this).attr("data-message");
    myFunc();
    alert(message);
    window.location.href = href;
});

This technique leaves your HTML clean and allows you to perform multiple actions on the click event.

Finally, if you are not familiar with the concept of modules in JavaScript, take a look at Douglas Crockford's book JavaScript, The Good Parts.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top