Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (20.3k points)

The following are two methods of building a link that has the sole purpose of running JavaScript code. Which is better, in terms of functionality, page load speed, validation purposes, etc.?

function myJsFunc() {

    alert("myJsFunc");

}

<a href="#" onclick="myJsFunc();">Run JavaScript Code</a>

or

function myJsFunc() {

    alert("myJsFunc");

}

 <a href="javascript:void(0)" onclick="myJsFunc();">Run JavaScript Code</a>

1 Answer

0 votes
by (40.7k points)

It's mostly preferred to use javascript:void(0).

Three important reasons for the use of # amongst a team of developers inevitably leads to some using the return value of the function called like this:

function doSomething() {

    //Some code

    return false;

}

Three reasons are as follows:

1. The first reason is that the developer may forget to use return doSomething() in the onclick and just use doSomething().

2. Another reason to avoid # is that the final return false; it will not get executed if the called function throws an error. Therefore, the developers have to handle any error appropriately in the called function.

3. 3rd reason is that there are cases where the onclick event property is assigned dynamically. 

It's preferred to call the function or assign it dynamically without having to code the function specifically for one method of attachment or another.

Therefore, my onclick (or on anything) in HTML markup looks this way:

onclick="someFunc.call(this)"

OR

onclick="someFunc.apply(this, arguments)"

This line of code javascript:void(0) avoids all of the above restrictions.

You can use 

href="#"

and make sure onclick always contains return false; at the end, and also any called function does not throw an error and if you attach a function dynamically to the onclick property make sure that as well as not throwing an error it returns false.

OR

Try using the code given below:

href="javascript:void(0)"

The above code is easy to use.

Related questions

0 votes
1 answer
asked Sep 5, 2019 in Web Technology by Tech4ever (20.3k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 13, 2019 in SQL by Tech4ever (20.3k points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...