Javascript void 0 ссылка

What Is “javascript:void(0)”—A Complete Guide (Examples)

You may have encountered javascript:void(0) in an HTML document as a href attribute like this:

A common reason why developers use javascript:void(0) trick is to prevent the page from reloading when clicking a link.

This comprehensive guide teaches you:

  • What javascript:void(0) does.
  • How the javascript:void(0) works.
  • And a bunch of examples.

Speaking of examples, I think the best way to learn what javascript:void(0) does is by taking a look at an example first.

Example—Understanding “javascript:void(0)”

If you render this HTML tag, it produces a link that shows an alert when you click it. Feel free to try it below:

When you clicked the link, did you notice how the page refreshed and jumped back to the top? Frustrating, right?

This is where adding javascript:void(0) in the href attribute helps. It prevents the page from refreshing when clicking the link.

Let’s try it! Here’s the same HTML tag you saw above. This time, the href attribute is javascript:void(0):

Below is the link that the above HTML code renders. Feel free to try it again!

This time the page didn’t refresh thanks to using javascript:void(0).

Now you understand what the javascript:void(0) is used. But the reason for such a funky expression might still be unclear to you. If you want to learn what it does, keep on reading!

The javascript:void(0) Complete Breakdown

In this section, you will learn what the expression javascript:void(0) does and why such a funky expression is needed.

The javascript:void(0) expression has two parts:

  1. javascript: — This prefix tells the href attribute to expect JavaScript to be executed.
  2. void(0) — This is the piece of JavaScript code that gets executed.

Let’s take a closer technical look at these two parts.

1. javascript:

If you want to place JavaScript code in an href attribute, you need to use the javascript: prefix! This tells the anchor tag’s href attribute that it should expect some JavaScript code.

Back in the day, specifying the javascript: prefix was a convention for other HTML attributes too. As an example, here’s how you would specify a JavaScript action in the onclick attribute:

Notice that these days adding the javascript: prefix inline event attributes, such as onclick, onsubmit, or onmouseover is unnecessary.

But when you place JavaScript code into an href attribute, you still need to do this! The javascript: prefix tells the href attribute you want to run a JavaScript action instead of refreshing the page.

If you run JavaScript within a href attribute and forget to use the javascript: prefix, the JavaScript code won’t run. This causes the webpage to refresh.

Next, let’s take a look at the actual JavaScript part, that is, the void(0) expression.

2. void(0)

In JavaScript, the void keyword is an operator you can call on a single expression or a value. The void operator evaluates the expression and does not return a value. Instead, it returns undefined.

Using void is useful when an expression produces a value in a place where it shouldn’t. The void operator runs the input expression but returns no value regardless of whether the expression returns a value or not.

For example, consider this piece of JavaScript:

function giveValue() < console.log("Running the function!") return 100 >const x = void(giveValue()) console.log(x)

The output of running this piece of code is:

Running the function! undefined

So even though the giveValue() function returns 100, the void operator neglects that. It surely runs the giveValue() function but doesn’t return a value. That’s why the value of x is undefined instead of 100 when logging into the console.

There are two ways you can call the void operator:

In other words, you can also do it without parenthesis. For instance, in the above expression you could have done this instead:

Anyway, one way to look at the void operator is you can use it to obtain the value of undefined. One of the popular ways to obtain the undefined value is by calling void(0). But you could just as well call void(1000) or void(“test”) to get back undefined.

So after all, javascript:void(0) means “Tell the href attribute to run the following piece of JavaScript code: void(0) instead of changing or refreshing the page.”

Why Not “javascript:undefined” Then?

In the previous section, you learned that javascript:void(0) is just a way to obtain the value undefined. In href attributes, this prevents the site from refreshing when the anchor is clicked.

Now you may wonder, why not just do javascript:undefined instead of javascript:void(0).

In modern browsers, you could indeed replace javascript:void(0) with javascript:undefined.

But the reason why javascript:void(0) is better than javascript:undefined is because, in older browsers, undefined is not a keyword! Instead, it’s a writeable property whose value you can change.

For example, in a browser that doesn’t support JavaScript 1.8.5, the following code:

console.log(undefined); var undefined = 1000; console.log(undefined);

Produces the following output:

You just successfully defined undefined to be 1000! If you now called javascript:undefined in the href attribute, the page would refresh because the JavaScript expression returns 1000 instead of undefined. To avoid this, it’s safer to use javascript:void(0) instead of javascript:undefined.

Summary

That wraps it up for today!

To recap, you learned that javascript:void(0) prevents a page from refreshing when an anchor is clicked. The javascript:void(0) consists two parts:

  • The javascript: prefix that lets the href know you want to run JavaScript instead of opening a URL.
  • The void(0) statement returns undefined which prevents the page from refreshing.

Thanks for reading. Happy coding!

Read Also

Источник

Нужно ли использовать ‘#’ или ‘javascript:void(0)’ в href-атрибуте пустых ссылок

Стоит ли применять JavaScript void 0 ? Если использовать # , и тем самым препятствуя привычной работе ссылок, ( например, для прокрутки к верху страницы ), то приходится указывать и значение return false для функции в событии onclick :

Hey Hey  

Если вместо этого использовать javascript:void , то использовать return false не нужно, так как void(0) – самый миниатюрный скрипт, который расценивается как undefined . То есть:

Тот же эффект, что и при использовании href=»#» , только код с JavaScript void меньше и чище.

JavaScript: void(0)

Когда мы используем JavaScript в навигации, значение return в исполняемом скрипте становится содержимым нового документа, который отображается в браузере. Оператор void превращает значение return value в следующем за ним выражении в return undefined , что и предотвращает исполнение данного события.

Ссылка перенаправляет браузер на текстовую версию результатов, которые расценены как JavaScript . Однако если результатом будет undefined , то браузер останется на той же странице. JavaScript void 0 — что значит? Это миниатюрный скрипт, который определяется как undefined .

Однако javascript:void(0) ; нарушает Content Security Policy ( CSP, политика защиты контента ) у протокола HTTPS эта защита включена. Это помогает выявлять и нивелировать определенные типы атак, включая Cross-Site Scripting ( XSS ), инъекции вредоносных данных.

Следовательно, если вы суеверный разработчик, то пользуйтесь href=»#» вместо javascript:void и не беспокойтесь о нарушении политики защиты.

Href=»#»

Хэш безопаснее в тех случаях, когда у пользователей отключена поддержка JavaScript .

Хотя эту проблему можно легко обойти за счет jQuery :

Можно даже вернуть false в атрибут элемента onclick , и получить тот же эффект:

Несколько рекомендаций напоследок

В href javascript void 0 используется, если нужен четкий и быстрый результат.

href=»#» и предотвращение исполнения события используется тогда, когда не хочется нарушать стандарты JavaScript.

Пожалуйста, оставляйте свои комментарии по текущей теме статьи. За комментарии, подписки, дизлайки, отклики, лайки огромное вам спасибо!

Источник

void operator

The void operator evaluates the given expression and then returns undefined .

Try it

Syntax

Description

This operator allows evaluating expressions that produce a value into places where an expression that evaluates to undefined is desired.

The void operator is often used merely to obtain the undefined primitive value, usually using void(0) (which is equivalent to void 0 ). In these cases, the global variable undefined can be used.

It should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator:

void 2 === "2"; // (void 2) === '2', returns false void (2 === "2"); // void (2 === '2'), returns undefined 

Examples

Immediately Invoked Function Expressions

When using an immediately-invoked function expression, the function keyword cannot be at the immediate start of the statement, because that would be parsed as a function declaration, and would generate a syntax error when the parentheses representing invocation is reached — if the function is unnamed, it would immediately be a syntax error if the function is parsed as a declaration.

function iife()  console.log("Executed!"); >(); // SyntaxError: Unexpected token ')' function ()  console.log("Executed!"); >(); // SyntaxError: Function statements require a function name 

In order for the function to be parsed as an expression, the function keyword has to appear at a position that only accepts expressions, not statements. This can be achieved be prefixing the keyword with a unary operator, which only accepts expressions as operands. Function invocation has higher precedence than unary operators, so it will be executed first. Its return value (which is almost always undefined ) will be passed to the unary operator and then immediately discarded.

Of all the unary operators, void offers the best semantic, because it clearly signals that the return value of the function invocation should be discarded.

void function ()  console.log("Executed!"); >(); // Logs "Executed!" 

This is a bit longer than wrapping the function expression in parentheses, which has the same effect of forcing the function keyword to be parsed as the start of an expression instead of a statement.

(function ()  console.log("Executed!"); >)(); 

JavaScript URIs

When a browser follows a javascript: URI, it evaluates the code in the URI and then replaces the contents of the page with the returned value, unless the returned value is undefined . The void operator can be used to return undefined . For example:

a href="javascript:void(0);">Click here to do nothinga> a href="javascript:void(document.body.style.backgroundColor='green');"> Click here for green background a> 

Note: javascript: pseudo protocol is discouraged over other alternatives, such as unobtrusive event handlers.

Non-leaking Arrow Functions

Arrow functions introduce a short-hand braceless syntax that returns an expression. This can cause unintended side effects by returning the result of a function call that previously returned nothing. To be safe, when the return value of a function is not intended to be used, it can be passed to the void operator to ensure that (for example) changing APIs do not cause arrow functions’ behaviors to change.

.onclick = () => void doSomething(); 

This ensures the return value of doSomething changing from undefined to true will not change the behavior of this code.

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Apr 5, 2023 by MDN contributors.

Your blueprint for a better internet.

MDN

Support

Our communities

Developers

Visit Mozilla Corporation’s not-for-profit parent, the Mozilla Foundation.
Portions of this content are ©1998– 2023 by individual mozilla.org contributors. Content available under a Creative Commons license.

Источник

Читайте также:  Javascript files utf 8
Оцените статью